jquery_examples
jQuery Practical Examples
Section titled “jQuery Practical Examples”Explore common jQuery tasks through concise examples. Remember to wrap your code in $(function() { ... }); to ensure the DOM is ready.
Selecting Elements
Section titled “Selecting Elements”$("p").hide();
Demonstrates hiding all <p> elements.
$("#main-image").hide();
Demonstrates hiding the element with id="main-image".
$(". MuiDialog-paper").hide();
Demonstrates hiding all elements with class=" MuiDialog-paper".
$(this).hide();
Inside an event handler, hides the specific element that triggered the event (e.g., the button clicked).
Selector examples explained
Handling Events
Section titled “Handling Events”$("button").on('click', function() { alert('Button clicked!'); });
Shows an alert when any <button> is clicked. .on() is the standard method for event binding.
$("img").on('dblclick', function() { $(this).fadeOut(); });
Hides an image with a fade effect when it’s double-clicked.
$("#menu").on('mouseenter', function() { $(this).addClass('hover'); });
Adds the class hover when the mouse pointer enters the element with id="menu".
$("#menu").on('mouseleave', function() { $(this).removeClass('hover'); });
Removes the class hover when the mouse pointer leaves the element with id="menu".
$(". MuiDialog-paper").hover(function() { $(this).toggleClass('highlight'); });
Adds highlight class on mouse enter, removes it on mouse leave for elements with class=" MuiDialog-paper". hover() is a shortcut for mouseenter and mouseleave.
$("input[type='text']").on('focus', function() { $(this).css('border-color', 'blue'); });
Changes the border color when a text input field gains focus.
$("input[type='text']").on('blur', function() { $(this).css('border-color', ''); });
Resets the border color when a text input field loses focus.
Event handling examples explained
Show, Hide, Toggle Visibility
Section titled “Show, Hide, Toggle Visibility”$("#details").hide();
Immediately hides the element with id="details".
$("#details").show();
Immediately shows the element with id="details".
$("#details").toggle();
Toggles the visibility of the element with id="details" (shows if hidden, hides if shown).
$("span.optional").hide(500);
Hides elements with class="optional" over 500 milliseconds.
Show/Hide examples explained
Fading Effects
Section titled “Fading Effects”$("#notification").fadeIn('slow');
Gradually fades in the element with id="notification" (‘slow’ duration).
$("#notification").fadeOut(1000);
Gradually fades out the element with id="notification" over 1000 milliseconds (1 second).
$("#notification").fadeToggle('fast');
Toggles between fading in and fading out (‘fast’ duration).
$("#overlay").fadeTo(500, 0.5);
Fades the element with id="overlay" to 50% opacity over 500 milliseconds.
Fading examples explained
Sliding Effects
Section titled “Sliding Effects”$("#details-panel").slideDown();
Slides down (reveals) the element with id="details-panel".
$("#details-panel").slideUp('fast');
Slides up (hides) the element with id="details-panel" quickly.
$("#details-panel").slideToggle(500);
Toggles between sliding down and sliding up over 500 milliseconds.
Sliding examples explained
Custom Animations
Section titled “Custom Animations”$("#box").animate({ left: '250px' });
Animates the left CSS property of the element with id="box" to 250px.
$("#box").animate({ opacity: 0.5, height: '50px', width: '50px' }, 1000);
Animates multiple CSS properties (opacity, height, width) over 1 second.
$("#box").animate({ left: '+=50px' }, 'fast');
Animates the left property by increasing its current value by 50px.
$("#box").animate({ height: 'toggle' });
Animates the height to show or hide the element.
$("#box").animate({ width: '200px' }).animate({ height: '200px' });
Queues animations: first animates width, then animates height.
Animation examples explained (Note: For complex animations, CSS transitions/animations are often more performant).
Stopping Animations
Section titled “Stopping Animations”$("#sliding-panel").stop();
Stops the currently running animation on the element with id="sliding-panel".
$("#animated-box").stop(true, true);
Clears the animation queue and immediately jumps to the final state of the current animation.
Stopping animation examples explained
Getting HTML Content and Attributes
Section titled “Getting HTML Content and Attributes”const text = $("p#intro").text();
Gets the combined text content of the element with id="intro" (strips HTML tags).
const content = $("div#content").html();
Gets the HTML content (including tags) of the element with id="content".
const name = $("input#username").val();
Gets the current value of the input field with id="username".
const linkUrl = $("a#w3s-link").attr('href');
Gets the value of the href attribute from the link with id="w3s-link".
Getting content/attribute examples explained
Setting HTML Content and Attributes
Section titled “Setting HTML Content and Attributes”$("p#intro").text('New introduction text.');
Sets the text content of the element with id="intro".
$("div#content").html('<h2>New Title</h2><p>New paragraph.</p>');
Sets the HTML content of the element with id="content".
$("input#username").val('DefaultUser');
Sets the value of the input field with id="username".
$("a#w3s-link").attr('href', 'https://www.w3schools.com/jquery/');
Sets the href attribute of the link with id="w3s-link".
$("img").attr({ src: 'new_image.jpg', alt: 'New Alt Text' });
Sets multiple attributes (src and alt) for all <img> elements.
$("p").html(function(index, oldHtml) { return oldHtml + ' **(Updated)**'; });
Uses a callback function to modify the HTML content of each paragraph, appending ’ (Updated)’.
Setting content/attribute examples explained
Adding Elements/Content
Section titled “Adding Elements/Content”$("ul#list").append('<li>New Item</li>');
Appends a new list item to the end of the <ul> with id="list".
$("ul#list").prepend('<li>First Item</li>');
Prepends a new list item to the beginning of the <ul> with id="list".
$("p#first-para").after('<hr>');
Inserts a horizontal rule <hr> immediately after the paragraph with id="first-para".
$("h2#title").before('<p>Introduction:</p>');
Inserts a paragraph immediately before the heading with id="title".
Adding elements examples explained
Removing Elements/Content
Section titled “Removing Elements/Content”$(". MuiDialog-paper").remove();
Removes all elements with class=" MuiDialog-paper" from the DOM.
$("#container").empty();
Removes all child elements inside the element with id="container", but leaves the container itself.
$("p").remove('.old');
Removes only the <p> elements that also have the class old.
Removing elements examples explained
Manipulating CSS Classes
Section titled “Manipulating CSS Classes”$("#header").addClass('fixed-header');
Adds the class fixed-header to the element with id="header".
$("button").addClass('btn btn-primary');
Adds multiple classes (btn and btn-primary) to all <button> elements.
$("#header").removeClass('fixed-header');
Removes the class fixed-header from the element with id="header".
$("#menu-item").toggleClass('active');
Adds the active class if it’s not present, or removes it if it is present, for the element with id="menu-item".
CSS class manipulation examples explained
Working with CSS Properties
Section titled “Working with CSS Properties”const bgColor = $("#main").css('background-color');
Gets the computed value of the background-color CSS property for the element with id="main".
$("h1").css('color', 'blue');
Sets the color CSS property to blue for all <h1> elements.
$(". MuiDialog-paper").css({ 'background-color': 'yellow', 'font-weight': 'bold' });
Sets multiple CSS properties for all elements with class=" MuiDialog-paper".
CSS property examples explained
Getting Dimensions
Section titled “Getting Dimensions”const w = $("#image").width(); const h = $("#image").height();
Gets the computed width and height of the element (excluding padding, border, margin).
const innerW = $("#container").innerWidth();
Gets the width including padding, but not border.
const outerW = $("#container").outerWidth();
Gets the width including padding and border.
const outerWMargin = $("#container").outerWidth(true);
Gets the width including padding, border, and margin.
const docHeight = $(document).height(); const winHeight = $(window).height();
Gets the height of the entire HTML document and the browser viewport respectively.
$("#resizable").width(300).height(200);
Sets the width and height of the element.
Dimension examples explained
Traversing Up (Ancestors)
Section titled “Traversing Up (Ancestors)”$("span#item").parent();
Selects the direct parent element of the <span> with id="item".
$("span#item").parents();
Selects all ancestor elements (parent, grandparent, etc.) up to <html>.
$("span#item").parents('ul');
Selects all ancestor elements that are specifically <ul> elements.
$("li.active").parentsUntil('div.container');
Selects all ancestors between the active <li> and the div.container, but not including the container itself.
Ancestor traversal examples explained
Traversing Down (Descendants)
Section titled “Traversing Down (Descendants)”$("div#main-content").children();
Selects all direct child elements of the <div>.
$("div#main-content").children('p. MuiDialog-paper');
Selects only the direct children that are <p> elements with the class MuiDialog-paper.
$("div#main-content").find('span');
Selects all <span> elements that are descendants (children, grandchildren, etc.) of the <div>.
Descendant traversal examples explained
Traversing Sideways (Siblings)
Section titled “Traversing Sideways (Siblings)”$("h2.current").siblings();
Selects all sibling elements of the <h2> with class current.
$("h2.current").siblings('p');
Selects only the sibling elements that are <p> tags.
$("li.active").next();
Selects the immediately following sibling element.
$("li.active").nextAll('li');
Selects all following sibling elements that are <li> tags.
$("li#start").nextUntil('li#end');
Selects all sibling elements between the one with id="start" and the one with id="end".
$("li.active").prev(); Selects the immediately preceding sibling.
$("li.active").prevAll(); Selects all preceding siblings.
$("li#start").prevUntil('li#stop'); Selects preceding siblings between #start and #stop.
Sibling traversal examples explained
Filtering Selections
Section titled “Filtering Selections”$("li").first();
Selects the first <li> element among all matched <li> elements.
$("li").last();
Selects the last <li> element among all matched <li> elements.
$("li").eq(2);
Selects the third <li> element (index starts at 0).
$("p").filter('. MuiDialog-paper');
Filters the selection of paragraphs to include only those with class=" MuiDialog-paper".
$("p").not('. MuiDialog-paper');
Filters the selection of paragraphs to exclude those with class=" MuiDialog-paper".
Filtering examples explained
AJAX: Loading HTML Content
Section titled “AJAX: Loading HTML Content”$("#result").load('content/data.html');
Loads the content of data.html into the element with id="result".
$("#result").load('content/data.html #specific-section');
Loads only the content of the element with id="specific-section" from data.html into #result.
$("#result").load('content/data.php', { name: 'John', location: 'Boston' }, function(response, status, xhr) { if (status == 'error') { console.error('Error loading data:', xhr.statusText); } });
Loads content from data.php, sending data, and includes a callback function to handle completion (success or error). Note: Modern practice often prefers $.get or $.post with Promises.
AJAX load examples explained
AJAX: GET and POST Requests
Section titled “AJAX: GET and POST Requests”$.get('api/users.json', function(data) { console.log('Data received:', data); }).fail(function() { console.error('Failed to get data.'); });
Uses $.get() to retrieve data from api/users.json. It uses .done() (implicit in the callback shorthand) and .fail() for handling the asynchronous response (Promise-like behavior).
$.post('api/submit-form.php', { name: 'Jane', email: 'jane@example.com' }) .done(function(response) { console.log('Server response:', response); }) .fail(function() { console.error('Failed to post data.'); });
Uses $.post() to send data to api/submit-form.php and handles the response using .done() and .fail().
AJAX GET/POST examples explained (Note: The native fetch API is the modern standard for AJAX in JavaScript, but $.get/$.post are common in jQuery projects).