Finds all divs and makes a border. Then adds all paragraphs to the jQuery object to set their backgrounds yellow.
$("div").css("border", "2px solid red")
.add("p")
.css("background", "yellow");
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<p>Added this... (notice no border)</p>
Adds more elements, matched by the given expression, to the set of matched elements.
$("p").add("span").css("background", "yellow");
<p>Hello</p><span>Hello Again</span>
Adds more elements, created on the fly, to the set of matched elements.
$("p").clone().add("<span>Again</span>").appendTo(document.body);
<p>Hello</p>
Adds one or more Elements to the set of matched elements.
$("p").add(document.getElementById("a")).css("background", "yellow");
<p>Hello</p><span id="a">Hello Again</span>
Adds the class 'selected' to the matched elements.
$("p:last").addClass("selected");
<p>Hello</p>
<p>and</p>
<p>Goodbye</p>
Adds the classes 'selected' and 'highlight' to the matched elements.
$("p:last").addClass("selected highlight");
<p>Hello</p>
<p>and</p>
<p>Goodbye</p>
Inserts some HTML after all paragraphs.
$("p").after("<b>Hello</b>");
<p>I would like to say: </p>
Inserts a DOM element after all paragraphs.
$("p").after( document.createTextNode("Hello") );
<p>I would like to say: </p>
Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs.
$("p").after( $("b") );
<b>Hello</b>
<p>I would like to say: </p>
Show a message when an AJAX request completes.
$("#msg").ajaxComplete(function(request, settings){
$(this).append("<li>Request Complete.</li>");
});
Show a message when an AJAX request fails.
$("#msg").ajaxError(function(request, settings){
$(this).append("<li>Error requesting page " + settings.url + "</li>");
});
Show a message before an AJAX request is sent.
$("#msg").ajaxSend(function(evt, request, settings){
$(this).append("<li>Starting request at " + settings.url + "</li>");
});
Show a loading message whenever an AJAX request starts (and none is already active).
$("#loading").ajaxStart(function(){
$(this).show();
});
Hide a loading message after all the AJAX requests have stopped.
$("#loading").ajaxStop(function(){
$(this).hide();
});
Show a message when an AJAX request completes successfully.
$("#msg").ajaxSuccess(function(evt, request, settings){
$(this).append("<li>Successful Request!</li>");
});
Finds every element (including head, body, etc).
$("*").css("border","3px solid red");
<div>DIV</div>
<span>SPAN</span>
<p>P <button>Button</button></p>
A common way to find all elements is to set the 'context' to document.body so elements like head, script, etc are left out.
$("*", document.body).css("border","3px solid red");
Find all divs, and all the paragraphs inside of them, and give them both classnames. Notice the div doesn't have the yellow background color since it didn't use andSelf().
$("div").find("p").andSelf().addClass("border");
$("div").find("p").addClass("background");
<div>
<p>First Paragraph</p>
<p>Second Paragraph</p>
</div>
The first button shows how an unqueued animation works. It expands the div out to 90% width '''while''' the font-size is increasing. Once the font-size change is complete, the border animation will begin. The second button starts a traditional chained animation, where each animation will start once the previous animation on the element has completed.
$("#go1").click(function(){
$("#block1").animate( { width:"90%" }, { queue:false, duration:3000 } )
.animate( { fontSize:"24px" }, 1500 )
.animate( { borderRightWidth:"15px" }, 1500);
});
$("#go2").click(function(){
$("#block2").animate( { width:"90%"}, 1000 )
.animate( { fontSize:"24px" } , 1000 )
.animate( { borderLeftWidth:"15px" }, 1000);
});
$("#go3").click(function(){
$("#go1").add("#go2").click();
});
$("#go4").click(function(){
$("div").css({width:"", fontSize:"", borderWidth:""});
});
<button id="go1">» Animate Block1</button>
<button id="go2">» Animate Block2</button>
<button id="go3">» Animate Both</button>
<button id="go4">» Reset</button>
<div id="block1">Block1</div>
<div id="block2">Block2</div>
Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.
$("p").animate({
"height": "toggle", "opacity": "toggle"
}, { duration: "slow" });
Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. It also will do it ''outside'' the queue, meaning it will automatically start without waiting for its turn.
$("p").animate({
left: "50px", opacity: 1
}, { duration: 500, queue: false });
An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function.
$("p").animate({
"opacity": "show"
}, { "duration": "slow", "easing": "easein" });
Click the button to animate the div with a number of different properties.
// Using multiple unit types within one animation.
$("#go").click(function(){
$("#block").animate({
width: "70%",
opacity: 0.4,
marginLeft: "0.6in",
fontSize: "3em",
borderWidth: "10px"
}, 1500 );
});
<button id="go">» Run</button>
<div id="block">Hello!</div>
Shows a div animate with a relative move. Click several times on the buttons to see the relative animations queued up.
$("#right").click(function(){
$(".block").animate({"left": "+=50px"}, "slow");
});
$("#left").click(function(){
$(".block").animate({"left": "-=50px"}, "slow");
});
<button id="left">«</button> <button id="right">»</button>
<div class="block"></div>
Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.
$("p").animate({
"height": "toggle", "opacity": "toggle"
}, "slow");
Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds.
$("p").animate({
"left": "50", "opacity": 1
}, 500);
An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. Note, this code will do nothing unless the paragraph element is hidden.
$("p").animate({
"opacity": "show"
}, "slow", "easein");
Change the color of any div that is animated.
$("#run").click(function(){
$("div:animated").toggleClass("colored");
});
function animateIt() {
$("#mover").slideToggle("slow", animateIt);
}
animateIt();
<button id="run">Run</button>
<div></div>
<div id="mover"></div>
<div></div>
Appends some HTML to all paragraphs.
$("p").append("<b>Hello</b>");
<p>I would like to say: </p>
Appends an Element to all paragraphs.
$("p").append(document.createTextNode("Hello"));
<p>I would like to say: </p>
Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
$("p").append( $("b") );
<b>Hello</b><p>I would like to say: </p>
Appends all spans to the element with the ID "foo"
$("span").appendTo("#foo"); // check append() examples
<span>I have nothing more to say... </span>
<div id="foo">FOO! </div>
Finds the title attribute of the first <em> in the page.
var title = $("em").attr("title");
$("div").text(title);
<p>
Once there was a <em title="huge, gigantic">large</em> dinosaur...
</p>
The title of the emphasis is:<div></div>
Set some attributes for all <img>s in the page.
$("img").attr({
src: "/images/hat.gif",
title: "jQuery",
alt: "jQuery Logo"
});
$("div").text($("img").attr("alt"));
<img />
<img />
<img />
<div></div>
Disables buttons greater than the 0th button.
$("button:gt(0)").attr("disabled","disabled");
<button>0th Button</button>
<button>1st Button</button>
<button>2nd Button</button>
Sets id for divs based on the position in the page.
$("div").attr("id", function (arr) {
return "div-id" + arr[0];
})
.each(function () {
$("span", this).html("(ID = '<b>" + this.id + "</b>')");
});
<div>Zero-th <span></span></div>
<div>First <span></span></div>
<div>Second <span></span></div>
Sets src attribute from title attribute on the image.
$("img").attr("src", function() {
return "/images/" + this.title;
});
<img title="hat.gif"/>
<img title="hat-old.gif"/>
<img title="hat2-old.gif"/>
Finds all inputs that with a name attribute that contains 'man' and sets the value with some text.
$("input[name*='man']").val("has man in it!");
<input name="man-news" />
<input name="milkman" />
<input name="letterman2" />
<input name="newmilk" />
Finds all inputs with an attribute name that ends with 'letter' and puts text in them.
$("input[name$='letter']").val("a letter");
<input name="newsletter" />
<input name="milkman" />
<input name="jobletter" />
Finds all inputs with name 'newsletter' and changes the text of the span next to it.
$("input[name='newsletter']").next().text(" is newsletter");
<div>
<input type="radio" name="newsletter" value="Hot Fuzz" />
<span>name?</span>
</div>
<div>
<input type="radio" name="newsletter" value="Cold Fusion" />
<span>name?</span>
</div>
<div>
<input type="radio" name="accept" value="Evil Plans" />
<span>name?</span>
</div>
Bind a single click that adds the div id to its text.
$("div[id]").one("click", function(){
var idString = $(this).text() + " = " + $(this).attr("id");
$(this).text(idString);
});
<div>no id</div>
<div id="hey">with id</div>
<div id="there">has an id</div>
<div>nope</div>
Finds all inputs that have an id attribute and whose name attribute ends with man and sets the value.
$("input[id][name$='man']").val("only this one");
<input id="man-news" name="man-news" />
<input name="milkman" />
<input id="letterman" name="new-letterman" />
<input name="newmilk" />
Finds all inputs that don't have the name 'newsletter' and changes the text of the span next to it.
$("input[name!='newsletter']").next().text(" is not newsletter");
<div>
<input type="radio" name="newsletter" value="Hot Fuzz" />
<span>name?</span>
</div>
<div>
<input type="radio" name="newsletter" value="Cold Fusion" />
<span>name?</span>
</div>
<div>
<input type="radio" name="accept" value="Evil Plans" />
<span>name?</span>
</div>
Finds all inputs with an attribute name that starts with 'news' and puts text in them.
$("input[name^='news']").val("news here!");
<input name="newsletter" />
<input name="milkman" />
<input name="newsboy" />
Inserts some HTML before all paragraphs.
$("p").before("<b>Hello</b>");
<p> is what I said...</p>
Inserts a DOM element before all paragraphs.
$("p").before( document.createTextNode("Hello") );
<p> is what I said...</p>
Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs.
$("p").before( $("b") );
<p> is what I said...</p><b>Hello</b>
Handle click and double-click for the paragraph. Note: the coordinates are window relative so in this case relative to the demo iframe.
$("p").bind("click", function(e){
var str = "( " + e.pageX + ", " + e.pageY + " )";
$("span").text("Click happened! " + str);
});
$("p").bind("dblclick", function(){
$("span").text("Double-click happened in " + this.tagName);
});
<p>Click or double click here.</p>
<span></span>
To display each paragraph's text in an alert box whenever it is clicked:
$("p").bind("click", function(){
alert( $(this).text() );
});
You can pass some extra data before the event handler:
function handler(event) {
alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)
To cancel a default action and prevent it from bubbling up, return false:
$("form").bind("submit", function() { return false; })
To cancel only the default action by using the preventDefault method.
$("form").bind("submit", function(event){
event.preventDefault();
});
Stop only an event from bubbling by using the stopPropagation method.
$("form").bind("submit", function(event){
event.stopPropagation();
});
Can bind custom events too.
$("p").bind("myCustomEvent", function(e, myName, myValue){
$(this).text(myName + ", hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent", [ "John" ]);
});
<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
To triggers the blur event on all paragraphs:
$("p").blur();
To pop up an alert saying "Hello World!" every time any paragraph's blur event triggers:
$("p").blur( function () { alert("Hello World!"); } );
Attaches a change even to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
<select name="sweets" multiple="multiple">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Carmel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div></div>
To add a validity test to all text input elements:
$("input[@type='text']").change( function() {
// check input for validity here
});
Finds all checkbox inputs.
var input = $(":checkbox").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="checkbox" />
<input type="file" />
<input type="hidden" />
<input type="image" />
<input type="password" />
<input type="radio" />
<input type="reset" />
<input type="submit" />
<input type="text" />
<select><option>Option<option/></select>
<textarea></textarea>
<button>Button</button>
</form>
<div>
</div>
Finds all input elements that are checked.
function countChecked() {
var n = $("input:checked").length;
$("div").text(n + (n == 1 ? " is" : " are") + " checked!");
}
countChecked();
$(":checkbox").click(countChecked);
<form>
<input type="checkbox" name="newsletter" checked="checked" value="Hourly" />
<input type="checkbox" name="newsletter" value="Daily" />
<input type="checkbox" name="newsletter" value="Weekly" />
<input type="checkbox" name="newsletter" checked="checked" value="Monthly" />
<input type="checkbox" name="newsletter" value="Yearly" />
</form>
<div></div>
[ <input type="checkbox" name="newsletter" checked="checked" value="Daily" />,
<input type="checkbox" name="newsletter" checked="checked" value="Monthly" /> ]
Finds all children of the element with id "main" which is yellow.
$("#main > *").css("border", "3px double red");
<span id="main">
<div></div>
<button>Child</button>
<div class="mini"></div>
<div>
<div class="mini"></div>
<div class="mini"></div>
</div>
<div><button>Grand</button></div>
<div><span>A Span <em>in</em> child</span></div>
<span>A Span in main</span>
</span>
Find all children of the clicked element.
$("#container").click(function (e) {
$("*").removeClass("hilite");
var $kids = $(e.target).children();
var len = $kids.addClass("hilite").length;
$("#results span:first").text(len);
$("#results span:last").text(e.target.tagName);
e.preventDefault();
return false;
});
<div id="container">
<div>
<p>This <span>is the <em>way</em> we</span>
write <em>the</em> demo,</p>
</div>
<div>
<a href="#"><b>w</b>rit<b>e</b></a> the <span>demo,</span> <button>write
the</button> demo,
</div>
<div>
This <span>the way we <em>write</em> the <em>demo</em> so</span>
<input type="text" value="early" /> in
</div>
<p>
<span>t</span>he <span>m</span>orning.
<span id="results">Found <span>0</span> children in <span>TAG</span>.</span>
</p>
</div>
Find all children of each div.
$("div").children().css("border-bottom", "3px double red");
<p>Hello (this is a paragraph)</p>
<div><span>Hello Again (this span is a child of the a div)</span></div>
<p>And <span>Again</span> (in another paragraph)</p>
<div>And One Last <span>Time</span> (most text directly in a div)</div>
Find all children with a class "selected" of each div.
$("div").children(".selected").css("color", "blue");
<div>
<span>Hello</span>
<p class="selected">Hello Again</p>
<div class="selected">And Again</div>
<p>And One Last Time</p>
</div>
Finds the element with the class "myClass".
$(".myClass").css("border","3px solid red");
<div class="notMe">div class="notMe"</div>
<div class="myClass">div class="myClass"</div>
<span class="myClass">span class="myClass"</span>
To trigger the click event on all of the paragraphs on the page:
$("p").click();
To hide paragraphs on a page when they are clicked:
$("p").click(function () {
$(this).slideUp();
});
$("p").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
Clones all b elements (and selects the clones) and prepends them to all paragraphs.
$("b").clone().prependTo("p");
<b>Hello</b><p>, how are you?</p>
<b>Hello</b><p><b>Hello</b>, how are you?</p>
Create a button that's able to clone itself - and have the clones themselves be clonable.
$("button").click(function(){
$(this).clone(true).insertAfter(this);
});
<button>Clone Me!</button>
Finds all divs containing "John" and underlines them.
$("div:contains('John')").css("text-decoration", "underline");
<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn
Find all the text nodes inside a paragraph and wrap them with a bold tag.
$("p").contents().not("[nodeType=1]").wrap("<b/>");
<p>Hello <a href="http://ejohn.org/">John</a>, how are you doing?</p>
Append some new content into an empty iframe.
$("iframe").contents().find("body").append("I'm in an iframe!");
<iframe src="/index-blank.html" width="300" height="100"></iframe>
To access the background color of a clicked div.
$("div").click(function () {
var color = $(this).css("background-color");
$("#result").html("That div is <span style='color:" +
color + ";'>" + color + "</span>.");
});
<span id="result"> </span>
<div style="background-color:blue;"></div>
<div style="background-color:rgb(15,99,30);"></div>
<div style="background-color:#123456;"></div>
<div style="background-color:#f11;"></div>
To set the color of all paragraphs to red and background to blue:
$("p").hover(function () {
$(this).css({ backgroundColor:"yellow", fontWeight:"bolder" });
}, function () {
var cssObj = {
backgroundColor: "#ddd",
fontWeight: "",
color: "rgb(0,40,244)"
}
$(this).css(cssObj);
});
<p>
Move the mouse over a paragraph.
</p>
<p>
Like this one or the one above.
</p>
If the property name includes a "-", put it between quotation marks:
$("p").hover(function () {
$(this).css({ "background-color":"yellow", "font-weight":"bolder" });
}, function () {
var cssObj = {
"background-color": "#ddd",
"font-weight": "",
color: "rgb(0,40,244)"
}
$(this).css(cssObj);
});
<p>
Move the mouse over a paragraph.
</p>
<p>
Like this one or the one above.
</p>
To change the color of any paragraph to red on mouseover event.
$("p").mouseover(function () {
$(this).css("color","red");
});
<p>
Just roll the mouse over me.
</p>
<p>
Or me to see a color change.
</p>
To highlight a clicked word in the paragraph.
var words = $("p:first").text().split(" ");
var text = words.join("</span> <span>");
$("p:first").html("<span>" + text + "</span>");
$("span").click(function () {
$(this).css("background-color","yellow");
});
<p>
Once upon a time there was a man
who lived in a pizza parlor. This
man just loved pizza and ate it all
the time. He went on to be the
happiest man in the world. The end.
</p>
To bind a "Hello World!" alert box the dblclick event on every paragraph on the page:
$("p").dblclick( function () { alert("Hello World!"); });
Use dequeue to end a custom queue function which allows the queue to keep going.
$("button").click(function () {
$("div").animate({left:'+=200px'}, 2000);
$("div").animate({top:'0px'}, 600);
$("div").queue(function () {
$(this).toggleClass("red");
$(this).dequeue();
});
$("div").animate({left:'10px', top:'30px'}, 700);
});
<button>Start</button>
<div></div>
Finds all input descendants of forms.
$("form input").css("border", "2px dotted blue");
<form>
<div>Form is surrounded by the green outline</div>
<label>Child:</label>
<input name="name" />
<fieldset>
<label>Grandchild:</label>
<input name="newsletter" />
</fieldset>
</form>
Sibling to form: <input name="none" />
Finds all input elements that are disabled.
$("input:disabled").val("this is it");
<form>
<input name="email" disabled="disabled" />
<input name="id" />
</form>
Iterates over three divs and sets their color property.
$(document.body).click(function () {
$("div").each(function (i) {
if (this.style.color != "blue") {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
});
<div>Click here</div>
<div>to iterate through</div>
<div>these divs.</div>
If you want to have the jQuery object instead of the regular DOM element, use the $(this) function, for example:
$("span").click(function () {
$("li").each(function(){
$(this).toggleClass("example");
});
});
To do list: <span>(click here to change)</span>
<ul>
<li>Eat</li>
<li>Sleep</li>
<li>Be merry</li>
</ul>
You can use 'return' to break out of each() loops early.
$("button").click(function () {
$("div").each(function (index, domEle) {
// domEle == this
$(domEle).css("backgroundColor", "yellow");
if ($(this).is("#stop")) {
$("span").text("Stopped at div index #" + index);
return false;
}
});
});
<button>Change colors</button>
<span></span>
<div></div>
<div></div>
<div></div>
<div></div>
<div id="stop">Stop here</div>
<div></div>
<div></div>
<div></div>
Finds every DIV element.
$("div").css("border","3px solid red");
<div>DIV1</div>
<div>DIV2</div>
<span>SPAN</span>
Finds all elements that are empty - they don't have child elements or text.
$("td:empty").text("Was empty!").css('background', 'rgb(255,220,200)');
<table border="1">
<tr><td>TD #0</td><td></td></tr>
<tr><td>TD #2</td><td></td></tr>
<tr><td></td><td>TD#5</td></tr>
</table>
Removes all child nodes (including text nodes) from all paragraphs
$("button").click(function () {
$("p").empty();
});
<p>
Hello, <span>Person</span> <a href="javascript:;">and person</a>
</p>
<button>Call empty() on above paragraph</button>
Finds all input elements that are enabled.
$("input:enabled").val("this is it");
<form>
<input name="email" disabled="disabled" />
<input name="id" />
</form>
Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.
jQuery.fn.showTags = function (n) {
var tags = this.map(function () {
return this.tagName;
})
.get().join(", ");
$("b:eq(" + n + ")").text(tags);
return this;
};
$("p").showTags(0)
.find("span")
.showTags(1)
.css("background", "yellow")
.end()
.showTags(2)
.css("font-style", "italic");
<p>
Hi there <span>how</span> are you <span>doing</span>?
</p>
<p>
This <span>span</span> is one of
several <span>spans</span> in this
<span>sentence</span>.
</p>
<div>
Tags in jQuery object initially: <b></b>
</div>
<div>
Tags in jQuery object after find: <b></b>
</div>
<div>
Tags in jQuery object after end: <b></b>
</div>
Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.
$("p").find("span").end().css("border", "2px red solid");
<p><span>Hello</span>, how are you?</p>
Reduces the selection to the second selected element.
$("p").eq(1)
<p>This is just a test.</p><p>So is this</p>
[ <p>So is this</p> ]
Finds the third td. (annoying blink isn't it)
$("td:eq(2)").css("text-decoration", "blink");
<table border="1">
<tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
<tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
<tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>
Turn the div with index 2 red by adding an appropriate class.
$("div").eq(2).addClass("red");
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
To keep a server-side log of JavaScript errors, you might want to:
$(window).error(function(msg, url, line){
jQuery.post("js_error_log.php", { msg: msg, url: url, line: line });
});
To hide JavaScript errors from the user, you can try:
$(window).error(function(){
return true;
});
To hide the "broken image" icons for your IE users, you can try:
$("img").error(function(){
$(this).hide();
});
Finds even table rows, matching the first, third and so on (index 0, 2, 4 etc.).
$("tr:even").css("background-color", "#bbbbff");
<table border="1">
<tr><td>Row with Index #0</td></tr>
<tr><td>Row with Index #1</td></tr>
<tr><td>Row with Index #2</td></tr>
<tr><td>Row with Index #3</td></tr>
</table>
Animates hidden divs to fade in one by one, completing each animation within 600 milliseconds.
$(document.body).click(function () {
$("div:hidden:first").fadeIn("slow");
});
<span>Click here...</span>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
Fades a red block in over the text. Once the animation is done, it quickly fades in more text on top.
$("a").click(function () {
$("div").fadeIn(3000, function () {
$("span").fadeIn(100);
});
return false;
});
<p>
Let it be known that the party of the first part
and the party of the second part are henceforth
and hereto directed to assess the allegations
for factual correctness... (<a href="#">click!</a>)
<div><span>CENSORED!</span></div>
</p>
Animates all paragraphs to fade out, completing the animation within 600 milliseconds.
$("p").click(function () {
$("p").fadeOut("slow");
});
<p>
If you click on this paragraph
you'll see it just fade away.
</p>
Fades out spans in one section that you click on.
$("span").click(function () {
$(this).fadeOut(1000, function () {
$("div").text("'" + $(this).text() + "' has faded!");
$(this).remove();
});
});
$("span").hover(function () {
$(this).addClass("hilite");
}, function () {
$(this).removeClass("hilite");
});
<h3>Find the modifiers - <div></div></h3>
<p>
If you <span>really</span> want to go outside
<span>in the cold</span> then make sure to wear
your <span>warm</span> jacket given to you by
your <span>favorite</span> teacher.
</p>
Animates first paragraph to fade to an opacity of 0.33 (33%, about one third visible), completing the animation within 600 milliseconds.
$("p:first").click(function () {
$(this).fadeTo("slow", 0.33);
});
<p>
Click this paragraph to see it fade.
</p>
<p>
Compare to this one that won't fade.
</p>
Fade div to a random opacity on each click, completing the animation within 200 milliseconds.
$("div").click(function () {
$(this).fadeTo("fast", Math.random());
});
<p>And this is the library that John built...</p>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
Find the right answer! The fade will take 250 milliseconds and change various styles when it completes.
var getPos = function (n) {
return (Math.floor(n) * 90) + "px";
};
$("p").each(function (n) {
var r = Math.floor(Math.random() * 3);
var tmp = $(this).text();
$(this).text($("p:eq(" + r + ")").text());
$("p:eq(" + r + ")").text(tmp);
$(this).css("left", getPos(n));
});
$("div").each(function (n) {
$(this).css("left", getPos(n));
})
.css("cursor", "pointer")
.click(function () {
$(this).fadeTo(250, 0.25, function () {
$(this).css("cursor", "")
.prev().css({"font-weight": "bolder",
"font-style": "italic"});
});
});
<p>Wrong</p>
<div></div>
<p>Wrong</p>
<div></div>
<p>Right!</p>
<div></div>
Finds all file inputs.
var input = $(":file").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="file" />
<input type="hidden" />
<input type="image" />
<input type="password" />
<input type="radio" />
<input type="reset" />
<input type="submit" />
<input type="text" />
<select><option>Option<option/></select>
<textarea></textarea>
<button>Button</button>
</form>
<div>
</div>
Change the color of all divs then put a border around only some of them.
$("div").css("background", "#c8ebcc")
.filter(".middle")
.css("border-color", "red");
<div></div>
<div class="middle"></div>
<div class="middle"></div>
<div class="middle"></div>
<div class="middle"></div>
<div></div>
Selects all paragraphs and removes those without a class "selected".
$("p").filter(".selected")
Selects all paragraphs and removes those that aren't of class "selected" or the first one.
$("p").filter(".selected, :first")
Change the color of all divs then put a border two specific ones.
$("div").css("background", "#b4b0da")
.filter(function (index) {
return index == 1 || $(this).attr("id") == "fourth";
})
.css("border", "3px double red");
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
<div id="fourth"></div>
<div id="fifth"></div>
<div id="sixth"></div>
Remove all elements that have a descendant ol element
$("p").filter(function(index) {
return $("ol", this).length == 0;
});
Starts with all paragraphs and searches for descendant span elements, same as $("p span")
$("p").find("span").css('color','red');
<p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>
Add spans around each word then add a hover and italicize words with the letter '''t'''.
var newText = $("p").text().split(" ").join("</span> <span>");
newText = "<span>" + newText + "</span>";
$("p").html(newText)
.find("span")
.hover(function () { $(this).addClass("hilite"); },
function () { $(this).removeClass("hilite"); })
.end()
.find(":contains('t')")
.css({"font-style":"italic", "font-weight":"bolder"});
<p>
When the day is short
find that which matters to you
or stop believing
</p>
Finds the first table row.
$("tr:first").css("font-style", "italic");
<table>
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
</table>
Finds the first span in each matched div to underline and add a hover state.
$("div span:first-child")
.css("text-decoration", "underline")
.hover(function () {
$(this).addClass("sogreen");
}, function () {
$(this).removeClass("sogreen");
});
<div>
<span>John,</span>
<span>Karl,</span>
<span>Brandon</span>
</div>
<div>
<span>Glen,</span>
<span>Tane,</span>
<span>Ralph</span>
</div>
To focus on a login input box with id 'login' on page startup, try:
$(document).ready(function(){
$("#login").focus();
});
To stop people from writing in text input boxes, try:
$("input[@type=text]").focus(function(){
$(this).blur();
});
Selects all divs in the document and returns the DOM Elements as an Array, then uses the built-in reverse-method to reverse that array.
function disp(divs) {
var a = [];
for (var i = 0; i < divs.length; i++) {
a.push(divs[i].innerHTML);
}
$("span").text(a.join(" "));
}
disp( $("div").get().reverse() );
Reversed - <span></span>
<div>One</div>
<div>Two</div>
<div>Three</div>
Gives the tag name of the element clicked on.
$("*", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
$("span:first").text("Clicked on - " + domEl.tagName);
});
<span> </span>
<p>In this paragraph is an <span>important</span> section</p>
<div><input type="text" /></div>
Finds TD #5 and higher. Reminder: the indexing starts at 0.
$("td:gt(4)").css("text-decoration", "line-through");
<table border="1">
<tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
<tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
<tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>
Adds the class "test" to all divs that have a paragraph inside of them.
$("div:has(p)").addClass("test");
<div><p>Hello in a paragraph</p></div>
<div>Hello again! (with no paragraph)</div>
Check to see if an element has a specific class, and if so, perform an action.
$("div").click(function(){
if ( $(this).hasClass("protected") )
$(this).animate({ left: -10 }, 75)
.animate({ left: 10 }, 75)
.animate({ left: -10 }, 75)
.animate({ left: 10 }, 75)
.animate({ left: 0 }, 75);
});
<span></span><div class="protected"></div>
<span></span><div></div>
<span></span><div></div>
<span></span><div class="protected"></div>
Adds a background and text color to all the headers on the page.
$(":header").css({ background:'#CCC', color:'blue' });
<h1>Header 1</h1>
<p>Contents 1</p>
<h2>Header 2</h2>
<p>Contents 2</p>
Show various heights. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body.
function showHeight(ele, h) {
$("div").text("The height for the " + ele +
" is " + h + "px.");
}
$("#getp").click(function () {
showHeight("paragraph", $("p").height());
});
$("#getd").click(function () {
showHeight("document", $(document).height());
});
$("#getw").click(function () {
showHeight("window", $(window).height());
});
<button id="getp">Get Paragraph Height</button>
<button id="getd">Get Document Height</button>
<button id="getw">Get Window Height</button>
<div> </div>
<p>
Sample paragraph to test height
</p>
To set the height of each div on click to 30px plus a color change.
$("div").one('click', function () {
$(this).height(30)
.css({cursor:"auto", backgroundColor:"green"});
});
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
Hides all paragraphs then the link on click.
$("p").hide();
$("a").click(function () {
$(this).hide();
return false;
});
<p>Hello</p>
<a href="#">Click to hide me too</a>
<p>Here is another paragraph</p>
Animates all shown paragraphs to hide slowly, completing the animation within 600 milliseconds.
$("button").click(function () {
$("p").hide("slow");
});
<button>Hide 'em</button>
<p>Hiya</p>
<p>Such interesting text, eh?</p>
Animates all spans (words in this case) to hide fastly, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one.
$("#hidr").click(function () {
$("span:last-child").hide("fast", function () {
// use callee so don't have to name the function
$(this).prev().hide("fast", arguments.callee);
});
});
$("#showr").click(function () {
$("span").show(2000);
});
<button id="hidr">Hide</button>
<button id="showr">Show</button>
<div>
<span>Once</span> <span>upon</span> <span>a</span>
<span>time</span> <span>there</span> <span>were</span>
<span>three</span> <span>programmers...</span>
</div>
Hides the divs when clicked over 2 seconds, then removes the div element when its hidden. Try clicking on more than one box at a time.
for (var i = 0; i < 5; i++) {
$("<div>").appendTo(document.body);
}
$("div").click(function () {
$(this).hide(2000, function () {
$(this).remove();
});
});
<div></div>
To add a special style to table cells that are being hovered over, try:
$("li").hover(
function () {
$(this).append($("<span> ***</span>"));
},
function () {
$(this).find("span:last").remove();
}
);
<ul>
<li>Milk</li>
<li>Bread</li>
<li>Chips</li>
<li>Socks</li>
</ul>
To add a special style to table cells that are being hovered over, try:
$("td").hover(
function () {
$(this).addClass("hover");
},
function () {
$(this).removeClass("hover");
}
);
Click a paragraph to convert it from html to text.
$("p").click(function () {
var htmlStr = $(this).html();
$(this).text(htmlStr);
});
<p>
<b>Click</b> to change the <span id="tag">html</span>
</p>
<p>
to a <span id="text">text</span> node.
</p>
<p>
This <button name="nada">button</button> does nothing.
</p>
Click a paragraph to convert it from html to text.
$("p").click(function () {
var htmlStr = $(this).html();
$(this).text(htmlStr);
});
<p>
<b>Click</b> to change the <span id="tag">html</span>
</p>
<p>
to a <span id="text">text</span> node.
</p>
<p>
This <button name="nada">button</button> does nothing.
</p>
Add some html to each div.
$("div").html("<span class='red'>Hello <b>Again</b></span>");
<span>Hello</span>
<div></div>
<div></div>
<div></div>
Add some html to each div then immediately do further manipulations to the inserted html.
$("div").html("<b>Wow!</b> Such excitement...");
$("div b").append(document.createTextNode("!!!"))
.css("color", "red");
<div></div>
<div></div>
<div></div>
Add some html to each div.
$("div").html("<span class='red'>Hello <b>Again</b></span>");
<span>Hello</span>
<div></div>
<div></div>
<div></div>
Add some html to each div then immediately do further manipulations to the inserted html.
$("div").html("<b>Wow!</b> Such excitement...");
$("div b").append(document.createTextNode("!!!"))
.css("color", "red");
<div></div>
<div></div>
<div></div>
Finds the element with the id "myDiv".
$("#myDiv").css("border","3px solid red");
<div id="notMe"><p>id="notMe"</p></div>
<div id="myDiv">id="myDiv"</div>
Finds the element with the id "myID.entry[1]". See how certain characters must be escaped with backslashes.
$("#myID\\.entry\\[1\\]").css("border","3px solid red");
<div id="myID.entry[0]">id="myID.entry[0]"</div>
<div id="myID.entry[1]">id="myID.entry[1]"</div>
<div id="myID.entry[2]">id="myID.entry[2]"</div>
Finds all image inputs.
var input = $(":image").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="file" />
<input type="hidden" />
<input type="image" />
<input type="password" />
<input type="radio" />
<input type="reset" />
<input type="submit" />
<input type="text" />
<select><option>Option<option/></select>
<textarea></textarea>
<button>Button</button>
</form>
<div>
</div>
On click, returns the index (based zero) of that div in the page.
$("div").click(function () {
// this is the dom element clicked
var index = $("div").index(this);
$("span").text("That was div index #" + index);
});
<span>Click a div!</span>
<div>First div</div>
<div>Second div</div>
<div>Third div</div>
Returns the index for the element with ID foobar.
$("*").index( $('#foobar')[0] )
<div id="foobar"><b></b><span id="foo"></span></div>
Returns the index for the element with ID foo within another element.
$("*").index( $('#foo')[0] )
<div id="foobar"><b></b><span id="foo"></span></div>
Returns the index for the element clicked within a collection.
var mainNavLinks = $('ul#mainNav li a');
mainNavLinks.click(function(){alert(mainNavLinks.index(this)0;});
Returns -1, as there is no element with ID bar.
$("*").index( $('#bar')[0] )
<div id="foobar"><b></b><span id="foo"></span></div>
Finds all input elements.
var allInputs = $(":input");
var formChildren = $("form > *");
$("div").text("Found " + allInputs.length + " inputs and the form has " +
formChildren.length + " children.")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="file" />
<input type="hidden" />
<input type="image" />
<input type="password" />
<input type="radio" />
<input type="reset" />
<input type="submit" />
<input type="text" />
<select><option>Option</option></select>
<textarea></textarea>
<button>Button</button>
</form>
<div>
</div>
Inserts all paragraphs after an element with id of "foo". Same as $("#foo").after("p")
$("p").insertAfter("#foo"); // check after() examples
<p> is what I said... </p><div id="foo">FOO!</div>
Inserts all paragraphs before an element with id of "foo". Same as $("#foo").before("p")
$("p").insertBefore("#foo"); // check before() examples
<div id="foo">FOO!</div><p>I would like to say: </p>
Shows a few ways is() can be used inside an event handler.
$("div").one('click', function () {
if ($(this).is(":first-child")) {
$("p").text("It's the first div.");
} else if ($(this).is(".blue,.red")) {
$("p").text("It's a blue or red div.");
} else if ($(this).is(":contains('Peter')")) {
$("p").text("It's Peter!");
} else {
$("p").html("It's nothing <em>special</em>.");
}
$("p").hide().slideDown("slow");
$(this).css({"border-style": "inset", cursor:"default"});
});
<div></div>
<div class="blue"></div>
<div></div>
<div class="red"></div>
<div><br/><span>Peter</span></div>
<div class="blue"></div>
<p> </p>
Returns true, because the parent of the input is a form element
var isFormParent = $("input[@type='checkbox']").parent().is("form")
$("div").text("isFormParent = " + isFormParent);
<form><input type="checkbox" /></form>
<div></div>
Returns false, because the parent of the input is a p element
var isFormParent = $("input[@type='checkbox']").parent().is("form")
$("div").text("isFormParent = " + isFormParent);
<form><p><input type="checkbox" /></p></form>
<div></div>
Creates a div element (and all of its contents) dynamically, and appends it to the body element. Internally, an element is created and its innerHTML property set to the given markup. It is therefore both quite flexible and limited.
$("<div><p>Hello</p></div>").appendTo("body")
Do not create <input>-Elements without a type-attribute, due to Microsofts read/write-once-rule for the type-attribute of <input>-elements, see this [http://msdn2.microsoft.com/en-us/library/ms534700.aspx official statement] for details.
// Does NOT work in IE:
$("<input/>").attr("type", "checkbox");
// Does work in IE:
$("<input type='checkbox'/>");
Sets the background color of the page to black.
$(document.body).css( "background", "black" );
Hides all the input elements within a form.
$(myForm.elements).hide()
Executes the function when the DOM is ready to be used.
$(function(){
// Document is ready
});
Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.
jQuery(function($) {
// Your code using failsafe $ alias here...
});
Finds all p elements that are children of a div element.
$("div > p").css("border", "1px solid gray");
<p>one</p> <div><p>two</p></div> <p>three</p>
[ <p>two</p> ]
Finds all inputs of type radio within the first form in the document.
$("input:radio", document.forms[0]);
Finds all div elements within an XML document from an AJAX response.
$("div", xml.responseXML);
Load and execute a JavaScript file.
$.ajax({
type: "GET",
url: "test.js",
dataType: "script"
});
Save some data to the server and notify the user once its complete.
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Retrieve the latest version of an HTML page.
$.ajax({
url: "test.html",
cache: false,
success: function(html){
$("#results").append(html);
}
});
Loads data synchronously. Blocks the browser while the requests is active. It is better to block user interaction by other means when synchronization is necessary.
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
Sends an xml document as data to the server. By setting the processData option to false, the automatic conversion of data to strings is prevented.
var xmlDocument = [create xml document];
$.ajax({
url: "page.php",
processData: false,
data: xmlDocument,
success: handleResponse
});
Sets the defaults for AJAX requests to the url "/xmlhttp/", disables global handlers and uses POST instead of GET. The following AJAX requests then sends some data without having to set anything else.
$.ajaxSetup({
url: "/xmlhttp/",
global: false,
type: "POST"
});
$.ajax({ data: myData });
Returns the box model for the iframe.
$("p").html("The box model for this iframe is: <span>" +
jQuery.boxModel + "</span>");
<p>
</p>
Returns false if the page is in QuirksMode in Internet Explorer
$.boxModel
false
Show the browser info.
jQuery.each(jQuery.browser, function(i, val) {
$("<div>" + i + " : <span>" + val + "</span>")
.appendTo(document.body);
});
<p>Browser info:</p>
Returns true if the current useragent is some version of Microsoft's Internet Explorer
$.browser.msie
Alerts "this is safari!" only for safari browsers
if ($.browser.safari) {
alert("this is safari!");
}
Returns the browser version.
$("p").html("The browser version is: <span>" +
jQuery.browser.version + "</span>");
<p>
</p>
Alerts the version of IE that is being used
if ( $.browser.msie )
alert( $.browser.version );
}
Often you only care about the "major number," the whole number. This can be accomplished with JavaScript's built-in parseInt() function:
if (jQuery.browser.msie) {
alert(parseInt(jQuery.browser.version));
}
Get the store id of an element. It is assigned on the data() function call if one hasn't been assigned yet.
$(document.body).click(function(e) {
var id = jQuery.data(e.target);
$("span").text(id);
});
<div>A div</div>
<div>Another</div>
<p>The id of this div is <span>?</span></p>
Get the data named "blah" stored at for an element.
$("button").click(function(e) {
var adiv = $("div").get(0);
var value;
switch ($("button").index(this)) {
case 0 :
value = jQuery.data(adiv, "blah");
break;
case 1 :
jQuery.data(adiv, "blah", "hello");
value = "Stored!";
break;
case 2 :
jQuery.data(adiv, "blah", 86);
value = "Stored!";
break;
case 3 :
jQuery.removeData(adiv);
value = "Removed!";
break;
}
$("span").text("" + value);
});
<div>A div</div>
<button>Get "blah" from the div</button>
<button>Set "blah" to "hello"</button>
<button>Set "blah" to 86</button>
<button>Remove "blah" from the div</button>
<p>The "blah" value of this div is <span>?</span></p>
Store then retrieve a value from the div element.
var adiv = $("div").get(0);
jQuery.data(adiv, "test", { first: 16, last: "pizza!" });
$("span:first").text(jQuery.data(adiv, "test").first);
$("span:last").text(jQuery.data(adiv, "test").last);
<div>
The values stored were
<span></span>
and
<span></span>
</div>
Filters the original array of numbers leaving that are not 5 and have an index greater than 3. Then it removes all 9s while inverting it.
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>
Iterates over items in an array, accessing both the current item and its index.
$.each( [0,1,2], function(i, n){
alert( "Item #" + i + ": " + n );
});
Iterates over the properties in an object, accessing both the current item and its key.
$.each( { name: "John", lang: "JS" }, function(i, n){
alert( "Name: " + i + ", Value: " + n );
});
Adds two functions into the jQuery namespace.
jQuery.extend({
min: function(a, b) { return a < b ? a : b; },
max: function(a, b) { return a > b ? a : b; }
});
jQuery.min(2,3); // => 2
jQuery.max(4,5); // => 5
Merge settings and options, modifying settings.
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);
settings == { validate: true, limit: 5, name: "bar" }
Merge defaults and options, without modifying the defaults.
var empty = {}
var defaults = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
var settings = $.extend(empty, defaults, options);
settings == { validate: true, limit: 5, name: "bar" }
empty == { validate: true, limit: 5, name: "bar" }
Adds two plugin methods.
jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});
$("input[@type=checkbox]").check();
$("input[@type=radio]").uncheck();
Request the test.php page, but ignore the return results.
$.get("test.php");
Request the test.php page and send some additional data along (while still ignoring the return results).
$.get("test.php", { name: "John", time: "2pm" } );
Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
Alert out the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned).
$.get("test.cgi", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Loads the four most recent cat pictures from the Flickr JSONP API.
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data){
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});
<div id="images"></div>
Load the JSON data from test.js and access a name from the returned JSON data.
$.getJSON("test.js", function(json){
alert("JSON Data: " + json.users[3].name);
});
Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){
alert("JSON Data: " + json.users[3].name);
});
Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.getIfModified("test.php", function(data){
alert("Data Loaded: " + data);
});
Alert out the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).
$.getIfModified("test.cgi", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
list the result of a consultation of pages,php in HTML as an array. by Manuel Gonzalez.
var id=$("#id").attr("value");
$.getJSON("pages.php",{id:id},dates);
function dates(datos)
{
$("#list").html("Name:"+datos[1].name+"<br>"+"Last Name:"+datos[1].lastname+"<br>"+"Address:"+datos[1].address);
}
We load the new [http://jquery.com/plugins/project/color official jQuery Color Animation plugin] dynamically and bind some color animations to occur once the new functionality is loaded.
$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
$("#go").click(function(){
$(".block").animate( { backgroundColor: 'pink' }, 1000)
.animate( { backgroundColor: 'blue' }, 1000);
});
});
<button id="go">» Run</button>
<div class="block"></div>
Load the test.js JavaScript file and execute it.
$.getScript("test.js");
Load the test.js JavaScript file and execute it, displaying an alert message when the execution is complete.
$.getScript("test.js", function(){
alert("Script loaded and executed.");
});
Filters the original array of numbers leaving that are not 5 and have an index greater than 3. Then it removes all 9s while inverting it.
var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
$("div").text(arr.join(", "));
arr = jQuery.grep(arr, function(n, i){
return (n != 5 && i > 4);
});
$("p").text(arr.join(", "));
arr = jQuery.grep(arr, "a != 9");
$("span").text(arr.join(", "));
<div></div>
<p></p>
<span></span>
Filter an array of numbers to include only numbers bigger then zero.
$.grep( [0,1,2], function(n,i){
return n > 0;
});
[1, 2]
Filter an array of numbers to exclude numbers bigger then zero using the third parameter, invert.
$.grep( [0,1,2,3,4,5], "a > 1", true);
[0, 1]
var arr = [ 4, "Pete", 8, "John" ];
$("span:eq(0)").text(jQuery.inArray("John", arr));
$("span:eq(1)").text(jQuery.inArray(4, arr));
$("span:eq(2)").text(jQuery.inArray("David", arr));
<div>"John" found at <span></span></div>
<div>4 found at <span></span></div>
<div>"David" found at <span></span></div>
Test a few parameter examples.
function stub() {
}
var objs = [
function () {},
{ x:15, y:20 },
null,
stub,
"function"
];
jQuery.each(objs, function (i) {
var isFunc = jQuery.isFunction(objs[i]);
$("span:eq( " + i + ")").text(isFunc);
});
<div>jQuery.isFunction(objs[0]) = <span></span></div>
<div>jQuery.isFunction(objs[1]) = <span></span></div>
<div>jQuery.isFunction(objs[2]) = <span></span></div>
<div>jQuery.isFunction(objs[3]) = <span></span></div>
<div>jQuery.isFunction(objs[4]) = <span></span></div>
Finds out if the parameter is a funcion.
$.isFunction(function(){});
true
Turn a collection of HTMLElements into an Array of them.
var arr = jQuery.makeArray(document.getElementsByTagName("div"));
arr.reverse(); // use an Array method on list of dom elements
$(arr).appendTo(document.body);
<div>First</div>
<div>Second</div>
<div>Third</div>
<div>Fourth</div>
Maps the original array to a new one and adds 4 to each value.
var arr = [ "a", "b", "c", "d", "e" ]
$("div").text(arr.join(", "));
arr = jQuery.map(arr, function(n, i){
return (n.toUpperCase() + i);
});
$("p").text(arr.join(", "));
arr = jQuery.map(arr, "a + a");
$("span").text(arr.join(", "));
<div></div>
<p></p>
<span></span>
Maps the original array to a new one and adds 4 to each value.
$.map( [0,1,2], function(n){
return n + 4;
});
[4, 5, 6]
Maps the original array to a new one and adds 1 to each value if it is bigger then zero, otherwise it's removed.
$.map( [0,1,2], function(n){
return n > 0 ? n + 1 : null;
});
[2, 3]
Maps the original array to a new one, each element is added with it's original value and the value plus one.
$.map( [0,1,2], function(n){
return [ n, n + 1 ];
});
[0, 1, 1, 2, 2, 3]
Maps the original array to a new one, each element is squared.
$.map( [0,1,2,3], "a * a" );
[0, 1, 4, 9]
Maps the original object that was referenced by $ back to $.
jQuery.noConflict();
// Do something with jQuery
jQuery("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library.
jQuery.noConflict();
(function($) {
$(function() {
// more code using $ as alias to jQuery
});
})(jQuery);
// other code using $ as an alias to the other library
Creates a different alias instead of jQuery to use in the rest of the script.
var j = jQuery.noConflict();
// Do something with jQuery
j("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
Completely move jQuery to a new namespace in another object.
var dom = {};
dom.query = jQuery.noConflict(true);
// Do something with the new jQuery
dom.query("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
// Do something with another version of jQuery
jQuery("div > p").hide();
Serialize a key/value object.
var params = { width:1680, height:1050 };
var str = jQuery.param(params);
$("#results").text(str);
<div id="results"></div>
Request the test.php page, but ignore the return results.
$.post("test.php");
Request the test.php page and send some additional data along (while still ignoring the return results).
$.post("test.php", { name: "John", time: "2pm" } );
Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.post("test.php", function(data){
alert("Data Loaded: " + data);
});
Alert out the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).
$.post("test.cgi", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Set a data store then remove it.
var adiv = $("div").get(0);
$("span:eq(0)").text("" + jQuery.data(adiv, "test1"));
jQuery.data(adiv, "test1", "VALUE-1");
jQuery.data(adiv, "test2", "VALUE-2");
$("span:eq(1)").text("" + jQuery.data(adiv, "test1"));
jQuery.removeData(adiv);
$("span:eq(2)").text("" + jQuery.data(adiv, "test1"));
$("span:eq(3)").text("" + jQuery.data(adiv, "test2"));
<div>value1 before creation: <span></span></div>
<div>value1 after creation: <span></span></div>
<div>value1 after removal: <span></span></div>
<div>value2 after removal: <span></span></div>
Set a data store for 2 names then remove one of them.
var adiv = $("div").get(0);
$("span:eq(0)").text("" + jQuery.data(adiv, "test1"));
jQuery.data(adiv, "test1", "VALUE-1");
jQuery.data(adiv, "test2", "VALUE-2");
$("span:eq(1)").text("" + jQuery.data(adiv, "test1"));
jQuery.removeData(adiv, "test1");
$("span:eq(2)").text("" + jQuery.data(adiv, "test1"));
$("span:eq(3)").text("" + jQuery.data(adiv, "test2"));
<div>value1 before creation: <span></span></div>
<div>value1 after creation: <span></span></div>
<div>value1 after removal: <span></span></div>
<div>value2 after removal: <span></span></div>
Removes the two whitespaces at the start and at the end of the string.
$("button").click(function () {
var str = " lots of spaces before and after ";
alert("'" + str + "'");
str = jQuery.trim(str);
alert("'" + str + "' - no longer");
});
<button>Show Trim Example</button>
Removes the two whitespaces at the start and at the end of the string.
$.trim(" hello, how are you? ");
"hello, how are you?"
Removes any duplicate elements from the array of divs.
var divs = $("div").get();
// add 3 elements of class dup too (they are divs)
divs = divs.concat($(".dup").get());
$("div:eq(1)").text("Pre-unique there are " + divs.length + " elements.");
divs = jQuery.unique(divs);
$("div:eq(2)").text("Post-unique there are " + divs.length + " elements.")
.css("color", "red");
<div>There are 6 divs in this document.</div>
<div></div>
<div class="dup"></div>
<div class="dup"></div>
<div class="dup"></div>
<div></div>
Removes any duplicate elements from the array of divs.
$.unique(document.getElementsByTagName("div"));
[<div>, <div>, ...]
To perform actions in response to keyboard presses on a page, try:
$(window).keydown(function(event){
switch (event.keyCode) {
// ...
// different keys do different things
// Different browsers provide different codes
// see here for details: http://unixpapa.com/js/key.html
// ...
}
});
Show spaces and letters when typed.
$("input").keypress(function (e) {
if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
|| (97 <= e.which && e.which <= 97 + 25)) {
var c = String.fromCharCode(e.which);
$("p").append($("<span/>"))
.children(":last")
.append(document.createTextNode(c));
} else if (e.which == 8) {
// backspace in IE only be on keydown
$("p").children(":last").remove();
}
$("div").text(e.which);
});
<input type="text" />
<p>Add text - </p>
<div></div>
To perform an action when the escape key has been released:
$(document).keyup(function(event){
if (event.keyCode == 27) {
alert('escaped!');
}
});
Finds the last table row.
$("tr:last").css({backgroundColor: 'yellow', fontWeight: 'bolder'});
<table>
<tr><td>First Row</td></tr>
<tr><td>Middle Row</td></tr>
<tr><td>Last Row</td></tr>
</table>
Finds the last span in each matched div and adds some css plus a hover state.
$("div span:last-child")
.css({color:"red", fontSize:"80%"})
.hover(function () {
$(this).addClass("solast");
}, function () {
$(this).removeClass("solast");
});
<div>
<span>John,</span>
<span>Karl,</span>
<span>Brandon,</span>
<span>Sam</span>
</div>
<div>
<span>Glen,</span>
<span>Tane,</span>
<span>Ralph,</span>
<span>David</span>
</div>
Count the divs. Click to add more.
$(document.body).click(function () {
$(document.body).append($("<div>"));
var n = $("div").length;
$("span").text("There are " + n + " divs." +
"Click to add more.");
}).trigger('click'); // trigger the click to start
<span></span>
<div></div>
Load a piece of the documentation sidebar navigation into a custom unordered list.
$("#links").load("/Main_Page #p-Getting-Started li");
<b>jQuery Links:</b>
<ul id="links"></ul>
Load the feeds.html file into the div with the ID of feeds.
$("#feeds").load("feeds.html");
<div id="feeds"><b>45</b> feeds found.</div>
Same as above, but will POST the additional parameters to the server and a callback that is executed when the server is finished responding.
$("#feeds").load("feeds.php", {limit: 25}, function(){
alert("The last 25 entries in the feed have been loaded");
});
Run a function when the page is fully loaded including graphics.
$(window).load(function () {
// run code
});
Finds TDs less than the one with the 4th index (TD#4).
$("td:lt(4)").css("color", "red");
<table border="1">
<tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
<tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
<tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>
Build a list of all the values within a form.
$("p").append( $("input").map(function(){
return $(this).val();
}).get().join(", ") );
<p><b>Values: </b></p>
<form>
<input type="text" name="name" value="John"/>
<input type="text" name="password" value="password"/>
<input type="text" name="url" value="http://ejohn.org/"/>
</form>
A contrived example to show some functionality.
var mappedItems = $("li").map(function (index) {
var replacement = $("<li>").text($(this).text()).get(0);
if (index == 0) {
// make the first item all caps
$(replacement).text($(replacement).text().toUpperCase());
} else if (index == 1 || index == 3) {
// delete the second and fourth items
replacement = null;
} else if (index == 2) {
// make two of the third item and add some text
replacement = [replacement,$("<li>").get(0)];
$(replacement[0]).append("<b> - A</b>");
$(replacement[1]).append("Extra <b> - B</b>");
}
// replacment will be an dom element, null,
// or an array of dom elements
return replacement;
});
$("#results").append(mappedItems);
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
</ul>
<ul id="results">
</ul>
Show the mouse coordinates when the mouse is moved over the yellow div. Coordinates are relative to the window which in this case is the iframe.
$("div").mousemove(function(e){
var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
$("span:first").text("( e.pageX, e.pageY ) - " + pageCoords);
$("span:last").text("( e.clientX, e.clientY ) - " + clientCoords);
});
<p>
Try scrolling too.
<span>Move the mouse over the div.</span>
<span> </span>
</p>
<div></div>
Finds the elements that match any of these three selectors.
$("div,span,p.myClass").css("border","3px solid red");
<div>div</div>
<p class="myClass">p class="myClass"</p>
<p class="notMyClass">p class="notMyClass"</p>
<span>span</span>
Show the order in the jQuery object.
var list = $("div,p,span").map(function () {
return this.tagName;
}).get().join(", ");
$("b").append(document.createTextNode(list));
<span>span</span>
<p>p</p>
<p>p</p>
<div>div</div>
<span>span</span>
<p>p</p>
<div>div</div>
<b></b>
Find the very next sibling of each disabled button and change its text "this button is disabled".
$("button[disabled]").next().text("this button is disabled");
<div><button disabled="disabled">First</button> - <span></span></div>
<div><button>Second</button> - <span></span></div>
<div><button disabled="disabled">Third</button> - <span></span></div>
Find the very next sibling of each paragraph that has a class "selected".
$("p").next(".selected").css("background", "yellow");
<p>Hello</p>
<p class="selected">Hello Again</p>
<div><span>And Again</span></div>
Finds all inputs that are next to a label.
$("label + input").css("color", "blue").val("Labeled!")
<form>
<label>Name:</label>
<input name="name" />
<fieldset>
<label>Newsletter:</label>
<input name="newsletter" />
</fieldset>
</form>
<input name="none" />
Locate all the divs after the first and give them a class.
$("div:first").nextAll().addClass("after");
<div></div>
<div></div>
<div></div>
<div></div>
Locate all the paragraphs after the second child in the body and give them a class.
$(":nth-child(1)").nextAll("p").addClass("after");
<p>p</p>
<div>div</div>
<p>p</p>
<p>p</p>
<div>div</div>
<p>p</p>
<div>div</div>
Finds all inputs that are not checked and hilites the next sibling span. Notice there is no change when clicking the checkboxes since no click events have been linked.
$("input:not(:checked) + span").css("background-color", "yellow");
$("input").attr("disabled", "disabled");
<div>
<input type="checkbox" name="a" />
<span>Mary</span>
</div>
<div>
<input type="checkbox" name="b" />
<span>Paul</span>
</div>
<div>
<input type="checkbox" name="c" checked="checked" />
<span>Peter</span>
</div>
Adds a border to divs that are not green or blue.
$("div").not(".green, #blueone")
.css("border-color", "red");
<div></div>
<div id="blueone"></div>
<div></div>
<div class="green"></div>
<div class="green"></div>
<div class="gray"></div>
<div></div>
Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not( $("#selected")[0] )
Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not("#selected")
Removes all elements that match "div p.selected" from the total set of all paragraphs.
$("p").not($("div p.selected"))
Finds the second li in each matched ul and notes it.
$("ul li:nth-child(2)").append("<span> - 2nd!</span>");
<div><ul>
<li>John</li>
<li>Karl</li>
<li>Brandon</li>
</ul></div>
<div><ul>
<li>Sam</li>
</ul></div>
<div><ul>
<li>Glen</li>
<li>Tane</li>
<li>Ralph</li>
<li>David</li>
</ul></div>
This is a playground to see how the selector works with different strings. Notice that this is different from the :even and :odd which have no regard for parent and just filter the list of elements to every other one. The :nth-child, however, counts the index of the child to its particular parent. In any case, it's easier to see than explain so...
$("button").click(function () {
var str = $(this).text();
$("tr").css("background", "white");
$("tr" + str).css("background", "#e2e1fb");
$("#inner").text(str);
});
<div>
<button>:nth-child(even)</button>
<button>:nth-child(odd)</button>
<button>:nth-child(3n)</button>
<button>:nth-child(2)</button>
</div>
<div>
<button>:nth-child(3n+1)</button>
<button>:nth-child(3n+2)</button>
<button>:even</button>
<button>:odd</button>
</div>
<div><table>
<tr><td>John</td></tr>
<tr><td>Karl</td></tr>
<tr><td>Brandon</td></tr>
<tr><td>Benjamin</td></tr>
</table></div>
<div><table>
<tr><td>Sam</td></tr>
</table></div>
<div><table>
<tr><td>Glen</td></tr>
<tr><td>Tane</td></tr>
<tr><td>Ralph</td></tr>
<tr><td>David</td></tr>
<tr><td>Mike</td></tr>
<tr><td>Dan</td></tr>
</table></div>
<span>
tr<span id="inner"></span>
</span>
Finds odd table rows, matching the second, fourth and so on (index 1, 3, 5 etc.).
$("tr:odd").css("background-color", "#bbbbff");
<table border="1">
<tr><td>Row with Index #0</td></tr>
<tr><td>Row with Index #1</td></tr>
<tr><td>Row with Index #2</td></tr>
<tr><td>Row with Index #3</td></tr>
</table>
Access the offset of the second paragraph:
var p = $("p:last");
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );
<p>Hello</p><p>2nd Paragraph</p>
Click to see the offset.
$("*", document.body).click(function (e) {
var offset = $(this).offset();
e.stopPropagation();
$("#result").text(this.tagName + " coords ( " + offset.left + ", " +
offset.top + " )");
});
<div id="result">Click an element.</div>
<p>
This is the best way to <span>find</span> an offset.
</p>
<div class="abs">
</dov>
Tie a one-time click to each div.
var n = 0;
$("div").one("click", function(){
var index = $("div").index(this);
$(this).css({ borderStyle:"inset",
cursor:"auto" });
$("p").text("Div at index #" + index + " clicked." +
" That's " + ++n + " total clicks.");
});
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<p>Click a green square...</p>
To display the text of all paragraphs in an alert box the first time each of them is clicked:
$("p").one("click", function(){
alert( $(this).text() );
});
Finds the button with no siblings in each matched div and modifies look.
$("div button:only-child").text("Alone").css("border", "2px blue solid");
<div>
<button>Sibling!</button>
<button>Sibling!</button>
</div>
<div>
<button>Sibling!</button>
</div>
<div>
None
</div>
<div>
<button>Sibling!</button>
<button>Sibling!</button>
<button>Sibling!</button>
</div>
<div>
<button>Sibling!</button>
</div>
[ <li>Glen</li> ]
Finds all tds with children, including text.
$("td:parent").fadeTo(1500, 0.3);
<table border="1">
<tr><td>Value 1</td><td></td></tr>
<tr><td>Value 2</td><td></td></tr>
</table>
Shows the parent of each element as (parent > child). Check the View Source to see the raw html.
$("*", document.body).each(function () {
var parentTag = $(this).parent().get(0).tagName;
$(this).prepend(document.createTextNode(parentTag + " > "));
});
<div>div,
<span>span, </span>
<b>b </b>
</div>
<p>p,
<span>span,
<em>em </em>
</span>
</p>
<div>div,
<strong>strong,
<span>span, </span>
<em>em,
<b>b, </b>
</em>
</strong>
<b>b </b>
</div>
Find the parent element of each paragraph with a class "selected".
$("p").parent(".selected").css("background", "yellow");
<div><p>Hello</p></div>
<div class="selected"><p>Hello Again</p></div>
Find all parent elements of each span.
var parentEls = $("b").parents()
.map(function () {
return this.tagName;
})
.get().join(", ");
$("b").append("<strong>" + parentEls + "</strong>");
<div>
<p>
<span>
<b>My parents are: </b>
</span>
</p>
</div>
Click to find all unique div parent elements of each span.
function showParents() {
$("div").css("border-color", "white");
var len = $("span.selected")
.parents("div")
.css("border", "2px red solid")
.length;
$("b").text("Unique div parents: " + len);
}
$("span").click(function () {
$(this).toggleClass("selected");
showParents();
});
<p>
<div>
<div><span>Hello</span></div>
<span>Hello Again</span>
</div>
<div>
<span>And Hello Again</span>
</div>
</p>
<b>Click Hellos to toggle their parents.</b>
Finds all password inputs.
var input = $(":password").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="file" />
<input type="hidden" />
<input type="image" />
<input type="password" />
<input type="radio" />
<input type="reset" />
<input type="submit" />
<input type="text" />
<select><option>Option<option/></select>
<textarea></textarea>
<button>Button</button>
</form>
<div>
</div>
Prepends some HTML to all paragraphs.
$("p").prepend("<b>Hello </b>");
<p>there friend!</p>
<p>amigo!</p>
Prepends a DOM Element to all paragraphs.
$("p").prepend(document.createTextNode("Hello "));
<p>is what I'd say</p>
<p>is what I said</p>
Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
$("p").prepend( $("b") );
<p> is what was said.</p><b>Hello</b>
Prepends all spans to the element with the ID "foo"
$("span").prependTo("#foo"); // check prepend() examples
<div id="foo">FOO!</div>
<span>I have something to say... </span>
Find the very previous sibling of each div.
var $curr = $("#start");
$curr.css("background", "#f99");
$("button").click(function () {
$curr = $curr.prev();
$("div").css("background", "");
$curr.css("background", "#f99");
});
<div></div>
<div></div>
<div><span>has child</span></div>
<div></div>
<div></div>
<div></div>
<div id="start"></div>
<div></div>
<p><button>Go to Prev</button></p>
Find the very previous sibling of each paragraph that has a class "selected".
$("p").prev(".selected").css("background", "yellow");
<div><span>Hello</span></div>
<p class="selected">Hello Again</p>
<p>And Again</p>
Locate all the divs before the last and give them a class.
$("div:last").prevAll().addClass("before");
<div></div>
<div></div>
<div></div>
<div></div>
Show the length of the queue.
$("#show").click(function () {
var n = $("div").queue("fx");
$("span").text("Queue length is: " + n.length);
});
function runIt() {
$("div").show("slow");
$("div").animate({left:'+=200'},2000);
$("div").slideToggle(1000);
$("div").slideToggle("fast");
$("div").animate({left:'-=200'},1500);
$("div").hide("slow");
$("div").show(1200);
$("div").slideUp("normal", runIt);
}
runIt();
<button id="show">Show Length of Queue</button>
<span></span>
<div></div>
Queue a custom function.
$(document.body).click(function () {
$("div").show("slow");
$("div").animate({left:'+=200'},2000);
$("div").queue(function () {
$(this).addClass("newcolor");
$(this).dequeue();
});
$("div").animate({left:'-=200'},500);
$("div").queue(function () {
$(this).removeClass("newcolor");
$(this).dequeue();
});
$("div").slideUp();
});
Click here...
<div></div>
Set a queue array to delete the queue.
$("#start").click(function () {
$("div").show("slow");
$("div").animate({left:'+=200'},5000);
$("div").queue(function () {
$(this).addClass("newcolor");
$(this).dequeue();
});
$("div").animate({left:'-=200'},1500);
$("div").queue(function () {
$(this).removeClass("newcolor");
$(this).dequeue();
});
$("div").slideUp();
});
$("#stop").click(function () {
$("div").queue("fx", []);
$("div").stop();
});
<button id="start">Start</button>
<button id="stop">Stop</button>
<div></div>
Finds all radio inputs.
var input = $(":radio").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="file" />
<input type="hidden" />
<input type="image" />
<input type="password" />
<input type="radio" name="asdf" />
<input type="radio" name="asdf" />
<input type="reset" />
<input type="submit" />
<input type="text" />
<select><option>Option<option/></select>
<textarea></textarea>
<button>Button</button>
</form>
<div>
</div>
Display a message when the DOM is loaded.
$("p").text("The DOM is now loaded and can be manipulated.");
<p>
</p>
To run code when the DOM loads, write:
$(document).ready(function(){
// Your code here...
});
To use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias, write:
jQuery(function($) {
// Your code using failsafe $ alias here...
});
Commonly written as:
$(function() {
// Your code here...
});
Removes all paragraphs from the DOM
$("button").click(function () {
$("p").remove();
});
<p>Hello</p>
how are
<p>you?</p>
<button>Call remove() on paragraphs
Removes all paragraphs that contain "Hello" from the DOM
$("button").click(function () {
$("p").remove(":contains('Hello')");
});
<p class="hello">Hello</p>
how are
<p>you?</p>
<button>Call remove(":contains('Hello')") on paragraphs
Clicking the button enables the input next to it.
$("button").click(function () {
$(this).next().removeAttr("disabled")
.focus()
.val("editable now");
});
<button>Enable</button>
<input type="text" disabled="disabled" value="can't edit this" />
Remove the class 'blue' from the matched elements.
$("p:even").removeClass("blue");
<p class="blue under">Hello</p>
<p class="blue under highlight">and</p>
<p class="blue under">then</p>
<p class="blue under">Goodbye</p>
Remove the class 'blue' and 'under' from the matched elements.
$("p:odd").removeClass("blue under");
<p class="blue under">Hello</p>
<p class="blue under highlight">and</p>
<p class="blue under">then</p>
<p class="blue under">Goodbye</p>
Remove all the classes from the matched elements.
$("p:eq(1)").removeClass();
<p class="blue under">Hello</p>
<p class="blue under highlight">and</p>
<p class="blue under">then</p>
<p class="blue under">Goodbye</p>
Replace all the paragraphs with bold words.
$("<b>Paragraph. </b>").replaceAll("p"); // check replaceWith() examples
<p>Hello</p>
<p>cruel</p>
<p>World</p>
On click, replace the button with a div containing the same word.
$("button").click(function () {
$(this).replaceWith("<div>" + $(this).text() + "</div>");
});
<button>First</button>
<button>Second</button>
<button>Third</button>
Replace all the paragraphs with bold words.
$("p").replaceWith("<b>Paragraph. </b>");
<p>Hello</p>
<p>cruel</p>
<p>World</p>
Replace all the paragraphs with empty div elements.
$("p").replaceWith(document.createElement("div"));
<p>Hello</p>
<p>cruel</p>
<p>World</p>
On click, replace each paragraph with a jQuery div object that is already in the DOM. Notice it doesn't clone the object but rather moves it to replace the paragraph.
$("p").click(function () {
$(this).replaceWith($("div"));
});
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<div>Replaced!</div>
Finds all reset inputs.
var input = $(":reset").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="file" />
<input type="hidden" />
<input type="image" />
<input type="password" />
<input type="radio" />
<input type="reset" />
<input type="submit" />
<input type="text" />
<select><option>Option<option/></select>
<textarea></textarea>
<button>Button</button>
</form>
<div>
</div>
To make resizing the web page window a pain in the neck, try:
$(window).resize(function(){
alert("Stop it!");
});
To do something when your page is scrolled:
$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$("p").clone().appendTo(document.body);
$(window).scroll(function () {
$("span").css("display", "inline").fadeOut("slow");
});
<div>Try scrolling the iframe.</div>
<p>Paragraph - <span>Scroll happened!</span></p>
To trigger the select event on all input elements, try:
$("input").select();
To do something when text in input boxes is selected:
$(document).select( function () {
$("div").text("Something was selected").show().fadeOut(1000);
});
<p>
Click and drag the mouse to select text in the inputs.
</p>
<input type="text" value="Some text" />
<input type="text" value="to test on" />
<div></div>
Attaches a change even to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.trigger('change');
<select name="garden" multiple="multiple">
<option>Flowers</option>
<option selected="selected">Shrubs</option>
<option>Trees</option>
<option selected="selected">Bushes</option>
<option>Grass</option>
<option>Dirt</option>
</select>
<div></div>
Serialize a form to a query string, that could be sent to a server in an Ajax request.
function showValues() {
var str = $("form").serialize();
$("#results").text(str);
}
$(":checkbox, :radio").click(showValues);
$("select").change(showValues);
showValues();
<form>
<select name="single">
<option>Single</option>
<option>Single2</option>
</select>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select><br/>
<input type="checkbox" name="check" value="check1"/> check1
<input type="checkbox" name="check" value="check2" checked="checked"/> check2
<input type="radio" name="radio" value="radio1" checked="checked"/> radio1
<input type="radio" name="radio" value="radio2"/> radio2
</form>
<p><tt id="results"></tt></p>
Get the values from a form, iterate through them, and append them to a results display.
function showValues() {
var fields = $(":input").serializeArray();
$("#results").empty();
jQuery.each(fields, function(i, field){
$("#results").append(field.value + " ");
});
}
$(":checkbox, :radio").click(showValues);
$("select").change(showValues);
showValues();
<p><b>Results:</b> <span id="results"></span></p>
<form>
<select name="single">
<option>Single</option>
<option>Single2</option>
</select>
<select name="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select><br/>
<input type="checkbox" name="check" value="check1"/> check1
<input type="checkbox" name="check" value="check2" checked="checked"/> check2
<input type="radio" name="radio" value="radio1" checked="checked"/> radio1
<input type="radio" name="radio" value="radio2"/> radio2
</form>
Shows all paragraphs.
$("p").show()
<p style="display:none">Hello</p>
Animates all hidden paragraphs to show slowly, completing the animation within 600 milliseconds.
$("button").click(function () {
$("p").show("slow");
});
<button>Show it</button>
<p style="display: none">Hello</p>
Animates all hidden divs to show fastly in order, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one.
$("#showr").click(function () {
$("div:eq(0)").show("fast", function () {
// use callee so don't have to name the function
$(this).next().show("fast", arguments.callee);
});
});
$("#hidr").click(function () {
$("div").hide(2000);
});
<button id="showr">Show</button>
<button id="hidr">Hide</button>
<div>Hello,</div>
<div>how</div>
<div>are</div>
<div>you?</div>
Animates all span and input elements to show normally. Once the animation is done, it changes the text.
function doIt() {
$("span,div").show("normal");
}
$("button").click(doIt); // can pass in function name
$("form").submit(function () {
if ($("input").val() == "yes") {
$("p").show(4000, function () {
$(this).text("Ok, DONE! (now showing)");
});
}
$("span,div").hide("normal");
return false; // to stop the submit
});
<button>Do it!</button>
<span>Are you sure? (type 'yes' if you are) </span>
<div>
<form>
<input type="text" />
</form>
</div>
<p style="display:none;">I'm hidden...</p>
Find the unique siblings of all yellow li elements in the 3 lists (including other yellow li elements if appropriate).
var len = $(".hilite").siblings()
.css("color", "red")
.length;
$("b").text(len);
<ul>
<li>One</li>
<li>Two</li>
<li class="hilite">Three</li>
<li>Four</li>
</ul>
<ul>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
</ul>
<ul>
<li>Eight</li>
<li class="hilite">Nine</li>
<li>Ten</li>
<li class="hilite">Eleven</li>
</ul>
<p>Unique siblings: <b></b></p>
Find all siblings with a class "selected" of each div.
$("p").siblings(".selected").css("background", "yellow");
<div><span>Hello</span></div>
<p class="selected">Hello Again</p>
<p>And Again</p>
Finds all divs that are siblings after the element with #prev as its id. Notice the span isn't selected since it is not a div and the "niece" isn't selected since it is a child of a sibling, not an actual sibling.
$("#prev ~ div").css("border", "3px groove blue");
<div>div (doesn't match since before #prev)</div>
<div id="prev">div#prev</div>
<div>div sibling</div>
<div>div sibling <div id="small">div neice</div></div>
<span>span sibling (not div)</span>
<div>div sibling</div>
Count the divs. Click to add more.
$(document.body).click(function () {
$(document.body).append($("<div>"));
var n = $("div").size();
$("span").text("There are " + n + " divs." +
"Click to add more.");
}).click(); // trigger the click to start
<span></span>
<div></div>
Turns divs yellow based on a random slice.
function colorEm() {
var $div = $("div");
var start = Math.floor(Math.random() *
$div.length);
var end = Math.floor(Math.random() *
($div.length - start)) +
start + 1;
if (end == $div.length) end = undefined;
$div.css("background", "");
if (end)
$div.slice(start, end).css("background", "yellow");
else
$div.slice(start).css("background", "yellow");
$("span").text('$("div").slice(' + start +
(end ? ', ' + end : '') +
').css("background", "yellow");');
}
$("button").click(colorEm);
<button>Turn slice yellow</button>
<span>Click the button!</span>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
Selects all paragraphs, then slices the selection to include only the first element.
$("p").slice(0, 1).wrapInner("<b></b>");
Selects all paragraphs, then slices the selection to include only the first and second element.
$("p").slice(0, 2).wrapInner("<b></b>");
Selects all paragraphs, then slices the selection to include only the second element.
$("p").slice(1, 2).wrapInner("<b></b>");
Selects all paragraphs, then slices the selection to include only the second and third element.
$("p").slice(1).wrapInner("<b></b>");
Selects all paragraphs, then slices the selection to include only the third element.
$("p").slice(-1).wrapInner("<b></b>");
Animates all divs to slide down and show themselves over 600 milliseconds.
$(document.body).click(function () {
if ($("div:first").is(":hidden")) {
$("div").slideDown("slow");
} else {
$("div").hide();
}
});
Click me!
<div></div>
<div></div>
<div></div>
Animates all inputs to slide down, completing the animation within 1000 milliseconds. Once the animation is done, the input look is changed especially if it is the middle input which gets the focus.
$("div").click(function () {
$(this).css({ borderStyle:"inset", cursor:"wait" });
$("input").slideDown(1000,function(){
$(this).css("border", "2px red inset")
.filter(".middle")
.css("background", "yellow")
.focus();
$("div").css("visibility", "hidden");
});
});
<div>Push!</div>
<input type="text" />
<input type="text" class="middle" />
<input type="text" />
Animates all paragraphs to slide up or down, completing the animation within 600 milliseconds.
$("button").click(function () {
$("p").slideToggle("slow");
});
<button>Toggle</button>
<p>
This is the paragraph to end all paragraphs. You
should feel <em>lucky</em> to have seen such a paragraph in
your life. Congratulations!
</p>
Animates divs between dividers with a toggle that makes some appear and some disappear.
$("button").click(function () {
$("div:not(.still)").slideToggle("slow", function () {
var n = parseInt($("span").text(), 10);
$("span").text(n + 1);
});
});
<button>Toggle</button> There have been <span>0</span> toggled divs.
<div></div><div class="still"></div>
<div style="display:none;"></div><div class="still"></div>
<div></div><div class="still"></div>
<div class="hider"></div><div class="still"></div>
<div class="hider"></div><div class="still"></div>
<div></div>
Animates all divs to slide up, completing the animation within 400 milliseconds.
$(document.body).click(function () {
if ($("div:first").is(":hidden")) {
$("div").show("fast");
} else {
$("div").slideUp();
}
});
Click me!
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
Animates all paragraph to slide up, completing the animation within 200 milliseconds. Once the animation is done, it displays an alert.
$("button").click(function () {
$(this).parent().slideUp("slow", function () {
$("#msg").text($("button", this).text() + " has completed.");
});
});
<div>
<button>Hide One</button>
<input type="text" value="One" />
</div>
<div>
<button>Hide Two</button>
<input type="text" value="Two" />
</div>
<div>
<button>Hide Three</button>
<input type="text" value="Three" />
</div>
<div id="msg"></div>
Click the Go button once to start the animation, then click the STOP button to stop it where it's currently positioned. Another option is to click several buttons to queue them up and see that stop just kills the currently playing one.
// Start animation
$("#go").click(function(){
$(".block").animate({left: '+=100px'}, 2000);
});
// Stop animation when button is clicked
$("#stop").click(function(){
$(".block").stop();
});
// Start animation in the opposite direction
$("#back").click(function(){
$(".block").animate({left: '-=100px'}, 2000);
});
<button id="go">Go</button>
<button id="stop">STOP!</button>
<button id="back">Back</button>
<div class="block"></div>
Finds all submit inputs.
var input = $(":submit").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="file" />
<input type="hidden" />
<input type="image" />
<input type="password" />
<input type="radio" />
<input type="reset" />
<input type="submit" />
<input type="text" />
<select><option>Option<option/></select>
<textarea></textarea>
<button>Button</button>
</form>
<div>
</div>
To trigger the submit event on the first form on the page, try:
$("form:first").submit();
If you'd like to prevent forms from being submitted unless a flag variable is set, try:
$("form").submit(function() {
if ($("input:first").val() == "correct") {
$("span").text("Validated...").show();
return true;
}
$("span").text("Not valid!").show().fadeOut(1000);
return false;
});
<p>Type 'correct' to validate.</p>
<form action="javascript:alert('success!');">
<div>
<input type="text" />
<input type="submit" />
</div>
</form>
<span></span>
If you'd like to prevent forms from being submitted unless a flag variable is set, try:
$("form").submit( function () {
return this.some_flag_variable;
} );
Finds all text inputs.
var input = $(":text").css({background:"yellow", border:"3px red solid"});
$("div").text("For this type jQuery found " + input.length + ".")
.css("color", "red");
$("form").submit(function () { return false; }); // so it won't submit
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="file" />
<input type="hidden" />
<input type="image" />
<input type="password" />
<input type="radio" />
<input type="reset" />
<input type="submit" />
<input type="text" />
<select><option>Option<option/></select>
<textarea></textarea>
<button>Button</button>
</form>
<div>
</div>
Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone).
var str = $("p:first").text();
$("p:last").html(str);
<p><b>Test</b> Paragraph.</p>
<p></p>
Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone).
var str = $("p:first").text();
$("p:last").html(str);
<p><b>Test</b> Paragraph.</p>
<p></p>
Add text to the paragraph (notice the bold tag is escaped).
$("p").text("<b>Some</b> new text.");
<p>Test Paragraph.</p>
Add text to the paragraph (notice the bold tag is escaped).
$("p").text("<b>Some</b> new text.");
<p>Test Paragraph.</p>
Toggles all paragraphs.
$("button").click(function () {
$("p").toggle();
});
<button>Toggle</button>
<p>Hello</p>
<p style="display: none">Good Bye</p>
Click to toggle highlight on the list item.
$("li").toggle(
function () {
$(this).css("list-style-type", "disc")
.css("color", "blue");
},
function () {
$(this).css({"list-style-type":"", "color":""});
}
);
<ul>
<li>Go to the store</li>
<li>Pick up dinner</li>
<li>Debug crash</li>
<li>Take a jog</li>
</ul>
To toggle a style on table cells:
$("td").toggle(
function () {
$(this).addClass("selected");
},
function () {
$(this).removeClass("selected");
}
);
Toggle the class 'highlight' when a paragraph is clicked.
$("p").click(function () {
$(this).toggleClass("highlight");
});
<p class="blue">Click to toggle</p>
<p class="blue highlight">highlight</p>
<p class="blue">on these</p>
<p class="blue">paragraphs</p>
Clicks to button #2 also trigger a click for button #1.
$("button:first").click(function () {
update($("span:first"));
});
$("button:last").click(function () {
$("button:first").trigger('click');
update($("span:last"));
});
function update(j) {
var n = parseInt(j.text(), 0);
j.text(n + 1);
}
<button>Button #1</button>
<button>Button #2</button>
<div><span>0</span> button #1 clicks.</div>
<div><span>0</span> button #2 clicks.</div>
To submit the first form without using the submit() function, try:
$("form:first").trigger("submit")
To pass arbitrary data to an event:
$("p").click( function (event, a, b) {
// when a normal click fires, a and b are undefined
// for a trigger like below a refers too "foo" and b refers to "bar"
} ).trigger("click", ["foo", "bar"]);
This would display a "Hello World!" alert box.
$("p").bind("myEvent", function (event, message1, message2) {
alert(message1 + ' ' + message2);
});
$("p").trigger("myEvent", ["Hello","World!"]);
If you called .triggerHandler() on a focus event - the browsers default focus action would not be triggered, only the event handlers bound to the focus event.
$("#old").click(function(){
$("input").trigger("focus");
});
$("#new").click(function(){
$("input").triggerHandler("focus");
});
$("input").focus(function(){
$("<span>Focused!</span>").appendTo("body").fadeOut(1000);
});
<button id="old">.trigger("focus")</button>
<button id="new">.triggerHandler("focus")</button><br/><br/>
<input type="text" value="To Be Focused"/>
Can bind and unbind events to the colored button.
function aClick() {
$("div").show().fadeOut("slow");
}
$("#bind").click(function () {
// could use .bind('click', aClick) instead but for variety...
$("#theone").click(aClick)
.text("Can Click!");
});
$("#unbind").click(function () {
$("#theone").unbind('click', aClick)
.text("Does nothing...");
});
<button id="theone">Does nothing...</button>
<button id="bind">Bind Click</button>
<button id="unbind">Unbind Click</button>
<div style="display:none;">Click!</div>
To unbind all events from all paragraphs, write:
$("p").unbind()
To unbind all click events from all paragraphs, write:
$("p").unbind( "click" )
To unbind just one previously bound handler, pass the function in as the second argument:
var foo = function () {
// code to handle some kind of event
};
$("p").bind("click", foo); // ... now foo will be called when paragraphs are clicked ...
$("p").unbind("click", foo); // ... foo will no longer be called.
To display an alert when a page is unloaded:
$(window).unload( function () { alert("Bye now!"); } );
Get the single value from a single select and an array of values from a multiple select and display their values.
function displayVals() {
var singleValues = $("#single").val();
var multipleValues = $("#multiple").val() || [];
$("p").html("<b>Single:</b> " +
singleValues +
" <b>Multiple:</b> " +
multipleValues.join(", "));
}
$("select").change(displayVals);
displayVals();
<p></p>
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<select id="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select>
Find the value of an input box.
$("input").keyup(function () {
var value = $(this).val();
$("p").text(value);
}).keyup();
<input type="text" value="some text"/>
<p></p>
Set the value of an input box.
$("button").click(function () {
var text = $(this).text();
$("input").val(text);
});
<div>
<button>Feed</button>
<button>the</button>
<button>Input</button>
</div>
<input type="text" value="click a button" />
Get the single value from a single select and an array of values from a multiple select and display their values.
$("#single").val("Single2");
$("#multiple").val(["Multiple2", "Multiple3"]);
$("input").val(["check2", "radio1"]);
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<select id="multiple" multiple="multiple">
<option selected="selected">Multiple</option>
<option>Multiple2</option>
<option selected="selected">Multiple3</option>
</select><br/>
<input type="checkbox" value="check1"/> check1
<input type="checkbox" value="check2"/> check2
<input type="radio" name="r" value="radio1"/> radio1
<input type="radio" name="r" value="radio2"/> radio2
Make all visible divs turn yellow on click.
$("div:visible").click(function () {
$(this).css("background", "yellow");
});
$("button").click(function () {
$("div:hidden").show("fast");
});
<button>Show hidden to see they don't change</button>
<div></div>
<div class="starthidden"></div>
<div></div>
<div></div>
<div style="display:none;"></div>
Show various widths. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body.
function showWidth(ele, w) {
$("div").text("The width for the " + ele +
" is " + w + "px.");
}
$("#getp").click(function () {
showWidth("paragraph", $("p").width());
});
$("#getd").click(function () {
showWidth("document", $(document).width());
});
$("#getw").click(function () {
showWidth("window", $(window).width());
});
<button id="getp">Get Paragraph Width</button>
<button id="getd">Get Document Width</button>
<button id="getw">Get Window Width</button>
<div> </div>
<p>
Sample paragraph to test width
</p>
To set the width of each div on click to 30px plus a color change.
$("div").one('click', function () {
$(this).width(30)
.css({cursor:"auto", "background-color":"blue"});
});
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
Wraps a newly created div around all paragraphs.
$("p").wrap("<div class='wrap'></div>");
<p>Test Paragraph.</p>
Wraps a newly created tree of objects around each span.
$("span").wrap("<div><div><p><em><b></b></em></p></div></div>");
<span>Span Text</span>
<span>Another One</span>
Wraps an element with id of "content" around all paragraphs.
$("p").wrap(document.getElementById('content'));
<p>Test Paragraph.</p><div id="content"></div>
Wraps a jQuery object (in this case a div) around all paragraphs.
$("p").wrap($("<div>"));
<p>Test Paragraph.</p>
<p>Another Paragraph.</p>
Wrap a new div around all of the paragraphs.
$("p").wrapAll("<div></div>");
<p>Hello</p>
<p>cruel</p>
<p>World</p>
Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the <strong> (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html.
$("span").wrapAll("<div><div><p><em><b></b></em></p></div></div>");
<span>Span Text</span>
<strong>What about me?</strong>
<span>Another One</span>
Wrap a new div around all of the paragraphs.
$("p").wrapAll(document.createElement("div"));
<p>Hello</p>
<p>cruel</p>
<p>World</p>
Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target.
$("p").wrapAll($(".doublediv"));
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<div class="doublediv"><div></div></div>
Selects all paragraphs and wraps a bold tag around each of its contents.
$("p").wrapInner("<b></b>");
<p>Hello</p>
<p>cruel</p>
<p>World</p>
Wraps a newly created tree of objects around the inside of the body.
$("body").wrapInner("<div><div><p><em><b></b></em></p></div></div>");
Plain old text, or is it?
Selects all paragraphs and wraps a bold tag around each of its contents.
$("p").wrapInner(document.createElement("b"));
<p>Hello</p>
<p>cruel</p>
<p>World</p>
Selects all paragraphs and wraps a jQuery object around each of its contents.
$("p").wrapInner($("<span class='red'></span>"));
<p>Hello</p>
<p>cruel</p>
<p>World</p>