jQuery Examples

jQuery Examples:

Some basic jQuery examples I created over time to help me learn jQuery. Hopefully you find this helpful as well! I apologize as some of these examples are a work in progress.

View Source of this page on all examples to be sure you have the right jquery.




Quick Reference:
$(document).ready(function(){
alert ('Ready to do your bidding, master');
});

$(function() { alert('Good to go'); });

Quick Selection
$(document).ready(function(){

$('p').show(); // Select all the p elements
$('p,div,h2,input').hide(); // Select multiple elements
$('#someId tr') // Select table rows within id someId

Filters
$('li:eq(2)') // Select the second li within list items

Content Filters
$('li:contains(second-level)') // Selects li that contains the text "second level"

Examples: $("p").addClass("myClass yourClass"); // Adds more than one class to all p elements });

* When the document is ready run our function. Almost everything you do in jQuery needs to be done after the document is ready.
jQuery Open Link

Reference

$('.open-link').click(function(){ window.open('http://www.example.org'); return false; });
Jquery Screen Size Detection
$(document).ready(function() { if ((screen.width>=1024) && (screen.height>=768)) { alert('Screen size: 1024x768 or larger'); $("link[rel=stylesheet]:not(:first)").attr({href : "detect1024.css"}); } else { alert('Screen size: less than 1024x768, 800x600 maybe?'); $("link[rel=stylesheet]:not(:first)").attr({href : "detect800.css"}); } });

Source - http://www.ilovecolors.com.ar/detect-screen-size-css-style/
Tooltip Using Jquery
A simple tooltip using jquery. Below are example href links, each with a title. The jquery should identify the title then append and position a div with the text of the title.
jQuery UI Modal/Dialog for image

Selecting Based on attribute
Click the buttons below to select different elements based on their attributes.





Title = "test title 1"
showRow="true"
Pick me! alt="Pick me!"


Focus

*Example of jquery .focus which jumps user to element with class ".bottom"
jQuery and CSS Tabs

Name
Items: 23

Name
Items: 23



Source / Credit - http://www.lessthanweb.com/blog/simple-css-tabs-with-jquery




Content 1

Content 1
Content 2

Content 2
Content 3

Content 3

jQuery Using Onclick, Also passing in param
Some Random Div


Hidden Div Content - Needs to show and hide based on onclick event

Hidden Div Content

Hidden Div Content


Show Hide Example
Click the image to view a basic jquery show / hide.



$(document).ready(function(){ $('.showHide2').click(function() { $('.hiddenDiv').slideToggle("slow"); }); $('.showHide1').click(function() { $('.hiddenDiv').toggle(); }); $('.showHide3').click(function() { $('.hiddenDiv').fadeToggle(); }); });

jQuery Drop Down Menu Examples

JQuery Drop Down Two separate UL lists - Functional in IE 6 on up.
  • Default
  • Default
  • US
  • BRL
  • CNY
  • EUR
  • GBP
  • ILS
  • JPY
  • KRW
  • RUB



Example, jquery drop down on hover



Example 2 $(document).ready(function(){ $('#menu > li >ul') .hide() .click(function(e) { e.stopPropagation(); }); // Toggle for when you click the menu $('#menu > li').toggle(function() { $(this) .css('background-position', 'right -20px') .find('ul').slideDown(300); }, function() { $(this) .css('background-position', 'right top') .find('ul').slideUp(300); }); // Menu responds to hover event with delayed execution $('#menu > li').hover(function() { $(this).addClass('waiting'); setTimeout(function() { $('#menu .waiting') .click() .removeClass('waiting'); }, 400); }, function() { $('#menu .waiting').removeClass('waiting'); }); $('#menu li li').hover( function () { $(this).css ('color', '#FF0000'); }, function () { $(this).css ('color', '#000000'); } ); }); Resources:
- http://www.queness.com/post/1047/easy-to-style-jquery-drop-down-menu-tutorial
- http://css-tricks.com/simple-jquery-dropdowns/
Simple Modal Example

Close

Simple Modal

// Modal opens based on click event $('.popDisModal').click(function() { $(".mySearchAlert").modal(); }); // Closes Modal $(".mySearchAlertClose").click(function () { $.modal.close(); });
Close

Advanced Modal

// Modal opens based on click event $('.popDisModal2').click(function (e) { $('.mySearchAlert2').modal({ opacity:70, overlayClose:true, // Allows you to close via click anywhere outside modal overlayCss: {backgroundColor:"#000"} }); return false; }); // Closes Modal $(".mySearchAlertClose").click(function () { $.modal.close(); });
$(document).ready(function(){ // Modal opens based on click event $('.popDisModal').click(function (e) { $('.mySearchAlert').modal({ opacity:80, overlayClose:true, // Allows you to close via click anywhere outside modal overlayCss: {backgroundColor:"#000"} }); return false; }); // Closes Modal $(".mySearchAlertClose").click(function () { $.modal.close(); }); });

Header

Please remove the IP detect Chinese flag module that pops up for users from IP=China. Please remove the IP detect Chinese flag module that pops up for users from IP=China.

Button

Limit the number of form textarea lines to a specific number and count the lines.


0 lines used.
$(document).ready(function(){ var lines = 10; var linesUsed = $('#linesUsed'); $('#countMe').keydown(function(e) { newLines = $(this).val().split("\n").length; linesUsed.text(newLines); if(e.keyCode == 13 && newLines >= lines) { linesUsed.css('color', 'red'); $(this).parents('form').submit(function() { return false; }); return false; } else { linesUsed.css('color', ''); $(this).parents('form').submit(function() { return true; }); return true; } }); });

Clear a form input field once / change color of text from gray to black.

$('.clearMe').one("focus", function() { $(this).val(""); $(this).removeClass("preClick"); $(this).addClass("blkAgain"); }); $('.clearly').submit(function() { $('input.clearMe').val('Good Job, it worked!').addClass('goodJob'); // alert($('.clearMe').val()); return false; });
Uncheck Test:



See - http://stackoverflow.com/questions/372325

Show/Hide a rows based on checked or unchecked form checkbox. Two different Examples

Form:
Check 1:
Example Table 1:
Manufacturer row One here
Manufacturer row Two here
$(document).ready(function(){ $('input.manOne').change(function () { if ($(this).is(":checked")) { //do the stuff that you would do when 'checked' $('tr.manOne').hide(); return; } //Here do the stuff you want to do when 'unchecked' $('tr.manOne').show(); }); });
Form:
Check 1:
Check 2:
Check 3:
Example Table 2:
Manufacturer row One here
Manufacturer row Two here
Manufacturer row Three here
$(document).ready(function(){ $('#distributorAnchors input').change(function () { var cls = $(this).attr("class"); if ($(this).is(":checked")) { //do the stuff that you would do when 'checked' $('tr.' + cls).hide(); return; } //Here do the stuff you want to do when 'unchecked' $('tr.' + cls).show(); }); });
This
Example of the 'this' selector being used to select an image within the class or id you have specified.
http://api.jquery.com/toggle-event/
$(".face").toggle( function () { $('img',this).attr('src','sad-icon.jpg'); }, function () { $('img',this).attr('src','icon-happy.png'); });

Sliding Panel
Used .click method to capture the event and then the .slideToggle method to slide the div into view matching the height of the element. CSS used to hide the div id panel until button event (click) occurs.

.slideToggle( [ duration ], [ callback ] ) - Allows for a callback function that calls once the animation is complete

Inside 1
Inside 2
$('#slider').click(function() { $('#panel').slideToggle("slow"); return false; });


Accordian
With the click method attached to the H3 Title tags of each section we use the .slideToggle method to display the content. The .eq method is used to specify a specific element within a set of matched elements. In thise case we chose .eq(2). At the same time the .siblings() method is used to get the siblings or the p element and apply the .slideup method which hides the matching elements with a sliding motion.

Title Here

The contents of your accordian can go here. Graphics, text, more elements or whatever you like can be placed in here. Try it for yourself!

Title Here

The contents of your accordian can go here. Graphics, text, more elements or whatever you like can be placed in here. Try it for yourself!

Title Here

The contents of your accordian can go here. Graphics, text, more elements or whatever you like can be placed in here. Try it for yourself!

Title Here

The contents of your accordian can go here. Graphics, text, more elements or whatever you like can be placed in here. Try it for yourself!

$('.accordion h3').eq(2).addClass('active'); $('.accordion p').eq(2).show(); $(".accordion h3").click(function(){ $(this).next("p").slideToggle("slow") .siblings("p:visible").slideUp("slow"); $(this).toggleClass("active"); $(this).siblings("h3").removeClass("active"); });


Hover Fun

  1. Used .append method to add em elements.
  2. Then used the .hover for the button element.
  3. Used the .find method to get the descendant em of element button.
  4. Used the .animate method to animate the em.
  5. Created a variable hoverText using .attr method to extract the title text from each button.
  6. .text method to add the text to the em element.
  7. CSS used to set display: none; and position: absolute;


$(".hmenu button").append("<em></em>") $(".hmenu button").hover(function() { $(this).find("em").animate({opacity: "show", top: "-75"}, "slow"); var hoverText = $(this).attr("title"); $(this).find("em").text(hoverText); }, function() { $(this).find("em").animate({opacity: "hide", top: "-85"}, "fast"); });




Animate Hide method
We use the .click method to fire when the link is clicked. We then use the .parents method which grabs the ancestor/div of the a element. We then use the .animate method to hide the div slowly with an opacity change as it gets hidden. return false at the end to prevent the default link action.

Guess What

Now you see me

But when you click these XOXO's I'm gone!


$(".simplehide .simplehide2").click(function(){ $(this).parents(".simplehide").animate({opacity: "hide" }, "slow"); return false; });




Chain Gang
We are chaining multiple methods here. Watch speedy zip around the screen.




Event Click Handler:
(Hides then shows again, threw on a blue border for fun. Also displays url of link clicked)
Example Link $(".link-notify").click(function(event){ alert("You just clicked " + this.href); event.preventDefault(); .hide("slow").show("slow"); $(this).hide("slow").show("slow").addClass("setBold"); });


Change Page Style sheet to: $("#css-normal").click(function() { $("link[rel=stylesheet]").attr({href : "web_design.css"}); }); // blue $("#css-blue").click(function() { $("link[rel=stylesheet]").attr({href : "blue.css"}); }); // green $("#css-green").click(function() { $("link[rel=stylesheet]").attr({href : "green.css"}); });
Overlay Fun
[ x ]

Overlay Success!

Content of the overlay here



$("#overlay-test").click( function() { var position = $(".basic-info").offset(); // Grabs the position $("#populate-overlay").css( { position: "absolute", left: position.left, top: position.top } ).show(); } ); $(".close-x").click(function () { $(this).parent().hide(); }); $(".cancel-overlay").click(function () { $(this).parent().hide(); });


Highlight and paragraph change

This is an example paragraph one.

This is an example paragraph two.

This is an example paragraph three.

This is an example paragraph four.

$("p.highlight").click(function () { $(this).toggleClass("highlight").html("I'm am now a funky light switch now! Click me on and off."); }); $(".paragraph-example").click(function() { var str = $(".paragraph-example p:first").text(); $(".paragraph-example p:last").html(str).addClass("highlight"); });

Cool use of the jquery HTML method :


preview here:
$("#codehere").keyup(function() { $("#preview").html($(this).val()) })


.mouseover & .animate example $('#myBox').mouseover(function() { $(this).animate({ width: "70%", opacity: 0.4, marginLeft: "0.6in", fontSize: "3em", borderWidth: "10px" }, 500 ); });


Using jQuery to stripe and hover-highlight a table

Topic Course on Lynda.com
Ajax 4hrs 22mins
XML / XSLT 5hrs 48mins
ASP.NET Essential Training 6hrs 5mins
PHP MYSQL 11hrs!



Using Ajax to load an XML document
In this example the .get method is used to pull components of the XML document.
XML to populate here (click inside this div)
$('#xml-example').toggle(function() { $.get('test_file.xml', function(data) { $('#xml-example').empty(); $(data).find('entry').each(function() { var $entry = $(this); var html = '<div class="entry">'; html += '<h3 class="term">' + $entry.attr('term') + '</h3>'; html += '<div class="part">' + $entry.attr('part') + '</div>'; html += '<div class="definition">'; html += $entry.find('definition').text(); var $quote = $entry.find('quote'); if ($quote.length) { html += '<div class="quote">'; $quote.find('line').each(function() { html += '<div class="quote-line">' + $(this).text() + '</div>'; }); if ($quote.attr('author')) { html += '<div class="quote-author">' + $quote.attr('author') + '</div>'; } html += '</div>'; } html += '</div>'; html += '</div>'; $('#xml-example').append($(html)); }); }); return false; }, function() { $('#xml-example').empty(); });


.Each Method
Description: Iterate over a jQuery object, executing a function for each matched element. It's designed to make DOM looping constructs concise and less error-prone. When called it iterates over the DOM elements that are part of the jQuery object. Each time the callback runs, it is passed the current loop iteration, beginning from 0. More importantly, the callback is fired in the context of the current DOM element, so the keyword this refers to the element. In this example we iterate through alerting the index and text contained within each li. We also use .css method to apply the color red to each li. (Source api.jquery.com)

$('#mylist a').click(function() { $('#mylist li').each(function(index) { alert(index + ': ' + $(this).text()); }); });


AJAX - Communication between client and server
The server can dynamically shape data based on input from the user/browser/client. Using the .click method the user selects from the list of links. Using the .load method, data (test.php) is loaded from the server and returned into the matched element (id - ajax-list1). We use the .text method to get the contents of the element (in this case the a link).

Ajax List

$(document).ready(function() { $('#ajax-call a').click(function() { $('#ajax-list1').load('test.php', {'term': $(this).text()}); return false; }); });


AJAX load
.click method loads an html file when button is clicked.

$(document).ready(function() { $('#html-load').click(function() { $('#html-content').load('ajax-insert.html'); $('#html-content').slideDown('60000'); return false; }); });
.ajax Learn more about .ajax here. jQuery api here.

$(document).ready(function() { $('#html-load2').click(function() { $.ajax({ url: "ajax-insert2.html", cache: false, success: function(html) { $("#html-content2").replaceWith(html); } }); }); $('#html-content2').ajaxStart(function() { $(this).addClass('loading'); }); $('#html-content2').ajaxStop(function() { $(this).removeClass('loading'); }); });




jquery Validate with Modals - Basic jQuery form overlay using validate plugin and a character count.





Basic jQuery form using validate plugin and a character count.
Please fill in the form below and Send to share this information.






Form Validation Using jQuery:

A simple comment form with submit validation and default messages

*

*

*

 

*


Selecting the first div and image in a series of repeating divs.
Some Unique Header
Title
Title
Title
$(".results:first div:hidden").show(); $(".results:first .arrow").attr('src','http://www.findchips.com/findchips/images/arrow-down.png'); OR $("body div#priceInventory div:nth-child(2) div:nth-child(2)").show(); $("body div#priceInventory div:nth-child(2) div:nth-child(1) img").attr('src','http://www.findchips.com/findchips/images/arrow-down.png');

How to immitate something being clicked. Especially useful if you have a function tied to a click that you want to trigger. The following selects the first element on the page with class distiLabel.

$(".distiLabel:first").click();
Selects the parent div of "this" div then the next div to the parent div. Then hides "this" which is the link itself. Then it hides its parent. <div class="more" onClick="$(this).parent().next().fadeIn('fast');$(this).hide();$(this).parent().hide();">more...</div>


This is the bottom!