Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Friday, 17 March 2017

What is self executive function in Jquery

Self executive function-

It is a unnamed anonymous function that will be executed automatically when execution reached at (); Actually, jquery is a interpreted and dynamic language and jquery code is executed line by line so when execution reached at line (); It will be automatically fired.

Synatx -

   (function(){
    -------
    -----
   })();

Example:

  var example = (function() {
  var privateVariable = 'privateVariable';

  function privateMethod() {
    return 1;
  }

  return {
    publicVariable: 'publicValue',
    publicMethod: function() {
      //return privateMethod();
    }
  };
}());


calling : example.publicMethod()

What is prototype in Jquery/Javascript


Every JavaScript object has a prototype. The prototype is also an object.
All JavaScript objects inherit their properties and methods from their prototype.

JavaScript Prototypes

All JavaScript objects inherit the properties and methods from their prototype.
Objects created using an object literal, or with new Object(), inherit from a prototype called Object.prototype.
Objects created with new Date() inherit the Date.prototype.
The Object.prototype is on the top of the prototype chain.
All JavaScript objects (Date, Array, RegExp, Function, ....) inherit from the Object.prototype.

Creating a Prototype

The standard way to create an object prototype is to use an object constructor function:

Example

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
With a constructor function, you can use the new keyword to create new objects from the same prototype:

Example

var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
Try it Yourself »
The constructor function is the prototype for Person objects.
It is considered good practice to name constructor function with an upper-case first letter.


Adding Properties and Methods to Objects

Sometimes you want to add new properties (or methods) to an existing object.
Sometimes you want to add new properties (or methods) to all existing objects of a given type.
Sometimes you want to add new properties (or methods) to an object prototype.


Adding a Property to an Object

Adding a new property to an existing object is easy:

Example

myFather.nationality = "English";
Try it Yourself »
The property will be added to myFather. Not to myMother. Not to any other person objects.

Adding a Method to an Object

Adding a new method to an existing object is also easy:

Example

myFather.name = function () {
    return this.firstName + " " + this.lastName;
};
Try it Yourself »
The method will be added to myFather. Not to myMother.

Adding Properties to a Prototype

You cannot add a new property to a prototype the same way as you add a new property to an existing object, because the prototype is not an existing object.

Example

Person.nationality = "English";
Try it Yourself »
To add a new property to a prototype, you must add it to the constructor function:

Example

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
    this.nationality = "English";
}
Try it Yourself »
Prototype properties can have prototype values (default values).


Adding Methods to a Prototype

Your constructor function can also define methods:

Example

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
    this.name = function() {return this.firstName + " " + this.lastName;};
}
Try it Yourself »

Using the prototype Property

The JavaScript prototype property allows you to add new properties to an existing prototype:

Example

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
Try it Yourself »
The JavaScript prototype property also allows you to add new methods to an existing prototype:

Example

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
    return this.firstName + " " + this.lastName;
};
Try it Yourself »
Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.

What is Closure in Jquery

What is a closure?
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.
You create a closure by adding a function inside another function.
A Basic Example of Closures in JavaScript:
function showName (firstName, lastName) {
var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName () {
return nameIntro + firstName + " " + lastName;
}
return makeFullName ();
}
showName ("Michael", "Jackson"); // Your name is Michael Jackson

Thursday, 16 March 2017

Difference between Bind(), Live(), Delegate() and On() in Jquery

Bind Method-

.bind( eventType [, eventData ], handler )  ver-1.0

.bind( eventType [, eventData ] [, preventBubble ] )   ver-1.4.3

.bind( events )   ver-1.4

The .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object.

 Any string is legal for eventType; if the string is not the name of a native DOM event, then the handler is bound to a custom event. These events are never called by the browser, but may be triggered manually from other JavaScript code using .trigger() or .triggerHandler().

If the eventType string contains a period (.) character, then the event is namespaced. The period character separates the event from its namespace. For example, in the call .bind( "click.name", handler ), the string click is the event type, and the string name is the namespace. Namespacing allows us to unbind or trigger some events of a type without affecting others.

A basic usage of .bind() is:

$( "#foo" ).bind( "click", function() {
  alert( "User clicked on 'foo.'" );
});

This code will cause the element with an ID of foo to respond to the click event. When a user clicks inside this element thereafter, the alert will be shown.


Multiple Events -

Multiple event types can be bound at once by including each one separated by a space:


$( "#foo" ).bind( "mouseenter mouseleave", function() {
  $( this ).toggleClass( "entered" );
});

