Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 24

Jquery

JQuery Event Handlers


blur() :
Triggered when you leave an element
change() : Triggered when an element is changed
click() :
Triggered when you click an element
dblclick() : Triggered when you double click an element
error() :
Triggered when an error occurs
focus() :
Triggered when you enter an element
keydown() : Triggered when a key is pressed down
keypress() : Triggered when a key is pressed an released
keyup() :
Triggered when a key is released
load() :
Triggered when your page loads
mousedown() :
Triggered when the mouse button is pressed down
mouseup() : Triggered when the mouse button is released
mousemove() :
Triggered when the cursor moves
mouseover() :
Triggered when the mouse goes over an element
mouseout() : Triggered when the mouse moves off an element
submit() :
Triggered when the submit button is pressed
JQuery Event Object Properties
event.altKey :
Has value true if Alt key was pressed
event.ctrlKey :
Has value true if Ctrl key was pressed
event.data :
Contains value passed to bind() function
event.keyCode :
Contains the keycode for the last pressed key
event.pageX :
Returns the mouse coordinates on the X access
event.pageY :
Returns the mouse coordinates on the Y access
event.screenX :
Returns the mouse coordinates on the X access,
relative to the page
event.screenY :
Returns the mouse coordinates on the Y access,
relative to the page
event.shiftKey :
Has value true if Shift key was pressed
event.target :
Elements name that issued an event
event.timeStamp : Contains timestamp, that lists when the event occurred
event.type :
The type of event that occurred
Few commonly used CSS properties:

PART 1: Jquery selectors

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JQuery Ex 1</title>
<style>
table, th, td {
border: 1px solid black;
}
tr.nice td {
background: #FAFAD2; /* This css will be applied when we add a class with name
'nice' dynamically (in jquery) to a tr*/
}
tr.mouseon td {
background: #1E90FF; /* This css will be applied when we add a class with name
'mouseon' dynamically (in jquery) to a tr*/
}
</style>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$("document").ready(function () {
$("td").css("padding", "6px 10px"); // selecting all td's in the document
$(".hero").css("color", "red");

// selecting element with class 'hero'

$("h3, th").css("background-color", "orange");

// selecting multiple elements(tags)

$("p + h3").css("background-color", "purple");


// selecting h3 tag which immediately
preceeds paragraph tag. If there are more than one h3 tag, then only the first h3 tag will be
affected. And if there is any element between p tag and h3 tag, then h3 tag will NOT be
affected.
$("#randstuff ~ h4,h5").css("background-color", "purple"); // similar to above one, but
this selects element h4 or h5 even if there is any other element between #randstuff and
h4/h5
$("#superhumans > *").css("font-style", "italic"); // Here '>' represents child elements
of #superhumans and '*' represents all. Therefore it selects all child elements under
superhumans
$("div:has(h4)").css("text-decoration", "underline"); // (This one is awesome!). It
selects all elements in a div which has an h4 tag. If any div has a h4 tag, then all the elements
of the div will be underlined.
$("div[id]").css("border", "3px solid black"); // It selects all the div's which has 'id'
associated with it.
$("ul li.villian").css("background-color", "yellow"); // selecting li with a specific class
name
$("li[class='hero']").css("border", "2px solid blue");

// similar to above

$("li[class^='v']").css("border", "2px solid purple"); // selects an li element whose


class name starts with 'v'

$("li[class$='wn']").css("border", "2px solid orange"); // selects an li element whose


class name ends with 'wn'
$("li:contains('Richards')").css("background-color", "cyan"); // This is based on text of
any element. It selects an li element which contains a text 'Richards'
$("#numbers tr:odd").addClass("nice"); // selects all odd tr's inside #numbers div
and adds class 'nice' to it. In the css styling we have specified the css for class 'nice'.
$("#numbers tr").mouseover(function () { $(this).addClass("mouseon"); }); // selects
tr only on mouseover and adds mouseon class to it.
$("#numbers tr").mouseout(function () { $(this).removeClass("mouseon"); }); //
select tr only on mouseout and removes mouseon class from it.
});
</script>
<noscript>
<h3>This site requires JavaScript</h3>
</noscript>
</head>
<body>
<div id="numbers">
<p>
<h3>The Most Important Numbers</h3>
<table>
<tr>
<th>Number</th>
<th>Why I Care</th>
</tr>
<tr>
<td>2012</td>
<td>Year We All Die</td>
</tr>
<tr>
<td>12-21-12</td>
<td>My Next Birthday</td>
</tr>
<tr>
<td>12-21-12</td>
<td>The Day We All Die</td>
</tr>
</table>

