[go: up one dir, main page]

0% found this document useful (0 votes)
29 views15 pages

BWT-Unit IV

The document discusses jQuery utility methods like $.trim(), $.each(), $.inArray(), $.extend(), and $.proxy(). It also covers jQuery event methods, the event object, using this in event handlers, and named event handler functions. Additionally, it explains jQuery's hide() and show() methods.

Uploaded by

Divine Borah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views15 pages

BWT-Unit IV

The document discusses jQuery utility methods like $.trim(), $.each(), $.inArray(), $.extend(), and $.proxy(). It also covers jQuery event methods, the event object, using this in event handlers, and named event handler functions. Additionally, it explains jQuery's hide() and show() methods.

Uploaded by

Divine Borah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Unit IV jQuery II

Utility Methods
jQuery offers several utility methods in the $ namespace. These methods are
helpful for accomplishing routine programming tasks. For a complete reference
on jQuery utility methods.
Below are examples of a few of the utility methods:
$.trim()
Removes leading and trailing whitespace:

1 // Returns "lots of extra whitespace"


2 $.trim( " lots of extra whitespace " );
$.each()
Iterates over arrays and objects:

1 $.each([ "foo", "bar", "baz" ], function( idx, val ) {


2 console.log( "element " + idx + " is " + val );
3 });
4
5 $.each({ foo: "bar", baz: "bim" }, function( k, v ) {
6 console.log( k + " : " + v );
7 });
The method .each() can be called on a selection to iterate over the elements
contained in the selection. .each(), not $.each(), should be used for iterating over
elements in a selection.
$.inArray()
Returns a value's index in an array, or -1 if the value is not in the array:

1 var myArray = [ 1, 2, 3, 5 ];
2
3 if ( $.inArray( 4, myArray ) !== -1 ) {
4 console.log( "found it!" );
5 }
$.extend()
Changes the properties of the first object using the properties of subsequent
objects:

1 var firstObject = { foo: "bar", a: "b" };


2 var secondObject = { foo: "baz" };
3
4 var newObject = $.extend( firstObject, secondObject );
5
6 console.log( firstObject.foo ); // "baz"
7 console.log( newObject.foo ); // "baz"
If you don't want to change any of the objects you pass to $.extend(), pass an
empty object as the first argument:

1 var firstObject = { foo: "bar", a: "b" };


2 var secondObject = { foo: "baz" };
3
4 var newObject = $.extend( {}, firstObject, secondObject );
5
6 console.log( firstObject.foo ); // "bar"
7 console.log( newObject.foo ); // "baz"
$.proxy()
Returns a function that will always run in the provided scope — that is, sets the
meaning of this inside the passed function to the second argument.

1 var myFunction = function() {


2 console.log( this );
3 };
4 var myObject = {
5 foo: "bar"
6 };
7
8 myFunction(); // window
9
10 var myProxyFunction = $.proxy( myFunction, myObject );
11
12 myProxyFunction(); // myObject
If you have an object with methods, you can pass the object and the name of a
method to return a function that will always run in the scope of the object.

1 var myObject = {
2 myFn: function() {
3 console.log( this );
4 }
5 };
6
7 $( "#foo" ).click( myObject.myFn ); // HTMLElement #foo
8 $( "#foo" ).click( $.proxy( myObject, "myFn" ) ); // myObject
Testing Type
Sometimes the typeof operator can be confusing or inconsistent, so instead of
using typeof, jQuery offers utility methods to help determine the type of a
value.
First of all, you have methods to test if a specific value is of a specific type.

1 $.isArray([]); // true
2 $.isFunction(function() {}); // true
3 $.isNumeric(3.14); // true
Additionally, there is $.type() which checks for the internal class used to create
a value. You can see the method as a better alternative for the typeof operator.

1 $.type( true ); // "boolean"


