jQuery

Basic syntax is: $(selector).action()

A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)

Examples:

* $(this).hide() - hides the current element.
* $("p").hide() - hides all <p> elements.
* $(".test").hide() - hides all elements with class="test".
* $("#test").hide() - hides the element with id="test".

You might have noticed that all jQuery methods in our examples, are inside a document ready event:

<code>
$(document).ready(function(){
// jQuery methods go here...
});
</code>

This is to prevent any jQuery code from running before the document is finished loading (is ready).

It is good practice to wait for the document to be fully loaded and ready before working with it. This also allows you to have your JavaScript code before the body of your document, in the head section.

Here are some examples of actions that can fail if methods are run before the document is fully loaded:

Trying to hide an element that is not created yet

Trying to get the size of an image that is not loaded yet

Tip: The jQuery team has also created an even shorter method for the document ready event:

<code>
    $(function(){
        // jQuery methods go here...
    });
</code>

Selectors

jQuery selectors allow you to select and manipulate HTML element(s).

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.

All selectors in jQuery start with the dollar sign and parentheses: $().


===The element Selector===

The jQuery element selector selects elements based on the e

lement name.




You can select all <p> elements on a page like this:

$("p")

===The #id Selector===

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of the HTML element:




$("#test")



===The .class Selector===

The jQuery class selector finds elements with a specific class.




To find elements with a specific class, write a period character, followed by the name of the class:




$(".test")



$("*") Selects all elements

$(this) Selects the current HTML element

$("p.intro") Selects all <p> elements with class="intro"

$("p:first") Selects the first <p> element

$("ul li:first") Selects the first <li> element of the first <ul>

$("ul li:first-child") Selects the first <li> element of every <ul>

$("[href]") Selects all elements with an href attribute

$("a[target='_blank']") Selects all <a> elements with a target attribute value equal to "_blank"

$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT equal to "_blank"

$(":button") Selects all <button> elements and <input> elements of type="button"

$("tr:even") Selects all even <tr> elements

$("tr:odd") Selects all odd <tr> elements



Events

Here are some common DOM events:

Mouse Events Keyboard Events Form Events Document/Window Events

click keypress submit load

dblclick keydown change resize

mouseenter keyup focus scroll

mouseleave blur unload




===jQuery Syntax For Event Methods===

In jQuery, most DOM events have an equivalent jQuery method.




To assign a click event to all paragraphs on a page, you can do this:
$("p").click();

The next step is to define what should happen when the event fires. You must pass a function to the event:




$("p").click(function(){

// action goes here!!

});




===Commonly Used jQuery Event Methods===

$(document).ready()

The $(document).ready() method allows us to execute a function when the document is fully loaded. This event is already explained in the jQuery Syntax chapter.




==click()==

The click() method attaches an event handler function to an HTML element. The function is executed when the user clicks on the HTML element.




The following example says: When a click event fires on a <p> element; hide the current <p> element:




<code>

$("p").click(function(){

$(this).hide();

});

</code>




==dblclick()==

The dblclick() method attaches an event handler function to an HTML element. The function is executed when the user double-clicks on the HTML element:




<code>

$("p").dblclick(function(){

$(this).hide();

});

</code>




==mouseenter()==

The mouseenter() method attaches an event handler function to an HTML element. The function is executed when the mouse pointer enters the HTML element:




<code>

$("#p1").mouseenter(function(){

alert("You entered p1!");

});

</code>
==mouseleave()==
The mouseleave() method attaches an event handler function to an HTML element. The function is executed when the mouse pointer leaves the HTML element:
<code>
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});
<code>
==mousedown()==
The mousedown() method attaches an event handler function to an HTML element. The function is executed, when the left, middle or right mouse button is pressed down, while the mouse is over the HTML element:

<code>
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});
</code>
==mouseup()==
The mouseup() method attaches an event handler function to an HTML element. The function is executed, when the left, middle or right mouse button is released, while the mouse is over the HTML element:

<code>

$("#p1").mouseup(function(){

alert("Mouse up over p1!");

});

</code>




==hover()==

The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods. The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:




<code>

$("#p1").hover(function(){

alert("You entered p1!");

},

function(){

alert("Bye! You now leave p1!");

});

</code>
==focus()==

The focus() method attaches an event handler function to an HTML form field. The function is executed when the form field gets focus:
<code>
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});
</code>
==blur()==
The blur() method attaches an event handler function to an HTML form field. The function is executed when the form field loses focus:
<code>
$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});
</code>
==The on() Method==
The on() method attaches one or more event handlers for the selected elements.
Attach multiple event handlers to a <p> element:

