jQuery library can be downloaded from www.jquery.com
Adding The Library To Your Code
<!DOCTYPE html> <html> <head><title>Page Title</title></head> <script src='link_to_jquery_library_code'></script> <body><body> </html>
<!DOCTYPE html>
<html>
<head><title>Page Title</title></head>
<script src='link_to_jquery_library_code'></script>
<body><body>
</html>
Basic Syntax
$("selector").action()
$("selector").action()
- The
$
accesses the query library. - The
("selector")
finds HTML elements. - The
action()
is performed on the elements.
E.g.
$('p').hide() //hides all <p> elements $(".demo").hide() //hides all elements with class="demo" $("#demo").hide() //hides all elements with id="demo"
$('p').hide() //hides all <p> elements
$(".demo").hide() //hides all elements with class="demo"
$("#demo").hide() //hides all elements with id="demo"
Samples:
$("div") //selects all <div> elements $("#test") //selects all elements with id="test" $(".menu") //selects all elements with class="menu" $("div.menu") //selects all <div> elements with class="menu" $("div#test") //selects all <div> elements with id="test" $("p:first") //selects the first <p> element $("h1, p") //selects all <h1> and all <p> elements $("div p") //selects all <p> elements that are descendants of <div> $('*') //selects all elements in the DOM $(":contains('orange')") //selects all elements that contains the text, 'orange' $("[src]") //selects all elements with an src attribute $(":input") //selects all input elements $(":text") //selects all input elements with type="text"
$("div") //selects all <div> elements
$("#test") //selects all elements with id="test"
$(".menu") //selects all elements with class="menu"
$("div.menu") //selects all <div> elements with class="menu"
$("div#test") //selects all <div> elements with id="test"
$("p:first") //selects the first <p> element
$("h1, p") //selects all <h1> and all <p> elements
$("div p") //selects all <p> elements that are descendants of <div>
$('*') //selects all elements in the DOM
$(":contains('orange')") //selects all elements that contains the text, 'orange'
$("[src]") //selects all elements with an src attribute
$(":input") //selects all input elements
$(":text") //selects all input elements with type="text"
- The
attr()
method is used for getting the value of an attribute.
E.g.
<a href="github.com">Click here</a>
<a href="github.com">Click here</a>
//jQuery $(function(){ var val = $('a').attr("href"); alert(val); }); //alerts "github.com"
//jQuery
$(function(){
var val = $('a').attr("href");
alert(val);
});
//alerts "github.com"
- The
attr()
method also allows us to set a value for an attribute by specifying it as a second parameter.
E.g.
$(function() { $('a').attr("href", "jquery.com"); }); //This will change the href attribute of the <a> element to the provided value
$(function() {
$('a').attr("href", "jquery.com");
});
//This will change the href attribute of the <a> element to the provided value
- The
removeAttr()
method is used for removing any attribute of an element.
E.g.
//removes border attribute $("table").removeAttr("border"); //removes class attribute $("table").removeAttr("class");
//removes border attribute
$("table").removeAttr("border");
//removes class attribute
$("table").removeAttr("class");
The html()
method is used to get the content of the selected element, including the heml markup.
<p> jQuery is <b>fun</b> fun </p>
<p>
jQuery is <b>fun</b> fun
</p>
//jQuery $(function() { var val = $('p').html(); console.log(val); }); //outputs: jQuery is <b>fun</b>
//jQuery
$(function() {
var val = $('p').html();
console.log(val);
});
//outputs: jQuery is <b>fun</b>
- The
text()
method is used to get the text content without the html markup.
$(function() { var val = $('p').text(); console.log(val) });
$(function() {
var val = $('p').text();
console.log(val)
});
- It can also be used to change the text content by specifying a parameter.
Sample:
$(function() { $("#test").text("Hello"); });
$(function() {
$("#test").text("Hello");
});
- The
var
method is used to get the values of form fields such as text boxes, drop downs and similar inputs.
E.g.
<input type="text" id="name" value="Username" />
<input type="text" id="name" value="Username" />
$(function() { console.log($("#name").val()); });
$(function() {
console.log($("#name").val());
});
- The value for the field can be set by providing it as a parameter to the
val()
method.
addClass()
- The
addClass()
method adds one or more classes to selected elements.
E.g.
<div>Some text</div>
<div>Some text</div>
.header { color: blue; font-size: x-large; }
.header {
color: blue;
font-size: x-large;
}
$("div").addClass("header");
$("div").addClass("header");
- To specify multiple classes within the
addclass()
method, just separate them using spaces.
removeClass()
The removeClass()
method removes one or more class names from the selected elements.
E.g.
$("div").removeClass("red");
$("div").removeClass("red");
toggleClass()
It toggles between removing and adding classes from the selected elements; meaning that if the specified class exists for the element, it is removed; else it is added.
E.g.
<p>Some text</p> <button>Toggle class</button>
<p>Some text</p>
<button>Toggle class</button>
.red { color: red; font-weight: bold; }
.red {
color: red;
font-weight: bold;
}
//toggles the class "red" upon clicking the button $(function() { $("button").click(function() { $('p').toggleClass("red"); }); });
//toggles the class "red" upon clicking the button
$(function() {
$("button").click(function() {
$('p').toggleClass("red");
});
});
- It is used to get and/or set css property values.
Sample:
<p>Some text</p>
<p>Some text</p>
p { background-color: red; color: white; }
p {
background-color: red;
color: white;
}
$(function() { //Outputs the current background color of p console.log($('p').css("background-color")); //sets the background color to blue $('p').css("background-color", "blue"); });
$(function() {
//Outputs the current background color of p
console.log($('p').css("background-color"));
//sets the background color to blue
$('p').css("background-color", "blue");
});
- To set multiple css properties, the
css()
method uses the JSON syntax:css({"property": "value", "property": "value", ...});
css({"property": "value", "property": "value", ...});
- The
width()
andheight()
methods can be used to get and set the width and height of HTML elements.
E.g.
//sets both width and height to 100px $("div").width(100); $("div").height(100);
//sets both width and height to 100px
$("div").width(100);
$("div").height(100);
- They get and/or set the dimensions without the padding, borders and margins.
- The
innerWidth()
andinnerHeight()
methods include the padding. - The
outerWidth()
andouterHeight()
methods include the padding and the borders.
-
The
parent()
method returns the direct parent element of the selected element.
E.g.<div> Div element <p>Paragraph</p> </div>
<div> Div element <p>Paragraph</p> </div>
var e = $('p').parent(); e.css("border", "2px solid red")
var e = $('p').parent(); e.css("border", "2px solid red")
-
The
parent()
method moves one level up the DOM tree. -
The
children()
method selects all direct children of the selected element. -
siblings()
method returns all siblings' elements. -
next()
returns the next sibling element. -
nextAll()
returns all the next sibling elements. -
prev()
returns previous sibling element of the selected element. -
prevAll()
returns all previous sibling elements of the selected element. -
The
eq()
method returns an element with a soecific index number of the selected elements.
E.g.$("div").eq(2); //This returns the 3rd 'div' element
$("div").eq(2); //This returns the 3rd 'div' element
-
The
remove()
method removes selected elements.
E.g.<p style="color: red;">Red</p> <p style="color: blue;">Blue</p> <p style="color: green">Green</p>
<p style="color: red;">Red</p> <p style="color: blue;">Blue</p> <p style="color: green">Green</p>
$('p').eq(1).remove();
$('p').eq(1).remove();
This removes selected elements as well as its child elements.
-
The
empty()
method is used to remove the child elements of selected elements.$("div").empty();
$("div").empty();
E.g.
$("#demo").click(funcction(){ $("body").html(Date()); });
$("#demo").click(funcction(){
$("body").html(Date());
});
Common Events
Mouse Events
- Click occurs when an element is clicked.
- dblclick occurs when an element is double-clicked.
- mouseenter occurs when the mouse pointer enters the selected elements.
- mouseleaves occurs when the mouse pointer leaves the selected elements.
- mouseover occurs when the mouse pointer is over the selected elements.
Keyboard Events
- keydown occurs when a keyboard key is pressed down.
- keyup occurs when a keyboard key is released.
Form Events
- submit occurs when a form is submitted.
- change occurs when the value of an object has been changed.
- focus occurs when an element gets focus.
- blur occurs when an element loses focus.
Document Events
- ready occurs when the document has been loaded.
- resize occurs when a browser window changes size.
- scroll occurs when a user scrolls in the specified element.
Samples:
<input type="text" id="name" /> <div id="msg"></div>
<input type="text" id="name" />
<div id="msg"></div>
$("#name").keydown(function(){ $("#msg").html($("#name").val()); }); //assigns the content of div, the value of the input field.
$("#name").keydown(function(){
$("#msg").html($("#name").val());
});
//assigns the content of div, the value of the input field.
Note
- To handle events, you can also use the
on()
method. It attaches an event to the selected element.
E.g.$('p').on("click", function(){ console.log("clicked"); });
$('p').on("click", function(){ console.log("clicked"); });
- Multiple event names can be handled by separating them with spaces in the first arguement to pass the same function.
- Event handlers can be removed using
off()
method.
E.g.$("div").on("click", function(){ console.log("Hi there!"); $("div").off("click"); });
$("div").on("click", function(){ console.log("Hi there!"); $("div").off("click"); });
The arguement of the
off()
method is the event name you want to remove the handler for.
- You can trigger events programmatically using the
trigger()
method (without the user necessarily initiating the event).
E.g.$("div").on("click", function(){ console.log("Clicked"); $("div").trigger("click"); });
$("div").on("click", function(){ console.log("Clicked"); $("div").trigger("click"); });
append()
inserts content at the end of selected elements.prepend()
inserts content at the beginning of selected elements.after()
inserts content after the selected elements.before()
inserts the content before the selected elements.
Sample:
<p id="demo">Hi</p>
<p id="demo">Hi</p>
$(function() { $("#demo").append("David"); }); //Output: Hi David $(function() { $("#demo").before("<b>Good day!<b/>"); }); //Output: Good day (in bold)! Hi David $(function() { $("#demo").after("<i>Welcome<i/>"); }); //Good day (in bold)! Hi David Welcome $(function() { var txt = $("<p></p>").text("Hi"); //This creates a new <p> element which contains the text, "Hi" });
$(function() {
$("#demo").append("David");
});
//Output: Hi David
$(function() {
$("#demo").before("<b>Good day!<b/>");
});
//Output: Good day (in bold)! Hi David
$(function() {
$("#demo").after("<i>Welcome<i/>");
});
//Good day (in bold)! Hi David Welcome
$(function() {
var txt = $("<p></p>").text("Hi");
//This creates a new <p> element which contains the text, "Hi"
});