Day 1: Introduction to jQuery: Selectors, Events, Effects

Day 1: Introduction to jQuery: Selectors, Events, Effects

Day 1: Introduction to jQuery: Selectors, Events, Effects

Section 1: Introduction to jQuery (1 hour)

  1. What is jQuery? jQuery is a fast, small, and feature-rich JavaScript library. It was released in January 2006 by John Resig, a notable figure in the field of web development. The core purpose of jQuery is to simplify the client-side scripting of HTML. jQuery achieves this by wrapping many of the tasks that require many lines of JavaScript code into methods that you can call with a single line of code. These methods can handle everything from event handling and animation to AJAX interactions and manipulation of the HTML DOM. At its heart, jQuery is designed to simplify JavaScript and make it more accessible to non-programmers. It is open-source, free to use, and is incorporated into millions of websites worldwide. Furthermore, jQuery has a robust and vibrant community, which leads to regular updates, plentiful resources, and third-party plugins to extend its functionality.
  2. Brief History jQuery was first announced at BarCamp NYC by John Resig in January of 2006. Since then, it has seen multiple versions, each improving on the previous one. Over the years, jQuery has become the de facto library for simplifying JavaScript and HTML document traversal and manipulation, event handling, and animation on the client side, with an emphasis on web standards.
  3. Importance and Use Cases jQuery holds immense importance in the world of web development. It can manipulate HTML documents, handle events, create animations, and perform AJAX calls with minimal code, all while being cross-browser compatible. Due to its simplicity and extensive browser support, jQuery has been widely adopted and remains relevant even with the advent of modern front-end frameworks. Some key use cases for jQuery include:
  • Creating dynamic, interactive user interfaces for web applications
  • Manipulating HTML elements and attributes dynamically
  • Handling user interaction events such as clicks, mouse movement, keyboard presses, etc.
  • Creating animation and effects to improve UI/UX
  • Loading data from the server without page refresh using AJAX
  1. Downloading and Including jQuery in Your Project jQuery can be included in your project in several ways. You can download it from the official jQuery website (https://jquery.com) and host it on your own server, or you can include it directly from a Content Delivery Network (CDN) like Google or Microsoft. To include jQuery in your HTML file, you simply add a script tag pointing to the jQuery file. This should be placed in the head of your HTML document, but it can be placed in the body as well. Here’s how you include it from a CDN:
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Remember, it’s important to make sure that jQuery is loaded before you try to run any jQuery code.

  1. The Document Ready Event Since jQuery often manipulates the contents of an HTML document, it’s important to ensure that the full document is loaded before jQuery runs any code. To ensure this, jQuery provides a function called $(document).ready(). This function waits until the DOM is fully loaded before it runs the specified function. Here’s a simple example:
   $(document).ready(function(){
      // Your code here
   });

This is an essential part of any jQuery script and helps prevent issues where jQuery code executes before the document elements it interacts with are fully loaded into the DOM.

Further learning can be supported with some small interactive exercises where learners can practice adding jQuery to a simple HTML document and using the `$(document).ready()` function.

Section 2: jQuery Selectors (1.5 hours)

  1. Basic Selectors jQuery offers a powerful set of tools for selecting elements in a document. These selectors, borrowed from CSS, make it easy to select and manipulate any element(s) in a page.
  • Element Selector The jQuery element selector selects elements based on the element name. The syntax is similar to CSS, where you use the name of the HTML element you want to select. For instance, if you want to select all <p> elements and hide them, you would do: $(document).ready(function(){ $("p").hide(); }); In this example, all the paragraph elements in the document would be hidden when the document is loaded.
  • ID Selector The jQuery ID selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, however, so you should use the ID selector when you want to find a single, unique element. To find an element with a specific id, you write a hash character, followed by the id of the HTML element. Here’s an example that hides the element with the id of “demo”: $(document).ready(function(){ $("#demo").hide(); }); Note: In CSS, IDs are defined with the # symbol, hence we use it in jQuery as well to select elements by ID.
  • Class Selector The jQuery class selector finds elements with a specific class. The class selector uses a period character to select elements with a specific class. To find elements with a specific class, you write a period character, followed by the name of the class. Here’s an example that hides elements of class “test”: $(document).ready(function(){ $(".test").hide(); }); Note: Similar to CSS, classes are defined with the . symbol, hence we use it in jQuery as well to select elements by class.

These basic selectors form the backbone of most jQuery operations. Once you’ve selected elements with these selectors, you can do anything with them: modify their attributes, change their CSS properties, alter their HTML structure, and more. Thus, mastery of jQuery selectors is key to using jQuery effectively.

2. Hierarchical Selectors

  • Descendant Selector (“ancestor descendant”) The Descendant Selector in jQuery allows you to select elements that are descendants of a specified element. Descendants include children, grandchildren, and so forth. The syntax is a space-separated sequence of selectors. Here’s an example that hides all paragraph elements that are descendants of the element with the id of “demo”: $(document).ready(function(){ $("#demo p").hide(); });
  • Child Selector (“parent > child”) The Child Selector in jQuery allows you to select all direct child elements of a specified element. A child element is any element that is nested directly in another element. Children are elements that reside one level down in the hierarchy from their parents. Here’s an example that hides direct child paragraph elements of the element with the id of “demo”: $(document).ready(function(){ $("#demo > p").hide(); });
  • Sibling Selector (“sibling1 ~ sibling2”) The Sibling Selector in jQuery allows you to select all sibling elements that follow after the “sibling1” element, have the same parent, and match the filtering “sibling2” selector. Here’s an example that hides all paragraph elements that follow a heading element and share the same parent: $(document).ready(function(){ $("h2 ~ p").hide(); }); Note: In this example, all paragraph elements that are siblings of h2 (i.e., they share the same parent) and appear after h2 are selected.

These hierarchical selectors help in making more specific selections and come in handy while working with nested HTML elements. Mastering them can make your code more precise and efficient.

3. Attribute Selectors

Attribute selectors provide a powerful way to select elements based on their attributes and attribute values. This can be useful when elements can’t be accurately selected by their type, class, or ID.

  • Attribute Equals Selector (“[attribute=value]”) The Attribute Equals Selector matches elements that have the specified attribute with a certain value. Here’s an example that selects all input elements with a type attribute equal to ‘text’:
  $(document).ready(function(){
    $("input[type='text']").hide();
  });
  • Attribute Contains Selector (“[attribute*=value]”) The Attribute Contains Selector matches elements that have the specified attribute and it contains the specified value somewhere within the attribute value. Here’s an example that selects all elements with a title attribute containing the word ‘info’:
  $(document).ready(function(){
    $("[title*='info']").hide();
  });
  • Attribute Starts With Selector (“[attribute^=value]”) The Attribute Starts With Selector matches elements that have the specified attribute and it starts with the specified value. Here’s an example that selects all input elements with a name attribute that starts with ‘info’:
  $(document).ready(function(){
    $("input[name^='info']").hide();
  });
  • Attribute Ends With Selector (“[attribute$=value]”) The Attribute Ends With Selector matches elements that have the specified attribute and it ends with the specified value. Here’s an example that selects all input elements with a name attribute that ends with ‘info’:
  $(document).ready(function(){
    $("input[name$='info']").hide();
  });

These selectors are a potent way of selecting elements based on their attributes, allowing for more granular control over the elements you manipulate in your jQuery code.

Section 3: jQuery Events (1.5 hours)

  1. Introduction to Events in jQuery jQuery’s event handling capabilities provide an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers.
  • Common jQuery Events: Click, Double Click, Mouse Enter, Mouse Leave, Hover Here are some of the most commonly used jQuery events:
    • Click: The click event is triggered when an element is clicked. Example:
    $(document).ready(function(){ $("p").click(function(){ alert("Paragraph clicked."); }); });
    • Double Click: The dblclick event is triggered when an element is double-clicked. Example:
    $(document).ready(function(){ $("p").dblclick(function(){ alert("Paragraph double-clicked."); }); });
    • Mouse Enter: The mouseenter event is triggered when the mouse pointer enters the element. Example:
    $(document).ready(function(){ $("p").mouseenter(function(){ alert("Mouse pointer entered the paragraph."); }); });
    • Mouse Leave: The mouseleave event is triggered when the mouse pointer leaves the element. Example:
    $(document).ready(function(){ $("p").mouseleave(function(){ alert("Mouse pointer left the paragraph."); }); });
    • Hover: The hover event is a combination of mouseenter and mouseleave events. It first triggers when the mouse pointer enters the element and again when it leaves. Example:
    $(document).ready(function(){ $("p").hover(function(){ alert("Mouse pointer entered the paragraph."); }, function(){ alert("Mouse pointer left the paragraph."); }); }); These events form the basis of user interaction with the elements on a webpage. Understanding these will allow learners to create dynamic and interactive web pages.

2. Binding Event Handlers

Event handlers are functions that are called in response to a specific event taking place. In jQuery, there are several ways to bind event handlers to elements.

  • .bind() Method The .bind() method attaches one or more event handlers to selected elements, and specifies a function to run when the event occurs. As of jQuery 3.0, the .bind() method has been deprecated. It was replaced by the .on() method. However, for the sake of learning and when working with older code, understanding this method can be beneficial. Syntax:
  $(selector).bind(event, function);

Example:

  $(document).ready(function(){
    $("p").bind("click", function(){
      alert("Paragraph clicked.");
    });
  });
  • .on() Method The .on() method attaches one or more event handlers for the selected elements and child elements. It works for both existing and future elements, like elements created dynamically via AJAX calls, which is one of its advantages over .bind(). Syntax:
  $(selector).on(event, childSelector, data, function, map);

Example:

  $(document).ready(function(){
    $("p").on("click", function(){
      alert("Paragraph clicked.");
    });
  });

In this example, a click event handler is bound to all paragraph elements. When a paragraph is clicked, an alert is displayed.

Note: As of jQuery 3.0, the use of .bind() method is not recommended, and it is advised to use .on() instead. However, understanding both methods will help students in maintaining existing projects or working with legacy code that uses the .bind() method.

3. Event Propagation

Understanding the process of event propagation is critical to controlling how events are handled and managed in your jQuery code. Event propagation describes the process of an event moving through the Document Object Model (DOM), and it involves three phases: capturing phase, target phase, and bubbling phase.

  • Understanding Event Bubbling and Capturing
  • Event Bubbling In event bubbling, events first trigger on the deepest target in the document, or the element that directly caused the event (like the specific button a user clicked), and then propagate upwards (bubble up) through the ancestors in the DOM tree, triggering for each one, until they reach the document node. For example, if you have a click event listener on both a button and a form containing the button, and the user clicks on the button, the click event triggers first on the button, and then on the form.
  • Event Capturing The process is the opposite with event capturing. The event is first captured by the outermost element and propagated to the inner elements. It’s important to note that not all events bubble. The focus event, for example, does not bubble in Internet Explorer. You can check whether a specific event bubbles or not in the jQuery documentation.
  • Controlling Event Propagation jQuery provides several methods to control event propagation:
  • event.stopPropagation(): This method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Example: $(document).ready(function(){ $("p").click(function(event){ event.stopPropagation(); // event handler code here }); });
  • event.stopImmediatePropagation(): This method also stops the bubbling of an event to parent elements, but additionally it prevents any other handlers on the same element from being executed. Example: $(document).ready(function(){ $("p").click(function(event){ event.stopImmediatePropagation(); // event handler code here }); }); Note that stopping event propagation is generally considered a bad practice because it prevents any other event handlers from running, whether they’re attached to the current element or to elements higher up in the DOM tree. It’s better to properly structure your HTML and JavaScript code to avoid needing to use these methods.

4. Removing Event Handlers

While binding event handlers allows you to run a function when an event occurs, there might also be situations where you want to remove these event handlers at a later time. jQuery provides methods for removing event handlers.

  • .unbind() Method The .unbind() method removes one or more event handlers from selected elements. This method is the counterpart to .bind(). As of jQuery 3.0, the .unbind() method has been deprecated and replaced by the .off() method. Syntax:
  $(selector).unbind(event, function);

Example:

  $(document).ready(function(){
    $("p").click(function(){
      alert("Paragraph clicked.");
    });
    $("button").click(function(){
      $("p").unbind("click");
    });
  });

In this example, a click event handler is bound to all paragraph elements. When the button is clicked, the click event handler is removed from the paragraph elements.

  • .off() Method The .off() method removes one or more event handlers from the selected elements. This method is the counterpart to the .on() method. Syntax:
  $(selector).off(event, function);

Example:

  $(document).ready(function(){
    $("p").on("click", function(){
      alert("Paragraph clicked.");
    });
    $("button").click(function(){
      $("p").off("click");
    });
  });

In this example, a click event handler is bound to all paragraph elements. When the button is clicked, the click event handler is removed from the paragraph elements.

Note: As of jQuery 3.0, the use of .unbind() method is not recommended, and it is advised to use .off() instead. However, understanding both methods will help students in maintaining existing projects or working with legacy code that uses the .unbind() method.

Section 4: jQuery Effects (1 hour)

  1. Basic Effects jQuery provides several methods to apply effects on the HTML elements. These methods can be used to create visually compelling effects and transitions on your web page elements.
  • .hide() and .show() Methods The .hide() and .show() methods in jQuery are used to hide and show elements, respectively. The .hide() method hides the selected elements: $(document).ready(function(){ $("button").click(function(){ $("p").hide(); }); }); In this example, all paragraph elements are hidden when the button is clicked. The .show() method shows the hidden, selected elements: $(document).ready(function(){ $("button").click(function(){ $("p").show(); }); }); In this example, all paragraph elements are shown when the button is clicked.
  • .toggle() Method The .toggle() method in jQuery is used to toggle between the .hide() and .show() methods. If the selected element is visible, it is hidden; if it is hidden, it is shown. $(document).ready(function(){ $("button").click(function(){ $("p").toggle(); }); }); In this example, the visibility of all paragraph elements is toggled when the button is clicked. If the paragraphs are visible, they will be hidden and vice versa. These methods provide a simple yet powerful way to control the visibility of elements on a web page. It’s worth noting that these methods do not just change the CSS ‘display’ property of the selected elements, they also create a animation effect to hide or show the elements.

2. Fading Effects

Fading effects can be achieved using several methods in jQuery. These are used to gradually change the opacity for selected elements, creating a smooth transition and enhancing the user experience.

  • .fadeIn(), .fadeOut() and .fadeToggle() Methods The .fadeIn() method gradually changes the opacity of the selected elements from hidden to visible (fading in), and the .fadeOut() method does the opposite, fading selected elements from visible to hidden.
  $(document).ready(function(){
    $("#fadeInButton").click(function(){
      $("div").fadeIn();
    });
    $("#fadeOutButton").click(function(){
      $("div").fadeOut();
    });
  });

In this example, clicking the “#fadeInButton” button will fade in the “div” element, and clicking the “#fadeOutButton” button will fade it out.

The .fadeToggle() method toggles between the .fadeIn() and .fadeOut() methods. If the element is faded out, it will be faded in. If it is faded in, it will be faded out.

  $(document).ready(function(){
    $("#fadeToggleButton").click(function(){
      $("div").fadeToggle();
    });
  });

In this example, clicking the “#fadeToggleButton” button will toggle the “div” element between fade in and fade out.

  • .fadeTo() Method The .fadeTo() method allows fading to a given opacity. This method changes the opacity of the selected elements from the current state to a specified level within a given duration.
  $(document).ready(function(){
    $("#fadeToButton").click(function(){
      $("div").fadeTo("slow", 0.5);
    });
  });

In this example, clicking the “#fadeToButton” button will change the opacity of the “div” element to 50% at a slow speed.

Using these methods, you can create a variety of fading effects, greatly enhancing the interactivity and visual appeal of your web pages.

3. Sliding Effects

Another category of effects in jQuery involves sliding animations. These can provide a dynamic, interactive feel to your webpages.

  • .slideUp(), .slideDown() and .slideToggle() Methods The .slideUp() method animates the height of the selected elements, gradually changing it from its original value to 0, giving the effect of the element sliding up.
  $(document).ready(function(){
    $("#slideUpButton").click(function(){
      $("div").slideUp();
    });
  });

In this example, clicking the “#slideUpButton” button will slide up the “div” element.

The .slideDown() method does the opposite of .slideUp(). It animates the height of the selected element from 0 to its original value.

  $(document).ready(function(){
    $("#slideDownButton").click(function(){
      $("div").slideDown();
    });
  });

In this example, clicking the “#slideDownButton” button will slide down the “div” element.

The .slideToggle() method toggles between the .slideUp() and .slideDown() methods.

  $(document).ready(function(){
    $("#slideToggleButton").click(function(){
      $("div").slideToggle();
    });
  });

In this example, clicking the “#slideToggleButton” button will toggle the “div” element between slide up and slide down.

These methods can be combined with other jQuery effects and methods to create complex and visually interesting webpages. They are especially useful when creating interactive elements like collapsible sidebars, dropdown menus, and accordions.

Section 5: Practice Exercise and Quiz (1 hour)

1. Practice Exercise:

The best way to learn coding is by doing. Now that you’ve learned about jQuery selectors, events, and effects, you should put your skills to the test. The following exercise is designed to help you do just that.

Task:

  • Create a webpage with a variety of elements, such as paragraphs, headings, buttons, and divs.
  • Implement a jQuery function that hides all paragraph elements when a specific button is clicked.
  • Implement another function that changes the color of all headings when a different button is clicked.
  • Use event handlers to create a div that slides down and reveals some text when a third button is clicked.

Remember to test your webpage thoroughly to make sure everything works as expected.

2. Links to Online Resources for Further Reading and Understanding:

These resources provide a wealth of information, examples, and exercises to help you gain a deeper understanding of jQuery and its capabilities. Remember, consistent practice is key when learning to code. Happy coding!