<code>
$("p").on({
mouseenter: function(){
$(this).css("background-color", "lightgray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
},
click: function(){
$(this).css("background-color", "yellow");
}
});

</code>



jQuery Effects

===hide/show===

Syntax:




$(selector).hide(speed,callback);

$(selector).show(speed,callback);




The optional speed parameter specifies the speed of the hiding/showing, and can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the hide() or show() method completes.

<code>

$("#hide").click(function(){

$("p").hide();

});




$("#show").click(function(){

$("p").show();

});

</code>

===toggle===

Syntax:

$(selector).toggle(speed,callback);



The optional speed parameter can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after toggle() completes.




===fadeIn()===

Syntax:

  $(selector).fadeIn(speed,callback);

The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the fading completes.

The following example demonstrates the fadeIn() method with different parameters:

===fadeOut()===

The jQuery fadeOut() method is used to fade out a visible element.


  $(selector).fadeOut(speed,callback);

  

The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.

The optional callback parameter is a function to be executed after the fading completes.

===fadeToggle()===

The jQuery fadeToggle() method toggles between the fadeIn() and fadeOut() methods.


If the elements are faded out, fadeToggle() will fade them in.

If the elements are faded in, fadeToggle() will fade them out.


Syntax:

$(selector).fadeToggle(speed,callback);

The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.


The optional callback parameter is a function to be executed after the fading completes.

===fadeTo()===

The jQuery fadeTo() method allows fading to a given opacity (value between 0 and 1).

  $(selector).fadeTo(speed,opacity,callback);

The required speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or milliseconds.


The required opacity parameter in the fadeTo() method specifies fading to a given opacity (value between 0 and 1).

The optional callback parameter is a function to be executed after the function completes.


jQuery HTML Manipulation

Methods for DOM manipulation as following. They also come with a callback function. The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) value. You then return the string you wish to use as the new value from the function.

===text()===

Sets or returns the text content of selected elements

   $("#test1").text("Hello world!");


<code>

  $("#btn1").click(function(){

    $("#test1").text(function(i, origText){

        return "Old text: " + origText + " New text: Hello world!

        (index: " + i + ")"; 

    });

});

</code>

===html()===

Sets or returns the content of selected elements (including HTML markup)

   $("#test2").html("<b>Hello world!</b>");

   

<code>

$("#btn2").click(function(){

    $("#test2").html(function(i, origText){

        return "Old html: " + origText + " New html: Hello <b>world!</b>

        (index: " + i + ")"; 

    });

});

</code>

===val()===

Sets or returns the value of form fields

   $("#test3").val("Dolly Duck");


===attr()===

Method is used to get or set attribute values.

<code>

$("button").click(function(){

    $("#w3s").attr({

        "href" : "http://www.w3schools.com/jquery",

        "title" : "W3Schools jQuery Tutorial"

    });

});

</code>

With a callback function :

<code>

$("button").click(function(){

    $("#w3s").attr("href", function(i, origValue){

        return origValue + "/jquery"; 

    });

});

</code>


===append()===

Inserts content at the end of the selected elements

  $("p").append("Some appended text.");


==Multiple Append==

<code>

function appendText() {

    var txt1 = "<p>Text.</p>";               // Create element with HTML  

    var txt2 = $("<p></p>").text("Text.");   // Create with jQuery

    var txt3 = document.createElement("p");  // Create with DOM

    txt3.innerHTML = "Text.";

    $("body").append(txt1, txt2, txt3);      // Append the new elements 

}

</code>

===prepend()===

Inserts content at the beginning of the selected elements

  $("p").prepend("Some prepended text.");

===after()===

Inserts content after the selected elements

===before()===

Inserts content before the selected elements


===Remove Elements/Content===

To remove elements and content, there are mainly two jQuery methods:


==remove()==

Removes the selected element (and its child elements)

The jQuery remove() method also accepts one parameter, which allows you to filter the elements to be removed.


The parameter can be any of the jQuery selector syntaxes.


The following example removes all <p> elements with class="test":  

  $("p").remove(".test");

This example removes all <p> elements with class="test" and class="demo":  

  $("p").remove(".test, .demo");

==empty()==

Removes the child elements from the selected element


==addClass()==

Adds one or more classes to the selected elements

<code>

$("button").click(function(){

    $("h1, h2, p").addClass("blue");

    $("div").addClass("important");

});

</code>

==removeClass()==

Removes one or more classes from the selected elements

<code>

$("button").click(function(){

    $("h1, h2, p").removeClass("blue");

});

</code>

==toggleClass()==

Toggles between adding/removing classes from the selected elements

<code>

$("button").click(function(){

    $("h1, h2, p").toggleClass("blue");

});

</code>

==css()==

Sets or returns the style attribute

=Return a CSS Property=

To return the value of a specified CSS property, use the following syntax:

  css("propertyname");

The following example will return the background-color value of the FIRST matched element:

  $("p").css("background-color");

=Set a CSS Property=