</p>
</div>
<div>
<h3>The Most Powerful Superhumans</h3>
<ul id="superhumans">
<li class="unknown">Beyonder</li>
<li class="villian">Galactus</li>
<li class="hero">Franklin Richards</li>
<li class="hero">Reed Richards</li>
</ul>
<p>
<h4>Who Do You Think is Most Powerful?</h4>
</p>
<h6>Very Small</h6>
</div>
<div>
<h3 id="randstuff">Stuff 1</h3>
<h4>Stuff 2</h4>
<h5>Stuff 3</h5>
</div>
</body>
</html>

Few other examples:


$("#table a").css("color", "green"); // selects all anchor tags in a table
$("p > h3").css("color", "green"); // selects all h3 tags inside p
$("#oList li:nth-child(3)").css("color", "green"); // selects 3rd list element
$("input[type='text']").val("Azam"); // selects all text boxes
$("a[href*='google']").css("font-weight", "bolder"); // selects anchor tag whose href
contains the word 'google'. Note: Here '*' represents 'contains'. (We know that '^' represents
starts with and '$' represents ends with)
$("a:contains(sample)").css("color", "green"); // selects all anchor tags which contain the
text 'sample'
$("#oList li:not(:contains(sample))").css("color", "green"); // it selects list items which
does not contain the text 'sample'
$("p:has(i)").hide();
// if any paragraph tag has a p tag, then the paragraph will be
hidden. Note: Here 'i' is a html tag element which means italic

PART 2: FEW MORE SELECTORS

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JQuery Ex 1</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$("document").ready(function () {
$("h4:first").css("background-color", "yellow"); // selects first h4 tag in the document
$("p:last").css({ "background-color": "purple", "color": "white" }); // selects last
paragraph tag in the document. It also shows how to set multiple css at once.
$("p span:first-child").css("background-color", "orange"); // selects first child span inside
a paragraph. (If there is anyelement b/w p and first span then in such case it will not select
first span)
$("div p:last-child").css("background-color", "cyan"); // selects last paragraph in div
$("div:nth-child(1)").css("background-color", "pink"); // it selects exactly the child which
we want to grab. (I did not understand this!)

$("span:eq(2)").css("background-color", "purple"); // It selects the 3rd span element in


the document. Note: Element numbers starts from 0
tag)

$("h4:gt(0)").css("background-color", "green"); // selects all h4 tags greater than 0(1st


$("h4:lt(1)").css("background-color", "olive"); // opposite of above
$('#clickToHide').click(function () {
$('#clickToHide').hide();
}); // hides span if clicked
$('#bringItBack').click(function () {

if ($('#clickToHide').is(':visible')) {
forget to put ':')

// this is how we check for conditions (do not

//$('#clickToHide').hide();
$('#clickToHide').fadeOut(2000);
$(this).val('Bring Back');

}
else {

//$('#clickToHide').show();
$('#clickToHide').fadeIn(2000);
$(this).val('Delete Text');

});
//

// You can also replace hide & show with fadeIn or fadeOut

//

// Also you can use slideDown & slideUp

// // You can play with the speed by giving values in milliseconds or slow // fast, or
normal ex. fadeIn(1000) or fadeOut(slow)
});
</script>
<noscript>
<h3>This site requires JavaScript</h3>
</noscript>
</head>
<body>
<div id="firstDiv">
<h4>First Header</h4>
<p id="firstPara">First paragraph in first div
<span> First Span</span>
<span> Sample Span</span>
</p>
<p>Second paragraph in first div</p>

<p>Third paragraph in first div</p>


</div>

<div id="secondDiv">
<h4>Second Header</h4>
<p>First paragraph in second div<span> Second Span</span></p>
<p>Second paragraph in second div</p>
<p>Third paragraph in first div</p>
</div>

<div id="thirdDiv">
<h4>Third Header</h4>
<p>First paragraph in third div<span> Third Span</span></p>
<p>Second paragraph in third div</p>
<p>Third paragraph in first div</p>
</div>
<span id="clickToHide">Click to hide me</span>
<input type="button" id="bringItBack" value="Bring Back" />
</body>
</html>

