jQuery Tutorial Tutorials - jQuery .on() method

jQuery .on() method

The .on() method in jQuery is used to attach an event handler to the selected elements.

Use .off() to remove the attached event handler.

jQuery .on() method Syntax

.on(events[,selector][,data],handler)
Parameter Type Description
events String A string contain space-separated event types and optional namespaces, or just namespaces,such as click,submit,keydown.myPlugin, or .myPlugin.
handler Function event handler function to execute when the event is triggered.
selector String A selector used to filter selected elements that trigger the event
data Anything Data to be passwd to the handler

jQuery .on() method Example

example

when the user clicks any paragraph, shows its text contents as an alert.

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

Try now

example

.on() method allows a click event on any selector-filtered matched elements--even new ones.

$( "p" ).on( "click", function(index) {
  $( this ).after( "<p>new created paragraph"+index+"!</p>" );
});

Try now

example

bind multiple event types

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

Try now

example

bind multiple event handlers simultaneously

$("button").on({
  click:function(){$("p").slideToggle();},
  mouseover:function(){$("body").css("background-color","red");},  
  mouseout:function(){$("body").css("background-color","#FFFFFF");}  
});

Try now

example

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)

example

Cancel only the default action

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

example

use return false to prevents the default action from occurring and stops the event from bubbling.

$( "form" ).on( "submit", false );
//or
$("form").on("submit", function() { return false; })

It's equivalent to calling both event.preventDefault() and event.stopPropagation()

$("form").on("submit", function(event) { 
    event.preventDefault();
    event.stopPropagation();
})
Date:2019-08-29 23:44:56 From:www.Lautturi.com author:Lautturi