To set a specified CSS property, use the following syntax:

  css("propertyname","value");

The following example will set the background-color value for ALL matched elements:

  $("p").css("background-color", "yellow");

=Set multiple CSS Properties=

To set multiple CSS properties, use the following syntax:

  css({"propertyname":"value","propertyname":"value",...});

The following example will set a background-color and a font-size for ALL matched elements:

  $("p").css({"background-color": "yellow", "font-size": "200%"});

  

====jQuery Dimension Methods====

jQuery has several important methods for working with dimensions:


==width()==

The width() method sets or returns the width of an element (excludes padding, border and margin).

==height()==

The height() method sets or returns the height of an element (excludes padding, border and margin).

==innerWidth()==

The innerWidth() method returns the width of an element (includes padding).

==innerHeight()==

The innerHeight() method returns the height of an element (includes padding).

==outerWidth()==

The outerWidth() method returns the width of an element (includes padding and border).

==outerHeight()==

The outerHeight() method returns the height of an element (includes padding and border).


Traversing

jQuery traversing, which means "move through", are used to "find" (or select) HTML elements based on their relation to other elements. Start with one selection and move through that selection until you reach the elements you desire.


With jQuery traversing, you can easily move up (ancestors), down (descendants) and sideways (siblings) in the family tree, starting from the selected (current) element. This movement is called traversing - or moving through - the DOM.


===parent()===

The parent() method returns the direct parent element of the selected element.


This method only traverse a single level up the DOM tree.

The following example returns the direct parent element of each <span> elements:


<code>

$(document).ready(function(){

    $("span").parent();

});

</code>

===parents()===

The parents() method returns all ancestor elements of the selected element, all the way up to the document's root element (<html>).


The following example returns all ancestors of all <span> elements:

<code>

$(document).ready(function(){

    $("span").parents();

});

</code>


You can also use an optional parameter to filter the search for ancestors.


The following example returns all ancestors of all <span> elements that are <ul> elements:

<code>

$(document).ready(function(){

    $("span").parents("ul");

});

</code>

===parentsUntil()===

The parentsUntil() method returns all ancestor elements between two given arguments.


The following example returns all ancestor elements between a <span> and a <div> element:


<code>

$(document).ready(function(){

    $("span").parentsUntil("div");

});

</code>


===children()===

The children() method returns all direct children of the selected element.


This method only traverse a single level down the DOM tree.

The following example returns all elements that are direct children of each <div> elements:


<code>

$(document).ready(function(){

    $("div").children();

});

</code>


You can also use an optional parameter to filter the search for children.


The following example returns all <p> elements with the class name "first", that are direct children of <div>:


<code>

$(document).ready(function(){

    $("div").children("p.first");

});

</code>

===find()===

The find() method returns descendant elements of the selected element, all the way down to the last descendant.


The following example returns all <span> elements that are descendants of <div>:


<code>

$(document).ready(function(){

    $("div").find("span");

});

</code>


The following example returns all descendants of <div>:


<code>

$(document).ready(function(){

    $("div").find("*");

});

</code>


===siblings()===

The siblings() method returns all sibling elements of the selected element.

===next()===

The next() method returns the next sibling element of the selected element.

===nextAll()===

The nextAll() method returns all next sibling elements of the selected element.

===nextUntil()===

The nextUntil() method returns all next sibling elements between two given arguments.


The following example returns all sibling elements between a <h2> and a <h6> element:


<code>

$(document).ready(function(){

    $("h2").nextUntil("h6");

});

</code>

===prev()===

===prevAll()===

===prevUntil()===


====Filtering====

===first()===

The first() method returns the first element of the selected elements.


The following example selects the first <p> element inside the first <div> element:


<code>

$(document).ready(function(){

    $("div p").first();

});

</code>

===last()===

The last() method returns the last element of the selected elements.


The following example selects the last <p> element inside the last <div> element:


<code>

$(document).ready(function(){

    $("div p").last();

});

</code>


=== eq() ===

The eq() method returns an element with a specific index number of the selected elements.


The index numbers start at 0, so the first element will have the index number 0 and not 1. The following example selects the second <p> element (index number 1):


<code>

$(document).ready(function(){

    $("p").eq(1);

});

</code>

===filter()===

The filter() method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.


The following example returns all <p> elements with class name "intro":


<code>

$(document).ready(function(){

    $("p").filter(".intro");

});

</code>

===not()===

The not() method returns all elements that do not match the criteria.

Tip: The not() method is the opposite of filter().

The following example returns all <p> elements that do not have class name "intro":


<code>

$(document).ready(function(){

    $("p").not(".intro");

});

</code>

Commentaires

Posts les plus consultés de ce blog

Base de Données Sybase IQ

Sécurité des Applications

Principes de la Programmation Orientée Objet