jQuery is a JavaScript library that streamlines the creation of dynamic behavior with predefined methods for selecting and manipulating DOM elements. It offers a simplified approach to implementing responsiveness and requires fewer lines of code to assign behaviors to DOM elements than traditional JavaScript methods.
//Selecting DOM elements and adding an event listener in JSconst menu = document.getElementById('menu');const closeMenuButton = document.getElementById('close-menu-button');closeMenuButton.addEventListener('click', () => {menu.style.display = 'none';});//Selecting DOM elements and adding an event listener in jQuery$('#close-menu-button').on('click', () =>{$('#menu').hide();});
JavaScript code runs as soon as its file is loaded into the browser. If this happens before the DOM (Document Object Model) is fully loaded, unexpected issues or unpredictable behaviors can result.
jQuery’s .ready()
method waits until the DOM is fully rendered, at which point it invokes the specified callback function.
$(document).ready(function() {// This code only runs after the DOM is loaded.alert('DOM fully loaded!');});
jQuery objects are typically stored in variables where the variable name begins with a $
symbol. This naming convention makes it easier to identify which variables are jQuery objects as opposed to other JavaScript objects or values.
//A variable representing a jQuery objectconst $myButton = $('#my-button');
jQuery is typically imported from a CDN (Content Delivery Network) and added at the bottom of an HTML document in a <script>
tag before the closing </body>
tag.
The jQuery <script>
tag must be listed before linking to any other JavaScript file that uses the jQuery library.
<html><head></head><body><!-- HTML code --><!--The jQuery library--><script src="https://code.jquery.com/jquery-3.3.1.min.js"></script><!--Site-specific JavaScript code using jQuery--><script src="script.js"></script></body></html>