by Vipul Shekhawat
Use the left and right arrow keys to look through slides!
Download the file from jquery.com, add it to your web directory, and include
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
or link to Google's hosted version of it
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
or link to jQuery's own latest version
(not recommended due to possible backwards compatibility issues)
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
Element Selector
$("div")
ID Selector
$("#someId") $("div#someId")
Class Selector
$(".someClass")
Descendant Selector
$(".someClass a")
Multiple Selector
$("p, div, li")
Not Selector
$("div"):not(".someClass")
Image Selector
$("div"):image
Even/Odd Selectors
$("#someId"):even
Attribute Equals Selector
$('input[name=something]')
Attribute Contains Selector
$('input[name*="pass"]')
And many more!
You can copy/paste and run this code in your Javascript console! Refresh to reset the page!
How to open console: Chrome, Firefox, Safari
Append/Prepend
var html = "<p>Some new text</p>"; $("#appendId").append(html); $("#appendId").prepend(html);
Change Classes
$("#classId").addClass("ftw"); $("#classId").removeClass("ftw");
Remove
$("div").remove();
Overwrite
$("p").text("testing");
Retrieve Information
$("input[type='text']").val();
Modify CSS
$("body").css("color","red");
Show and Hide
$("#showHideId").hide(); $("#showHideId").show();
Slide Up and Down
$("#slideId").slideUp(); $("#slideId").slideDown();
Fade
$("#fadeId").fadeOut(); $("#fadeId").fadeIn(); $("#fadeId").fadeTo('slow',.5);
Toggles
var div = $("#toggleId"); div.toggle(); div.slideToggle(); div.fadeToggle();
Chained Effects
$("#chainId").fadeOut().slideDown().hide().fadeIn("fast");
And more! Check out animate() and queue() to create your own animation functions.
So far, we've only executed jQuery by running it in the console.
How do we actually use it on a webpage?
I've already created a function called "action" that toggles the box below. Try running each of these lines of code in the console to see how each event works.
Click and Double-click
$("#clickId").click(action); $("#clickId").dblclick(action);
Keyboard Input
$("#keyId").keydown(action); $("#keyId").keyup(action); $("#keyId").keypress(action);
Mouse Actions
$("#mouseId").hover(action); $("#mouseId").mouseenter(action); $("#mouseId").mousemove(action);
A snippet of actual code from my project last year:
SubmitInput.click(function(){ $.post("login.php", {password:PassInput.val()}, function(data){ // if password is incorrect, display error if (!data) { ErrorDiv.html("Incorrect password!"); ErrorDiv.slideDown("fast"); } // if correct, load admin portal else loadAdmin(); }, "json"); });
This is an example of how you can use $.post to easily send requests to the server without having to reload the page.