jquery javascript is a powerful language but it is not always easy to work with. jquery is a...
TRANSCRIPT
jQuery
JavaScript is a powerful language but it is not always easy to work with.
jQuery is a JavaScript library that helps with:
– HTML document traversal
– HTML manipulation
– Event handling
– Animation
– Ajax
Get it here: http://jquery.com/
Learn more here: http://learn.jquery.com
$ Syntax
In jQuery you will often be calling functions on jQuery objects.
This selects all buttons on the current page and applies someFunction() to them.
$(“button”).someFunction();
jQuery object representing one or more HTML elements
Function to apply
$ Syntax
Sometimes you will be calling jQuery functions that are not associated with HTML elements at all. These are called jQuery core methods.
$.ajax(...)
$.each(...)
SelectorsSelectors “select” elements in the DOM. This is one of the best
parts of jQuery – you can easily traverse the DOM and grab the element or elements that you need with CSS selectors.
$(“button”) selects all button elements
$(“.fancy”) selects all elements with the class fancy
$(“#myElement”) selects one element with the ID myElement
$(“nav .fancy”) selects all elements with the class fancy that are inside a nav element
Learn more here: https://learn.jquery.com/using-jquery-core/selecting-elements/
And here: https://api.jquery.com/category/selectors/
Selectors – More Efficient
It's actually faster to use the jQuery find() function:
$(“nav .fancy”)
$(“nav”).find(“.fancy”)
And while you can use pseudo classes, it's faster to use the jQuery functions:
$(“li:first”)
$(“li”).first()
Selectors – More Efficient
More options with Filter...
Select elements with both class1 and class2
$(“.class1.class2”)
$(“.class1”).filter(“.class2”)
Selectors
You can also step forward and back
$(“li”).first()
$(“li”).first().next()
$(“li”).last().prev()
Walk up the DOM tree
$(“li”).parent()
Walk down the DOM tree
$(“ul”).children(“.someClass”)
Selectors - Closest
<ul> <li> <p> ... <span>...</span> </p> </li> <li> <p> ... <span>...</span> </p> </li></ul>
Just because you can use parent() doesn't mean you always should!
//Finds a specific element
$(“span”).parent().parent();
This code is easier to read:
//Finds the nearest ancestor
//li element
$(“span”).closest(“li”);
Change Text
Let's say you want to dynamically change the text in an h1 tag:
$(“h1”).text(“Hello!”);
Or maybe you just want to grab the text to do something with it later:
var text = $(“h1”).text();
Document ReadyIf you just write your JavaScript or jQuery in a script tag
without wrapping it in any functions, it will execute as soon as the browser reads it. But that would be before the DOM has finished loading, so it won't find your HTML elements.
You can execute code when the document has finished loading (not including images that may still be downloading) by using the “document ready” function:
$(document).ready(function() {
// Your code here.
});
Adding Elements
Create an element:
var listItem = $(“<li>Some Text</li>”);
Add an element to the DOM:
$(“ul”).append(listItem); //add as last child
$(“ul”).prepend(listItem); //add as first child
$(“ul”).before(listItem); //add before ul
$(“ul”).after(listItem); //add after ul
Adding Elements
One way:
$(“ul”).append(listItem); //add as last child
$(“ul”).prepend(listItem); //add as first child
$(“ul”).before(listItem); //add before ul
$(“ul”).after(listItem); //add after ul
Another way:
listItem.appendTo($(“ul”)); //add as last child
listItem.prependTo($(“ul”)); //add as first child
listItem.insertBefore($(“ul”)); //add before ul
listItem.insertAfter($(“ul”)); //add after ul
Removing Elements
Removing one or more elements is simple:
$(“li”).remove()
Event Handlers
Add a click event handler to all button elements:
$(“button”).click(function(event) {
});
Anonymous Function
Passing Functions as Arguments
If you wanted to pass arguments into the button's click function
Wrong
$(“button”).click(myFunction(myParam));
Right
$(“button”).click(function () {
myFunction(myParam);
});
Event Handlers – Prevent Default Behavior
You can prevent the default behavior of an event using the following:
$(“button”).click(function(event) {
event.preventDefault();
});
$(this)
Sometimes you will want to refer to the element that the event occurred on. In many languages, including JavaScript, there is a this keyword.
$(“button”).click(function(event) {
$(“button”).text(“Clicked”) //WRONG
this.text(“Clicked”); //WRONG
$(this).text(“Clicked”); //RIGHT
});
Changing CSS Classes
Add or Remove a CSS class:
$(“button”).addClass(“someClass”);
$(“button”).removeClass(“someClass”);
HTML 5 Data
HTML 5 added data attributes:
<div class=”product” data-price=”19.99”>
...
<button type=”button”>How Much?</button>
</div>
$(“button”).click(function() {
var price = $(this).closest(“.product”).data(“price”);
//do something with the price
});
HTML 5 Data
Another way to write it...
<div class=”product” data-price=”19.99”>
...
<button type=”button”>How Much?</button>
</div>
$(“.product”).on(“click”, “button”, function() {
var price = $(this).closest(“.product”).data(“price”);
//do something with the price
});
Form Data
To pull data out of an input box...
$(“#someInput”).val();
To set data in an input box...
$(“#someInput”).val(“new value”);
Show / Hide
Show or hide element(s). There are optional parameters for animation available.
Documentation: http://api.jquery.com/category/effects/basics/
$(“selector”).show();
$(“selector”).hide();
Documentation: http://api.jquery.com/category/effects/sliding/
$(“selector”).slideUp();
$(“selector”).slideDown();
$(“selector”).slideToggle();
Callbacks
A callback is a function that is called automatically at a later time. For example, if you make an AJAX request, it may take some time for the data to return (even if only a second). The beauty of AJAX is that it's asynchronous – in other words, code execution continues without waiting for the data to be returned.
You may, however, want to execute code when the AJAX request returns. You can specify a callback function to handle this need.
AJAX
var jqxhr = $.ajax( "URL_To_Service" )
.done(function(data) {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});