Module III: Effects and Events in jQuery PDF

Summary

This document provides an introduction to jQuery, a JavaScript library used for web development. It covers the basics of jQuery, including how to select and manipulate HTML elements, as well as handling events and performing animations.

Full Transcript

Programme Name: BCA Semester III Course Name: Internet and Web Technologies Course Code : BCA37002 Class : BCA3E Academic Session: Odd sem 2024-25 Table of Contents Module No. Module Name Content 3 Effects, Events in JQuery jQuery intro : Jo...

Programme Name: BCA Semester III Course Name: Internet and Web Technologies Course Code : BCA37002 Class : BCA3E Academic Session: Odd sem 2024-25 Table of Contents Module No. Module Name Content 3 Effects, Events in JQuery jQuery intro : John Resig is the creator and maintainer of the jQuery JavaScript library. it is a lightweight, "write less, do more", JavaScript library. jQuery makes it easy to find the elements of a document, and then manipulate those elements by adding content, editing HTML attributes and CSS properties, defining event handlers, and performing animations. As its name implies, the jQuery library is focused on queries. A typical query uses a CSS selector to identify a set of document elements and then returns an object that represents those elements. This returned object provides many useful methods for operating on the matching elements as a group. Whenever possible, these methods return the object on which they are invoked, allowing a succinct method-chaining idiom to be used. These features are at the heart of jQuery’s power and utility: An expressive syntax (CSS selectors) for referring to elements in the document An efficient query method for finding the set of document elements that match a CSS selector A useful set of methods for manipulating selected elements Powerful functional programming techniques for operating on sets of elements as a group, rather than one at a time A succinct idiom (method chaining) for expressing sequences of operations. ---------------------------------------------------------------------------------------------------------------------------- Download jQuery : Adding jQuery to Your Web Pages You have two primary ways to include jQuery in your website: 1. Download and Host Locally Visit jQuery.com and download the latest version of the jQuery library. After downloading, upload the jQuery file to your server. Include the following tag in the or at the end of your HTML file: html: Make sure to replace path/to/your/jquery.min.js with the actual location of the jQuery file on your server. 2. Include jQuery from a CDN You can also include jQuery directly from a Content Delivery Network (CDN). This is generally faster as the file might already be cached in the user's browser from other websites. To add jQuery using Google’s CDN, place this in your HTML: html: —----------------------------------------------------------------------------------------------------------------------------- jQuery Syntax Overview The basic syntax of jQuery is designed to simplify tasks like selecting HTML elements, handling events, and manipulating the DOM. It follows a simple pattern: javascript: $(selector).action(); $: This is the jQuery object. It is shorthand for "jQuery." selector: This is used to "query" or find HTML elements. action(): This is the method that performs a specific action on the selected elements. —----------------------------------------------------------------------------------------------------------------------------- Selecting Elements The $(selector) part is where you select the elements. It works similarly to CSS selectors: Select by element name: javascript: $("p") // Selects all elements Select by class: javascript: $(".myClass") // Selects all elements with class="myClass" Select by ID: javascript: $("#myId") // Selects the element with id="myId" Select by attribute: javascript: $("input[type='text']") // Selects all input elements of type="text" Syntax Description $("*") Selects all elements $(this) Selects the current HTML element $("p.intro") Selects all elements with class="intro" $("p:first") Selects the first element $("ul li:first") Selects the first element of the first $("ul li:first-child") Selects the first element of every $("[href]") Selects all elements with an href attribute $("a[target='_blank']") Selects all elements with a target attribute value equal to "_blank" $("a[target!='_blank']") Selects all elements with a target attribute value NOT equal to "_blank" $(":button") Selects all elements and elements of type="button" $("tr:even") Selects all even elements $("tr:odd") Selects all odd elements —----------------------------------------------------------------------------------------------------------------------------- What Are Events? Events are actions or occurrences that happen in the browser and can be responded to by JavaScript. Any time a user interacts with a webpage, or something changes, it triggers an event. Events can happen due to user actions or automated browser activities. An event represents the precise moment when something happens. Examples of Common User Actions (Events): Moving the mouse over an element (e.g., hovering over a button or image) Selecting a radio button or other form elements like checkboxes or dropdowns Clicking on an element such as a button, link, or image These actions (events) allow web developers to create interactive and dynamic web pages that respond to user input. The Term "Fires/Fired" When an event occurs, we say that the event is "fired." For example: "The keypress event is fired" the moment you press a key on your keyboard. "The click event is fired" when a user clicks a button or link. Common DOM Events in jQuery: Here are some common events that jQuery can handle: Mouse Events: ○ click: Triggered when an element is clicked. ○ dblclick: Triggered on a double-click. ○ mouseenter: Fired when the mouse enters the boundary of an element. ○ mouseleave: Fired when the mouse leaves the boundary of an element. ○ mousemove: Fired when the mouse moves over an element. Keyboard Events: ○ keypress: Triggered when a key is pressed. ○ keydown: Triggered when a key is pressed down. ○ keyup: Triggered when a key is released. Form Events: ○ submit: Triggered when a form is submitted. ○ change: Triggered when the value of an input element changes. ○ focus: Fired when an input element gains focus (i.e., when the user clicks into a text field). ○ blur: Fired when an input element loses focus (i.e., when the user clicks outside of a text field). Window Events: ○ load: Fired when the page has fully loaded. ○ resize: Fired when the browser window is resized. ○ scroll: Triggered when the user scrolls the page. ○ unload: Fired when the user leaves the page. Example of Using Events in jQuery :Here is an example of how you can use jQuery to handle a click event on a button, $(document).ready(function(){ $("#myButton").click(function(){ alert("Button was clicked!"); }); }); Click Me In this example, when the button is clicked, an alert box appears with the message "Button was clicked!". This is how we handle the click event using jQuery. —----------------------------------------------------------------------------------------------------------------------------- jQuery hide() and show() : the hide() and show() methods are used to hide and show HTML elements dynamically. Here's how you can use them: Syntax: hide(): This method hides the selected element(s). show(): This method shows the hidden element(s). Example : jQuery hide and show Hide Show This is a paragraph that can be hidden or shown. $(document).ready(function(){ $("#hide").click(function(){ $("p").hide(); //$("p").hide(1000); Hides the paragraph over 1 second. }); $("#show").click(function(){ $("p").show(); //$("p").show("slow"); Shows the paragraph with a slow animation. }); //$("p").show("fast"); Shows the paragraph with a fast animation. }); —----------------------------------------------------------------------------------------------------------------------------- Sliding Elements : jQuery provides the.slideUp(),.slideDown(), and.slideToggle() methods to create sliding effects. // Slide up (hide) an element $("#element").slideUp(); // Slide down (show) an element $("#element").slideDown(); // Toggle between sliding up and down $("#element").slideToggle(); Event Trigger Example: $("#slideUpButton").click(function() { $("#element").slideUp(); }); $("#slideDownButton").click(function() { $("#element").slideDown(); }); $("#slideToggleButton").click(function() { $("#element").slideToggle(); }); Fading Elements : You can create fade effects using.fadeIn(),.fadeOut(), and.fadeToggle(). // Fade out an element $("#element").fadeOut(); // Fade in an element $("#element").fadeIn(); // Toggle between fading in and out $("#element").fadeToggle(); Event Trigger Example: $("#fadeOutButton").click(function() { $("#element").fadeOut(); }); $("#fadeInButton").click(function() { $("#element").fadeIn(); }); $("#fadeToggleButton").click(function() { $("#element").fadeToggle(); }); Deleting Animation Elements You can remove an element from the DOM after an animation by combining.remove() with animations such as.fadeOut(). // Fade out and remove element after animation completes $("#element").fadeOut(500, function() { $(this).remove(); }); Event Trigger Example: $("#deleteButton").click(function() { $("#element").fadeOut(500, function() { $(this).remove(); }); }); Custom Animation : For custom animations, you can use the.animate() method, where you define CSS properties to animate. // Animate the element's width, height, and opacity $("#element").animate({ width: "300px", height: "300px", opacity: 0.5 }, 1000); Event Trigger Example: $("#customAnimateButton").click(function() { $("#element").animate({ width: "300px", height: "300px", opacity: 0.5 }, 1000); }); Working with Events You can attach the above animations to different events, such as click, hover, focus, keydown, etc. For example: // Custom animation triggered by a click event $("#animateOnClick").click(function() { $(this).animate({ left: "+=50px" }, 500); }); // Trigger animation when an input field gains focus $("#inputField").focus(function() { $(this).animate({ borderWidth: "10px" }, 500); }); Putting it all together: Here’s a more complex example that combines some of the animations with events. Toggle Element Animate Element $(document).ready(function() { $("#toggleButton").click(function() { $("#element").toggle(); }); $("#customAnimateButton").click(function() { $("#element").animate({ width: "300px", height: "300px", opacity: 0.5 }, 1000); }); }); —------------------------------------------------------------------- The.animate() function in jQuery allows you to create custom animations by animating the CSS properties of an element. It provides greater flexibility compared to other built-in methods like.fadeIn() or.slideUp(). You can animate most numeric CSS properties, such as width, height, opacity, margin, padding, and others. Syntax $(selector).animate(properties, duration, easing, callback); properties: The CSS properties to animate and their target values. duration: The speed of the animation (in milliseconds or as a string, like "slow", "fast"). easing (optional): The easing function to use for the transition ("swing" by default, or "linear"). callback (optional): A function to call once the animation completes. Example: Basic Usage // Animate the width and opacity of an element $("#box").animate({ width: "300px", opacity: 0.5 }, 1000); Animating Multiple Properties :You can animate multiple CSS properties at once. For example: // Animate width, height, and opacity at the same time $("#box").animate({ width: "300px", height: "300px", opacity: 0.7 }, 1000); Relative Values : You can use relative values (e.g., += or -=) to animate properties relative to their current values. // Increase the width by 50px and decrease the height by 50px $("#box").animate({ width: "+=50px", height: "-=50px" }, 500); Chaining Animations : You can chain multiple animations together. jQuery will automatically queue animations so that they run sequentially. $("#box").animate({ width: "300px" }, 1000).animate({ height: "300px" }, 1000).animate({ opacity: 0.5 }, 1000); Custom Animation with Easing Easing functions define how the intermediate points in an animation are calculated. jQuery provides two basic easing types: linear: The animation progresses at a constant pace. swing: The default easing type, where the animation starts slow, speeds up, and then slows down at the end. Example: // Use linear easing for a smooth, constant animation $("#box").animate({ width: "300px" }, 1000, "linear"); You can also use external easing functions by including the jQuery UI library or an easing plugin. Complete Example with Callback : You can provide a callback function that executes after the animation finishes. // Animate height and opacity, then log a message when done $("#box").animate({ height: "300px", opacity: 0.4 }, 1000, function() { console.log("Animation complete!"); }); Animation Queues By default, animations are placed in a queue and are executed one after the other. However, you can stop, start, or clear these queues using.stop(),.finish(), or.dequeue(). Example: Stopping Animation // Stop the animation in the middle $("#box").animate({ width: "500px" }, 5000); // Stops the animation if the stop button is clicked $("#stopButton").click(function() { $("#box").stop(); }); Example: Clearing the Animation Queue // This will clear all animations in the queue $("#box").clearQueue(); Controlling Animation Speed You can control how fast or slow an animation should be executed by setting the duration parameter in milliseconds or using predefined speed options. Milliseconds: You can specify an exact number of milliseconds (e.g., 1000 for 1 second). Predefined Speeds: "fast" (200ms) or "slow" (600ms). // Animate the width over 2 seconds (2000 milliseconds) $("#box").animate({ width: "400px" }, 2000); // Animate with predefined speed 'slow' $("#box").animate({ height: "400px" }, "slow"); Custom Animation Example : Here's a complete example combining different elements of the.animate() method: Start Animation $(document).ready(function() { $("#startAnimation").click(function() { // Chain multiple animations with different properties and easing $("#box").animate({ left: "+=200px", // Slide the box to the right width: "300px", // Increase width height: "300px" // Increase height }, 1000, "swing") // Easing and duration.animate({ opacity: 0.5 }, 1000, "linear") // Second animation with linear easing.animate({ left: "-=200px", // Move the box back to the left width: "100px", height: "100px", opacity: 1 // Reset the opacity }, 1000, function() { console.log("All animations complete!"); }); }); }); In this example: The element slides right, increases in size, fades to half opacity, and then reverses the process. Each step of the animation has a different easing function. Advanced Custom Animations You can create even more complex animations by controlling individual parts of an element, such as margins, paddings, or borders. $("#box").animate({ marginLeft: "50px", // Animate the margin padding: "20px", // Animate the padding borderWidth: "5px" // Animate the border width }, 1000); By combining.animate() with event handlers (e.g.,.click(),.hover()), you can create highly interactive animations.

Use Quizgecko on...
Browser
Browser