📖 Intro to jQuery
JavaScript Libraries
JavaScript libraries are a collection of pre-written JavaScript functions that can be used in a web page to perform common tasks. These libraries eliminate the need to code it yourself in native JavaScript. Some popular JavaScript libraries include:
- jQuery
- YUI (Yahoo User Interface)
- Dojo Toolkit
- Mootools
- Prototype
jQuery
jQuery is a popular open-source JavaScript library written by a group from MIT. This library is open-source and friendly to web designers. It works from a relatively small size of reliable and well-tested options. It is supported by a large developer community and includes plug-ins to expand the options and applications.
Adding jQuery to your page
There are 2 methods for adding jQuery to your web pages. The first and sometimes easiest is to link to a CDN server. The advantages are that you don't have to download and host on your server which can deliver faster response times and provide the latest updates. Some disadvantages are that you have to be connected to Internet to access the online libraries. This is generally a good idea unless you have an isolated application not connected to the Internet.
CDN Method
To use the CDN method, you must add a src link in the head section of your html page from one of the CDN repositories. You can choose any one of these you prefer. They should be identical by version.
- jQuery CDN
-
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
- Google CDN
-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
- Microsoft CDN
-
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.5.1.min.js"></script>
- Find the latest version by visiting
- http://docs.jquery.com/Downloading_jQuery.
Local Method
If you prefer, you can download to your own server. The advantages are that your pages will continue to work if CDN servers are down. The disadvantage are increased load on your server and possibly increased download times. You will also be responsible for updates to the code residing on your server. These disadvantages may become necessary if you need a customized jQuery library. If you still want to host your own version, download latest version of jQuery. Then, right-click on a minified version of latest release and save a copy for use on your website.
Once you have downloaded and installed a local copy of the jQuery library, you now need to add code to your page to tell the browser where to find the appropriate version of jQuery to support the code. Use a simple src link <script src="js/jquery-3.1.1.min.js"></script>
to the jQuery source file.
Add JavaScript code to use jQuery after the link to the jQuery library
Whichever method you choose to reference the jQuery libraries, you will now need to add code to your html file to access the jQuery libraries and any local JavaScript code. Make sure your local JavaScript file comes after the jQuery library file reference. Make sure all JavaScript references come after the css.
<!-- HTML -->
<!-- Place this in the head section of your html file after the css links -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="js/localjs.js"></script>
If you want to use the local jQuery option, just edit the src attribute above to point to the local version. You will also have to edit the src attrubite of the local JavaScript file to point to the location of the local file.
In order to run the jQuery, you will have to add it to your html page inside the normal <script></script>
tags or add a it to the external JavaScript file like you would any other JavaScript code. Again, the best practice is to include this in an external JavaScript file.
You should wrap your jQuery code in the $(document).ready(function() {});
function because many of the methods used by jQuery will rely on certain html elements from the html code. If the page hasn't fully loaded when the jQuery runs, jQuery may fail to find the required elements and produce errors. Using the function as shown below ensures the page html has fully loaded before jQuery runs.
/* JavaScript */
// place this in your external JavaScript file
$(document).ready(function() {
console.log('Ready!'); // debug to verify jQuery working. load page and check the console log (F12)
// jQuery function calls go here...
});
Document Object Model
The DOM allows JavaScript to communicate with elements on a web page, the browser window, etc. It includes all html elements, attributes and relationships on a web page as well as the text. Each individual element, tag or text is called a node. The DOM is represented as a tree-like structure with branches. More specifically, the DOM elements are referred to using common family tree descriptions. For example, nested elements are called child elements and so on.
To select an element using JavaScript:
document.getElementById('idname')
to get a specific tag on a page with an iddocument.getElementByTagName('elementname')
to get all tags of the same type on a page
To select an element using jQuery, use $('selector')
where 'selector' can be:
- an element:
$('h1')
gets all the h1 tags on a page - an id
$('#idname')
gets the element with id="idname" - a class
$('.classname')
gets all elements with class="classname" - descendent selectors
$('#idname a')
gets all a elements within an element with id="idname" - child selectors:
$('blockquote > img')
gets img tags that are child elements of a blockquote - adjacent siblings:
$('div + h3')
gets all h3 elements that immediately follow a div element
To select elements with a specific attribute:
$('img[alt]')
gets all img tags with an alt attribute regardless of value$('img[width="100"])
gets all img tags with width="100" attribute$('img[alt^="thumbnail"])
gets all img tags with an alt attribute value that starts with "thumbnail"$('img[alt$="thumbnail"])
gets all img tags with an alt attribute value that ends with "thumbnail"$('img[alt*="thumbnail"])
gets all img tags with an alt attribute value that contains "thumbnail" anywhere within it
Using filters based on characteristics $(selector:filter)
where selector can be an element, id or class and filter can be:
:even
and:odd
select every other element in a group:first
and:last
select the first or last element in a group:not
selects elements that do not match the selector type:has
selects elements that contain another selector:contains
selects elements that contain specific text:hidden
selects elements that are hidden:visible
selects elements that are visible
Getting and Setting Page Content
Use #getAndSet to modify section heading.
- .html()
- retrieve html from a selection:
$('selector').html();
- replace content in a selection:
$('selector').html("replacement content");
- .text()
- works like html() but treats all content as text including html entities.
- retrieve text from a selection:
$('selector').text();
- replace text content in a selection:
$('selector').text("replacement text");
- .append()
- adds html as last child element of the selected element (just before the closing tag)
$('selector').append("content to append");
- .prepend()
- adds html as first child element of the selected element (just after the opening tag)
$('selector').prepend("content to prepend");
- .before()
- adds html before the selected element's opening tag
$('selector').before("content to add");
- .after()
- adds html after the selected element's closing tag
$('selector').after("content to add");
- .remove()
- completely removes the selected element from the page
$('selector').remove();
- .replaceWith()
- completely replaces the selected element
$('selector').replaceWith("replacement content");
Getting and Setting Tag Attributes
- .addClass()
- adds a class to the selected element:
$('selector').addClass("classname");
- leaves existing classes there as well
- .removeClass()
- removes the specified class from the selected element:
$('selector').removeClass("classname");
- .toggleClass()
- adds a class to the selected element if it does not exist, removes it if it does exist:
$('selector').toggleClass("classname");
- .css()
- to retrieve the value of a CSS property:
$('selector').css('cssproperty');
- to change the value of a CSS property:
$('selector').css('cssproperty', 'value');
- .attr()
- to retrieve the value of an attribute:
$('selector').attr('attribute');
- to change the value of an attribute:
$('selector').attr('attribute', 'value');
- .removeAttr()
- completely removes an attribute from a tag:
$('selector').removeAttr('attribute');
To retrieve the value of multiple CSS properties at once.
chaining
$('selector').css('cssproperty1', 'value1')
.css('cssproperty2', 'value2')
.css('cssproperty3', 'value3')
. . .;
object literal
$('selector').css({
'cssproperty1': 'value1',
'cssproperty2': 'value2',
'cssproperty3': 'value3',
. . .
});
To modify multiple elements on a page.
each()
function loops through each item in a selection and executes custom JavaScript code.
$('selector').each(function() {
custom JavaScript code
});
Below is an example of dynamically creating a footer nav menu from information contained in the aside element of a web page. Most of the html and JavaScript code has been removed for brevity, but you can view the entire working example at https://2learnweb.brookhavencollege.edu/profherd/javascript/examples/jquery-intro-examples/jquery-intro-example.html.
Example
<!-- HTML -->
<aside>
<p class="logo" id="mavericks">
<a href="http://www.nba.com/mavericks/" id="mavslogo">
<img src="mavericks_logo.png" alt="Dallas Mavericks Logo" title="Dallas Mavericks">
<br>Dallas Mavericks
</a>
</p>
<p class="logo" id="cowboys">
<a href="http://www.dallascowboys.com/" id="cowboyslogo">
<img src="cowboys_logo.png" alt="Dallas Cowboys Logo" title="Dallas Cowboys">
<br>Dallas Cowboys
</a>
</p>
<p class="logo" id="rangers">
<a href="http://texas.rangers.mlb.com" id="rangerslogo">
<img src="rangers_logo.png" alt="Texas Rangers Logo" title="Texas Rangers">
<br>Texas Rangers
</a>
</p>
<p class="logo" id="stars">
<a href="http://stars.nhl.com/" id="starslogo">
<img src="stars_logo.png" alt="Dallas Stars Logo" title="Dallas Stars">
<br>Dallas Stars
</a>
</p>
</aside>
<footer>
<nav id="footnav"></nav>
<hr>
<p>Programming with JavaScript Example</p>
</footer>
$(this)
keyword refers to the element that is calling the anonymous function. Use it in place of the selector inside the custom code.
/* JavaScript */
$(document).ready(function() {
console.log('Ready!'); // debug to verify jQuery working. load page and check the console log (F12)
// jQuery function calls go here...
// custom 'each' function to pull the links from the sidebar to create a navigation bar in the footer
// $('aside a') selects all a elements in the aside element
$('aside a').each(function() {
// gets the href value and the text value for each aside a element and stores in variables
teamlink = $(this).attr('href');
teamname = $(this).text();
// adds a node in the #footnav navigation area in the footer for each link by appending a node
$('#footnav').append(`<a href="${teamlink}">${teamname}</a>`);
})
});