PART 3:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JQuery Event Handlers</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
$("document").ready(function () {
$('#oneButton').bind('click',alertButtonClick);
$('#textBox1').bind('blur',onBlurEvent)
.bind('focus',onFocusEvent)
.bind('onmousedown',onMDownEvent)
.bind('onmouseup',onMUpEvent)
.bind('change',onChangeEvent);
$(window).resize(resizedWindow); // assigning multiple events at once

$('#twoButton').bind('dblclick', dblClickedMe);
$('#logo').bind('mouseover', mouseOverMe).bind('mouseout', mouseOutMe); //
assigning multiple events at once
$("form").submit(function() { alert("Submit button clicked") });
$('#threeButton').bind('click',unbindLogo);
$
('#theBody').bind('keyup',checkKeyPressed).bind('mousemove',theMouseMoved).click(event,
eventTriggered);
});
function alertButtonClick() {
alert("There was a button clicked");
}
function onBlurEvent() {
$("#second").html("You left the text box");
}
function onFocusEvent() {
$("#second").html("You entered the text box");
}
function onMDownEvent() {
$("#second").html("You left the text box");
}
function onMUpEvent() {
$("#second").html("You entered the text box");
}
function onChangeEvent() {
$("#third").html("You changed the text box");
}
function resizedWindow() {
$("#second").html("Window was resized W: " + $(window).width() + " H: " + $
(window).height());
}
function dblClickedMe() {
$("#second").html("You double clicked");
}
function mouseOverMe() {
$("#second").html("You put your cursor on my logo");

}
function mouseOutMe() {
$("#second").html("You left my logo");
}
function unbindLogo() {
$('#logo').unbind('mouseover', mouseOverMe).unbind('mouseout', mouseOutMe); //
It removes mouseover & mouseout events from logo
}
function checkKeyPressed(event) {
$('#fifth').text(String.fromCharCode(event.keyCode)); // gets the alphabet of key
pressed
}
function theMouseMoved(event) {
$("#seventh").html(event.screenX); // gets the x coordinate
$("#ninth").html(event.screenY); // gets the y coordinate
}
function eventTriggered(event) {
$("#tenth").text(event.target.nodeName); // gets the element name on which click
action is performed
$("#eleventh").html(event.timeStamp);
}
</script>

</head>

<body id="theBody">
<div>
<h3>JQuery Event Handlers</h3>
</div>
<div>
<img src='http://www.newthinktank.com/favicon.png' id="logo" alt='Little Brain' />
</div>
<br />
<div>
<p><strong>Events Triggered on the Page:</strong></p>
<p id="second">Waiting for Event</p>
<p id="third">Waiting for Change</p>
</div>

<div>
<p><strong>Key Events Triggered on the Page:</strong></p>
<span id="fourth">Key Pressed:</span>
<span id="fifth">Waiting for Change</span>
</div>
<br />
<div>
<p><strong>Mouse Movements on the Page:</strong></p>
<span id="sixth">Mouse X Coordinate:</span>
<span id="seventh">Waiting for Change</span><br />
<span id="eighth">Mouse Y Coordinate:</span>
<span id="ninth">Waiting for Change</span><br />
<span>Textbox Changed: </span>
<span id="tenth">Waiting for Event</span><br />
<span>Element Changed When: </span>
<span id="eleventh">Event Occurred When</span>
</div>
<br />
<form>
<button type="button" id="oneButton">Alert on Click</button>
<button type="button" id="twoButton">Click on me Twice</button>
<button type="button" id="threeButton">Unbind the Logo</button>
<input type='text' id="textBox1" size="40" />
<input type='submit' value='Send' />
</form>
</body>
</html>

PART 4:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JQuery Animations</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
$("document").ready(function() {

// Bind function calls to the buttons on the page


$('#replaceWHtml').bind('click', replaceWHtml);
$('#replaceWText').bind('click', replaceWText);
$('#addAPara').bind('click', addAPara);
$('#removeAPara').bind('click', removeAPara);
$('#lastIsFirst').bind('click', lastIsFirst);
$('#addBefore').bind('click', addBefore);
$('#addAfter').bind('click', addAfter);
$('#addToTextBox').bind('click', addToTextBox);
});

// You use html when you want to replace tags