The effect of this on <div id="foo"> (when it does not initially have the "entered" class) is to add the "entered" class when the mouse enters the <div> and remove the class when the mouse leaves.

As of jQuery 1.4 we can bind multiple event handlers simultaneously by passing an object of event type/handler pairs:


$( "#foo" ).bind({
  click: function() {
    // Do something on click
  },
  mouseenter: function() {
    // Do something on mouseenter
  }
});


Event Handlers -

The handler parameter takes a callback function, as shown above. Within the handler, the keyword this refers to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal $() function. For example:


$( "#foo" ).bind( "click", function() {
  alert( $( this ).text() );
});


The Event object -

The handler callback function can also take parameters. When the function is called, the event object will be passed to the first parameter.

Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.

Using the event object in a handler looks like this:


$( document ).ready(function() {
  $( "#foo" ).bind( "click", function( event ) {
    alert( "The mouse cursor is at (" +
      event.pageX + ", " + event.pageY +
      ")" );
  });
});


Passing Event Data -

The optional eventData parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures. For example, suppose we have two event handlers that both refer to the same external variable:

var message = "Spoon!";
$( "#foo" ).bind( "click", function() {
  alert( message );
});
message = "Not in the face!";
$( "#bar" ).bind( "click", function() {
  alert( message );
});

Because the handlers are closures that both have message in their environment, both will display the message Not in the face! when triggered. The variable's value has changed. To sidestep this, we can pass the message in using eventData:


var message = "Spoon!";
$( "#foo" ).bind( "click", {
  msg: message
}, function( event ) {
  alert( event.data.msg );
});
message = "Not in the face!";
$( "#bar" ).bind( "click", {
  msg: message
}, function( event ) {
  alert( event.data.msg );
});




Examples:
Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe.


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>bind demo</title>
  <style>
  p {
    background: yellow;
    font-weight: bold;
    cursor: pointer;
    padding: 5px;
  }
  p.over {
     background: #ccc;
  }
  span {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Click or double click here.</p>
<span></span>

<script>
$( "p" ).bind( "click", function( event ) {
  var str = "( " + event.pageX + ", " + event.pageY + " )";
  $( "span" ).text( "Click happened! " + str );
});
$( "p" ).bind( "dblclick", function() {
  $( "span" ).text( "Double-click happened in " + this.nodeName );
});
$( "p" ).bind( "mouseenter mouseleave", function( event ) {
  $( this ).toggleClass( "over" );
});
</script>

</body>
</html>

Demo:


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 );

Cancel a default action and prevent it from bubbling up by returning false:

$( "form" ).bind( "submit", function() {
  return false;
})

Cancel only the default action by using the .preventDefault() method.

$( "form" ).bind( "submit", function( event ) {
  event.preventDefault();
});

Stop an event from bubbling without preventing the default action by using the .stopPropagation() method.

$( "form" ).bind( "submit", function( event ) {
  event.stopPropagation();
});

HTML :
<ul id="members" data-role="listview" data-filter="true">
    <!-- ... more list items ... -->
    <li>
        <a href="detail.html?id=10">
            <h3>John Resig</h3>
            <p><strong>jQuery Core Lead</strong></p>
            <p>Boston, United States</p>
        </a>
    </li>
    <!-- ... more list items ... -->
</ul>



$( "#members li a" ).bind( "click", function( e ) {} ); 
$( "#members li a" ).click( function( e ) {} ); 


The .bind() method will attach the event handler to all of the anchors that are matched! That is not good. Not only is that expensive to implicitly iterate over all of those items to attach an event handler, but it is also wasteful since it is the same event handler over and over again.

Pros-

This methods works across various browser implementations.
It is pretty easy and quick to wire-up event handlers.
The shorthand methods (.click(), .hover(), etc...) make it even easier to wire-up event handlers.
For a simple ID selector, using .bind() not only wires-up quickly, but also when the event fires the event handler is invoked almost immediately.

Cons-

The method attaches the same event handler to every matched element in the selection.
It doesn't work for elements added dynamically that matches the same selector.
There are performance concerns when dealing with a large selection.
The attachment is done upfront which can have performance issues on page load.


Delegate Method-

.delegate( selector, eventType, handler )   ver- 1.4.2

.delegate( selector, eventType, eventData, handler )  ver- 1.4.2

.delegate( selector, events )  ver- 1.4.3


jQuery .delegate() method behaves in a similar way to the .live() method. But, instead of attaching the selector or event information to the document, you can choose where it is anchored. That is you can control on which node the events will be added. This can also respond to the dynamic element events.


// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );
For example, the following .delegate() code:


$( "table" ).delegate( "td", "click", function() {
  $( this ).toggleClass( "chosen" );
});
is equivalent to the following code written using .on():


$( "table" ).on( "click", "td", function() {
  $( this ).toggleClass( "chosen" );
});

Examples:

Click a paragraph to add another. Note that .delegate() attaches a click event handler to all paragraphs - even new ones.


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>delegate demo</title>
  <style>
  p {
    background: yellow;
    font-weight: bold;
    cursor: pointer;
    padding: 5px;
  }
  p.over {
    background: #ccc;
  }
  span {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Click me!</p>

<span></span>

<script>
$( "body" ).delegate( "p", "click", function() {
  $( this ).after( "<p>Another paragraph!</p>" );
});
</script>

</body>
</html>
Demo:


To display each paragraph's text in an alert box whenever it is clicked:


$( "body" ).delegate( "p", "click", function() {
  alert( $( this ).text() );
});

To cancel a default action and prevent it from bubbling up, return false:


$( "body" ).delegate( "a", "click", function() {
  return false;
});

To cancel only the default action by using the preventDefault method.


$( "body" ).delegate( "a", "click", function( event ) {
  event.preventDefault();
});

Can bind custom events too.


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>delegate demo</title>
  <style>
  p {
    color: red;
  }
  span {
    color: blue;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>

<script>
$( "body" ).delegate( "p", "myCustomEvent", function( e, myName, myValue ) {
  $( this ).text( "Hi there!" );
  $( "span" )
    .stop()
    .css( "opacity", 1 )
    .text( "myName = " + myName )
    .fadeIn( 30 )
    .fadeOut( 1000 );
});
$( "button" ).click(function() {
  $( "p" ).trigger( "myCustomEvent" );
});
</script>

</body>
</html>



Live Method- 

.live( events, handler ) ver - 1.3
.live( events [, data ], handler ) ver - 1.4
.live( events ) ver - 1.4.3

The .live method attaches the event handler to the root level document along with the associated selector and event information. By registering this information on the document it allows one event handler to be used for all events that have bubbled.Live method is deprecated from Jquery 1.7.
Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector

Examples:

Cancel a default action and prevent it from bubbling up by returning false.

$( "a" ).live( "click", function() {
  return false;
});

Cancel only the default action by using the preventDefault method.


$( "a" ).live( "click", function( event ) {
  event.preventDefault();
});

Bind custom events with .live().


$( "p" ).live( "myCustomEvent", function( event, myName, myValue ) {
  $( this ).text( "Hi there!" );
  $( "span" )
    .stop()
    .css( "opacity", 1 )
    .text( "myName = " + myName )
    .fadeIn( 30 )
    .fadeOut( 1000 );
  });
$( "button" ).click(function() {
  $( "p" ).trigger( "myCustomEvent" );
});

Use an object to bind multiple live event handlers. Note that .live() calls the click, mouseover, and mouseout event handlers for all paragraphs--even new ones.


$( "p" ).live({
  click: function() {
    $( this ).after( "<p>Another paragraph!</p>" );
  },
  mouseover: function() {
    $( this ).addClass( "over" );
  },
  mouseout: function() {
    $( this ).removeClass( "over" );
  }
});



Pros-

There is only one event handler registered instead of the numerous event handlers that could have been registered with the .bind() method.
The upgrade path from .bind() to .live() is very small. All you have to do is replace "bind" to "live".
Elements dynamically added to the DOM that match the selector magically work because the real information was registered on the document.
You can wire-up event handlers before the document ready event helping you utilize possibly unused time.

Cons-

This method is deprecated as of jQuery 1.7 and you should start phasing out its use in your code.
Chaining is not properly supported using this method.
The selection that is made is basically thrown away since it is only used to register the event handler on the document.
Using event.stopPropagation() is no longer helpful because the event has already delegated all the way up to the document.
Since all selector/event information is attached to the document once an event does occur jQuery has match through its large metadata store using the matchesSelector method to determine which event handler to invoke, if any.
Your events always delegate all the way up to the document. This can affect performance if your DOM is deep.


On Method-

.on( events [, selector ] [, data ], handler )  ver- 1.7

.on( events [, selector ] [, data ] )    ver- 1.7


You can consider jQuery .on() method as being ‘overloaded’ with different signatures. This method attach the event handler function for one or more events to the selected elements. jQuery .on() function was included in jQuery 1.7 so, for early versions it will not work.



function greet( event ) {
  alert( "Hello " + event.data.name );
}
$( "button" ).on( "click", {
  name: "Karl"
}, greet );
$( "button" ).on( "click", {
  name: "Addy"
}, greet );


var $test = $( "#test" );

function handler1() {
  console.log( "handler1" );
  $test.off( "click", handler2 );
}

function handler2() {
  console.log( "handler2" );
}

$test.on( "click", handler1 );
$test.on( "click", handler2 );


Examples:

Display a paragraph's text in an alert when it is clicked:


$( "p" ).on( "click", function() {
  alert( $( this ).text() );
});

Pass data to the event handler, which is specified here by name:


function myHandler( event ) {
  alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );

Cancel a form submit action and prevent the event from bubbling up by returning false:


$( "form" ).on( "submit", false );

Cancel only the default action by using .preventDefault().


$( "form" ).on( "submit", function( event ) {
  event.preventDefault();
});

Stop submit events from bubbling without preventing form submit, using .stopPropagation().


$( "form" ).on( "submit", function( event ) {
  event.stopPropagation();
});

Pass data to the event handler using the second argument to .trigger()

$( "div" ).on( "click", function( event, person ) {
  alert( "Hello, " + person.name );
});
$( "div" ).trigger( "click", { name: "Jim" } );

Use the the second argument of .trigger() to pass an array of data to the event handler


$( "div" ).on( "click", function( event, salutation, name ) {
  alert( salutation + ", " + name );
});
$( "div" ).trigger( "click", [ "Goodbye", "Jim" ] );

Attach and trigger custom (non-browser) events.


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>on demo</title>
  <style>
  p {
    color: red;
  }
  span {
    color: blue;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>

<script>
$( "p" ).on( "myCustomEvent", function( event, myName ) {
  $( this ).text( myName + ", hi there!" );
  $( "span" )
    .stop()
    .css( "opacity", 1 )
    .text( "myName = " + myName )
    .fadeIn( 30 )
    .fadeOut( 1000 );
});
$( "button" ).click(function () {
  $( "p" ).trigger( "myCustomEvent", [ "John" ] );
});
</script>

</body>
</html>
Demo:


Attach multiple event handlers simultaneously using a plain object.


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>on demo</title>
  <style>
  .test {
    color: #000;
    padding: .5em;
    border: 1px solid #444;
  }
  .active {
    color: #900;
  }
  .inside {
    background-color: aqua;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<div class="test">test div</div>

<script>
$( "div.test" ).on({
  click: function() {
    $( this ).toggleClass( "active" );
  }, mouseenter: function() {
    $( this ).addClass( "inside" );
  }, mouseleave: function() {
    $( this ).removeClass( "inside" );
  }
});
</script>

</body>
</html>



Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>on demo</title>
  <style>
  p {
    background: yellow;
    font-weight: bold;
    cursor: pointer;
    padding: 5px;
  }
  p.over {
    background: #ccc;
  }
  span {
    color: red;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Click me!</p>
<span></span>

<script>
var count = 0;
$( "body" ).on( "click", "p", function() {
  $( this ).after( "<p>Another paragraph! " + (++count) + "</p>" );
});
</script>

</body>
</html>




Display each paragraph's text in an alert box whenever it is clicked:


$( "body" ).on( "click", "p", function() {
  alert( $( this ).text() );
});

Cancel a link's default action using the .preventDefault() method:


$( "body" ).on( "click", "a", function( event ) {
  event.preventDefault();
});

Attach multiple events—one on mouseenter and one on mouseleave to the same element:


$( "#cart" ).on( "mouseenter mouseleave", function( event ) {
  $( this ).toggleClass( "active" );
});


/* The jQuery .bind(), .live(), and .delegate() methods are just one 
   line pass throughs to the new jQuery 1.7 .on() method */

// Bind
$( "#members li a" ).on( "click", function( e ) {} ); 
$( "#members li a" ).bind( "click", function( e ) {} ); 

// Live
$( document ).on( "click", "#members li a", function( e ) {} ); 
$( "#members li a" ).live( "click", function( e ) {} );

// Delegate
$( "#members" ).on( "click", "li a", function( e ) {} ); 
$( "#members" ).delegate( "li a", "click", function( e ) {} );

Difference between setInterval() and setTimeout() in Jquery

setTimeout(expression, timeout); runs the code/function once after the timeout.
setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout 

OR,

setInterval()

setInterval is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().
if you want to loop code for animations or clocks Then use setInterval.
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);

setTimeout()

setTimeout is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);
if you want something to happen one time after some seconds Then use setTimeout... because it only executes one time when the interval is reached.