2 $.type( 3 ); // "number"
3 $.type( "test" ); // "string"
4 $.type( function() {} ); // "function"
5
6 $.type( new Boolean() ); // "boolean"
7 $.type( new Number(3) ); // "number"
8 $.type( new String('test') ); // "string"
9 $.type( new Function() ); // "function"
10
11 $.type( [] ); // "array"
12 $.type( null ); // "null"
13 $.type( /test/ ); // "regexp"
14 $.type( new Date() ); // "date"

jQuery Events

You will learn about jQuery events in this section.

In most web applications, the user does some action to perform an operation.
For example, user clicks on save button to save the edited data in a web page.
Here, clicking on the button is a user's action, which triggers click event and
click event handler (function) saves data.
Event

jQuery Event Methods

The jQuery library provides methods to handle DOM events. Most jQuery
methods correspond to native DOM events.

The following table lists all jQuery methods and corresponding DOM events.

Category jQuery Method DOM Event


Form events blur onblur
change onchange
focus onfocus
focusin onfocusin
select onselect
submit onsubmit
Keyboard events keydown onkeydown
keypress onkeypress
keyup onkeyup
focusout
Mouse events click onclick
dblclick ondblclick
focusout
hover
mousedown onmousedown
mouseenter onmouseenter
mouseleave onmouseleave
mousemove onmousemove
mouseout onmouseout
mouseover onmouseover
mouseup onmouseup
Toggle
Browser events Error onerror()
Resize onresize
Category jQuery Method DOM Event
Scroll onscroll
Document loading Load onload
Ready
Unload onunload

Event Handling

To handle DOM events using jQuery methods, first get the reference of DOM
element(s) using jQuery selector and invoke appropriate jQuery event method.

<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/aj
ax/libs/jquery/1.11.2/jquery.min.js"
>
</script>
<script>
$(document).ready(function ()
{

$('#saveBtn').click(function
() {
alert('Save
button clicked');
});

});
</script>
</head>
<body>
<h1>Demo: jQuery click()
method</h1>
<h2>Demo: jQuery click()
method</h2>

<input type="button"
value="Save" id="saveBtn" />
</body>
</html>
In the above example, we first use id selector to get a reference of 'Save'
button and then call click method. We have specified handler function as a
callback function, which will be called whenever click event of Save button
is triggered.

Event Object

jQuery passes an event object to every event handler function. The event object
includes important properties and methods for cross-browser consistency e.g.
target, pageX, pageY, relatedTarget etc.

<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2
/jquery.min.js">
</script>
<script>
$(document).ready(function () {

$('#saveBtn').click(function (eventObj) {
alert('X =' + eventObj.pageX + ', Y =' +
eventObj.pageY);
});

});
</script>
</head>
<body>
<h1>Demo: jQuery eventObject </h1>

<input type="button" value="Save" id="saveBtn"


/>
</body>
</html>

this Keyword in Event Handler

this keyword in an event handler represents a DOM element which raised an


event.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2
/jquery.min.js">
</script>
<script>
$(document).ready(function () {

$(':button').click(function
(eventObj) {
alert(this.value + ' ' + this.type
+ ' clicked');
});

});
</script>
</head>
<body>
<h1>Demo: jQuery click() method </h1>

<input type="button" value="Save" id="saveBtn" />


<input type="button" value="Delete" id="delBtn" />
<input type="button" value="Clear" id="clearBtn" />
</body>
</html>

Specify Named Function as Event Handler

You can create separate functions and specify that as a handler. This is useful
if you want to use the same handler for different events or events on different
elements.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/j
query/1.11.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {

var mouseHandler =
function() {
alert('The mouse
entered' );
};

$('#myDiv').on('mouseenter',
mouseHandler);

});
</script>
</head>
<body>
<h1> Demo: Named function as
event handler </h1>

<div id="myDiv"
style="width:100px;height:100px;backgrou
nd-color:red;">
</div>
</body>
</html>

jQuery hide() and show()

With jQuery, you can hide and show HTML elements with
the hide() and show() methods:
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquer
y.min.js"></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>

<p>If you click on the "Hide" button, I will disappear.</p>

<button id="hide">Hide</button>
<button id="show">Show</button>

</body>
</html>

Syntax:

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

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

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

The optional callback parameter is a function to be executed after


the hide() or show() method completes (you will learn more about callback
functions in a later chapter).

The following example demonstrates the speed parameter with hide():

jQuery toggle()
You can also toggle between hiding and showing an element with
the toggle() method.

Shown elements are hidden and hidden elements are shown:

<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/j
query.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
</head>
<body>

<button>Toggle between hiding and showing the


paragraphs</button>

<p>This is a paragraph with little content.</p>


<p>This is another small paragraph.</p>

</body>
</html>
jQuery Effects - Fading

With jQuery you can fade elements in and out of visibility.

jQuery Fading Methods

With jQuery you can fade an element in and out of visibility.

jQuery has the following fade methods:

• fadeIn()
• fadeOut()
• fadeToggle()
• fadeTo()

jQuery fadeIn() Method

The jQuery fadeIn() method is used to fade in a hidden element.

Syntax:

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

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

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


completes.

The following example demonstrates the fadeIn() method with different


parameters:

<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/j
query.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
</script>
</head>
<body>

<p>Demonstrate fadeIn() with different parameters.</p>

<button>Click to fade in boxes</button><br><br>

<div id="div1"
style="width:80px;height:80px;display:none;background
-color:red;"></div><br>
<div id="div2"
style="width:80px;height:80px;display:none;background
-color:green;"></div><br>
<div id="div3"
style="width:80px;height:80px;display:none;background
-color:blue;"></div>

</body>
</html>

jQuery Effects - Sliding

The jQuery slide methods slide elements up and down.

jQuery Sliding Methods

With jQuery you can create a sliding effect on elements.

jQuery has the following slide methods:

• slideDown()
• slideUp()
• slideToggle()

jQuery slideDown() Method

The jQuery slideDown() method is used to slide down an element.

Syntax:

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

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

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


completes.

The following example demonstrates the slideDown() method:

<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0
/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}

#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>

<div id="flip">Click to slide down panel</div>


<div id="panel">Hello world!</div>

</body>
</html>

jQuery Effects - Animation

With jQuery, you can create custom animations.

jQuery Animations - The animate() Method

The jQuery animate() method is used to create custom animations.

Syntax:
$(selector).animate({params},speed,callback);

The required params parameter defines the CSS properties to be animated.

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

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


completes.

The following example demonstrates a simple use of the animate() method; it


moves a <div> element to the right, until it has reached a left property of 250px:

<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6
.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left: '250px'});
});
});
</script>
</head>
<body>

<button>Start Animation</button>

<p>By default, all HTML elements have a static


position, and cannot be moved. To manipulate the
position, remember to first set the CSS position
property of the element to relative, fixed, or
absolute!</p>

<div
style="background:#98bf21;height:100px;width:100
px;position:absolute;"></div>

</body>
</html>
Plug-ins:
A plug-in is piece of code written in a standard JavaScript file. These files provide
useful jQuery methods which can be used along with jQuery library methods.
There are plenty of jQuery plug-in available which you can download from
repository link at https://jquery.com/plugins.

How to use Plugins

To make a plug-in's methods available to us, we include plug-in file very similar
to jQuery library file in the <head> of the document.
We must ensure that it appears after the main jQuery source file, and before our
custom JavaScript code.
Following example shows how to include jquery.plug-in.js plugin –
How to create a jQuery plugin with methods: In Jquery Plug-in is a code that
is needed in a standard javascript file. Plugins help in providing different
methods that can be used with different jquery library methods.
Created method:
jQuery.fn.methodName = methodDefinition;
• To Obtain a perfect or compatible code use this .each which is used to
perform over a set of matched elements.
• Prefix should conclude with .js.

You might also like