function replaceWHtml() {
$('#h3Tag').html('<h6>Now I\'m an h6 tag</h6>');
}
// You use text when you want to replace only the text
function replaceWText() {
$('#h3Tag').text('<h6>Didn\'t replace text</h6>'); // This is interesting. Just look at the
output
}
// You can append anything
function addAPara() {
$('#randPara').append('<p>Another Paragraph</p>'); // here randPara is a div
}
// Remove deletes an html element
function removeAPara() {
$('#randPara p:last').remove(); // removes last paragraph of div
}
// Here I use append to move the last p to the first position
function lastIsFirst() {
$('#randPara p:last').append($('#randPara p:first'));
}
// You use before to place elements before another
function addBefore() {
$('#randPara p:first').before('I go before anything');
}
// You use after to place elements after another
function addAfter() {
$('#randPara p:last').after('I go after everything');
}
// Use val to change form element values
function addToTextBox() {
$('#randText').val('Random Text');
}
</script>
</head>
<body>
<div><h3>Playing With Text</h3></div>
<div>
<h3 id="h3Tag">H3 Tag</h3>

</div>
<br />
<div id="randPara">
<p id="firstP">The first paragraph</p>
</div>
<br />

<form>
<input type="text" id="randText"/>
<button type="button" id="replaceWHtml">Replace w/ HTML</button>
<button type="button" id="replaceWText">Replace w/ Text</button>
<button type="button" id="addAPara">Add Text</button>
<button type="button" id="removeAPara">Remove Text</button>
<button type="button" id="lastIsFirst">Last to First</button>
<button type="button" id="addBefore">Add Before</button>
<button type="button" id="addAfter">Add After</button>
<button type="button" id="addToTextBox">Add To Text Box</button>
</form>
</body>
</html>

PART 5:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JQuery Animations</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
$("document").ready(function () {

$('#deleteSpan').bind('click', deleteSpan);
// before places the new element before the paragraph
$('#randPara').before('<span>Before Paragraph</span>');
// insertBefore places the new element as a sibling
$('<span> Insert Before Paragraph</span>').insertBefore('#randPara');
// prependTo places the new element as the first child of the element
$('<span>Prepend To Paragraph</span>').prependTo('#randPara');
// appendTo places the new element as a child
$('<span>Append To Paragraph</span>').appendTo('#randPara');
// append places the new element as the last child of the element
$('#randPara').append('<span> Append Paragraph</span>');

// insertAfter places the new element as a sibling


$('<span> Insert After Paragraph</span>').insertAfter('#randPara');
// after places the new element after the paragraph
$('#randPara').after('<span> After Paragraph</span>');
function deleteSpan() {
$('span').remove(':contains("Append")');
}
});
</script>
</head>
<body>
<div><h3>Playing With Text</h3></div>

<div>
<h3 id="h3Tag">H3 Tag</h3>
</div>
<br />
<div id="randPara">
<p id="firstP">The First Paragraph</p>
</div>
<br /><br />
<form>
<button type="button" id="deleteSpan">Delete Spans</button>
</form>
<br />
</body>
</html>

PART 6:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JQuery Animations</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
<script type="text/javascript">
$("document").ready(function() {
$('#hideLogo').bind('click', hideTheImage);
$('#showLogo').bind('click', showTheImage);
$('#toggleText').bind('click', toggleTheText);
$('#fadeLogo').bind('click', fadeTheImage);
$('#fadeALittle').bind('click', fadeALittle);
$('#fullOpacity').bind('click', fullOpacityImage);
$('#slideAway').bind('click', slideTheImage);
$('#slideBack').bind('click', unslideTheImage);
$('#customAnim').bind('click', customAnimate);
$('#shakeLogo').bind('click', shakeLogo);
$('#bounceLogo').bind('click', bounceLogo);
$('#highlightLogo').bind('click', highlightLogo);

$('#pulsateLogo').bind('click', pulsateLogo);
$('#sizeLogo').bind('click', sizeLogo);
});
function hideTheImage() {
$('#logo').hide('puff',{}, 2500);
// I could also hide with effects .hide('effect', {properties}, 1000);
// Effects: blind, clip, drop, explode, fade, fold, puff, slide, scale
}
function showTheImage() {
$('#logo').show('fold', {}, 2500);
}
// Displays or hides matching elements on the page
function toggleTheText()
{
$("h4").toggle(2500);
}
function fadeTheImage() {
$('#logo').fadeOut(2500);
}
function fadeALittle() {
$('#logo').fadeTo(2500,.30);
}
function fullOpacityImage() {
$('#logo').fadeTo(2500,1);
}
function slideTheImage() {
$('#second').slideUp(2500);
}
function unslideTheImage() {
$('#second').slideDown(2500);
}
// animate only allows linear or swing easing
// With the JQuery UI Library you get many more easeOutElastic, easeInCirc,
// easeInOutExpo, easeOutBack, easeInOutElastic, easeOutBounce
function customAnimate() {

$('#logo').animate({opacity: 0.25, height: '150px'}, 2000, 'easeOutBounce');


}
function shakeLogo() {
$('#logo').effect('shake', {times:5, direction:'down', distance: 10}, 200);
}
function bounceLogo() {
$('#logo').effect('bounce', {times:5, direction:'up', distance: 10}, 200);
}
function highlightLogo() {
$('h3').effect('highlight', {color: 'purple'}, 500);
}
function pulsateLogo() {
$('#logo').effect('pulsate', {times:5}, 200);
}
function sizeLogo() {
$('#logo').effect('size', { to: {height: 350, width: 350}}, 200);
}
</script>
</head>

<body>
<div><h3>Playing with Animation's</h3></div>
<div id="logoDiv">
<img src='http://www.newthinktank.com/images/ThinkTankLogo.gif' id="logo" height='75'
alt='Little Brain' />
</div>
<br />
<div>
<h4>Message 1</h4>
<h4 style="display: none">Message 2</h4>
</div>
<div>
<p id="second">Here today, gone in a click!</p>

</div>
<br />
<form>
<button type="button" id="hideLogo">Hide the Logo</button>
<button type="button" id="showLogo">Show the Logo</button>
<button type="button" id="fadeLogo">Fade the Logo</button>
<button type="button" id="fadeALittle">Fade a Little</button>
<button type="button" id="fullOpacity">Full Opacity</button>
<button type="button" id="toggleText">Toggle the Text</button>
<button type="button" id="slideAway">Slide away Text</button>
<button type="button" id="slideBack">Slide Text Back</button>
<button type="button" id="customAnim">Custom Animation</button>
<button type="button" id="shakeLogo">Shake Logo</button>
<button type="button" id="bounceLogo">Bounce Logo</button>
<button type="button" id="highlightLogo">Highlight Logo</button>
<button type="button" id="pulsateLogo">Pulsate Logo</button>
<button type="button" id="sizeLogo">Size Logo</button>
</form>
</body>
</html>

PART 7: ACCORDIAN WITHOUT JQUERY-UI

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Accordian with code </title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"> </script>
<style>
h4 {
background-color:DarkSlateGray;
color:white;
padding:10px;
}
div {
background-color:LightCyan;
width:200px;
overflow:hidden;
}

</style>
<script type="text/javascript">
$("document").ready(function() {
$('#superHumans > div').hide();
$('#superHumans h4').click(function() {
$(this).siblings('div:visible').slideUp('2000');
$(this).next().animate({'height':'toggle'}, '2000', 'easeInOutExpo'
);
});
});
</script>
</head>
<body>

<div id="superHumans">
<h4>Beyonder</h4>
<div>
He had the power to achieve what ever he pleased. He has vast power to alter reality on a
planetary scale.
</div>
<h4>Thanos</h4>
<div>
Gifted with immortality and unaffected by attacks of any kind.
</div>
<h4>Galactus</h4>
<div>
He can levitate; restructure molecules; convert matter into energy and vice-versa; project
energy with enormous concussive force; teleport himself, others, and objects across space,
dimensions, and time; erect virtually impenetrable fields; restore others from any injury, even
total disintegration; and endow or enhance powers within others.
</div>
<h4>Franklin Richards</h4>
<div>
He has vast telepathic powers, tremendous telekinetic powers, the ability to fire enormously
powerful energy blasts, and the ability to rearrange the molecular structure of matter, even
up to a cosmic scale.
</div>
<h4>Doctor Manhattan</h4>

<div>
Mastery over the manipulation of all matter and energy. Knowledge of all that has occurred in
the past and present.
</div>
</div>
</body>
</html>

You might also like