Making things Interactive
jQuery's click() method is a quick and easy way to add a click listener to element(s)
//prints when item with id 'submit' is clicked
$('#submit').click(function(){
console.log("Another click");
});
//alerts when ANY button is clicked
$('button').click(function(){
alert("Someone clicked a button");
});
jQuery's keypress() method is a quick and easy way to add a keypress listener to element(s)
//listen for any keypress in any text input
$('input[type="text"').keypress(function(){
alert("text input keypress!");
});
jQuery's on() works similarly to addEventListener. It lets you specify the type of event to listen for.
//prints when item with id 'submit' is clicked
$('#submit').on('click', function(){
console.log("Another click");
});
//alerts when ANY button is clicked
$('button').on('click', function(){
console.log("button clicked!");
});
It's not just for click events. on() supports all types of events
//double click event
$('button').on('dblclick', function(){
alert("DOUBLE CLICKED!");
});
//drag start event
$('a').on('dragstart', function(){
console.log("DRAG STARTED!");
});
//keypress event
$('input[type="text"').on('keypress', function(){
alert("key press in an input!")
});
In most cases, click() and on('click') will both get the job done. HOWEVER, there is one key difference: