First events in jQuery
The click-event
Our examples in chapter 1 and 2 were very basic and easy. We can also change element-styles directly in a stylesheet. However, when we combine our previous examples with a click-event it gets more interesting. Our aim is to create a paragraph that changes its color when you click on it.
Instead of using a DOM-property, onlick
, as we would do in JavaScript we use a jQuery-method named click()
.
Click()
allows us to add a click-event-handler to any selected element. In the following example we add a click-event-handler to all paragraphs that have the class change-color
. You can also see how easy it is to do this with jQuery.
HTML code
jQuery code (we assume that it's called script.js)
$(document).ready(function(){
$("p.change-color").click(function(){
$(this).addClass("blue");
});
});
When the p
is clicked the anonymous function takes action.
These functions are called Callback-functions.
$(this)
refers to the selected paragraph.
Basic nesting of jQuery methods
$(selector).method(function(){
$(selector).method();
});