jQuery: Events

This entry is part 7 of 33 in the series jQuery Tutorial

After selector, Event is the second most important component of jQuery.
We use a click event to illustrate jQuery event.

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script>
        $(function () {
            $('p').click( function () {
                        $('p').css('background-color','yellow');
                    }
            )
        });
    </script>
</head>
<body>
<p>If you click me I will change</p>
</body>
</html>

Try The Code

Notice how we use the click event to act on <p> element.  We want the font color to change and so we put a function inside the click event.

Similar to .click, we use .css to change the background color of the font.

In jQuery, there is a this object that we use to refer to the current element that it is acting on.  In this example, the current element is <p>.

We can replace the p element with this object as below.

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script>
        $(function () {
            $('p').click( function () {
                       $(this).css('background-color','yellow');
                    }
            )
        });
    </script>
</head>
<body>
<p>If you click me I will change</p>
</body>
</html>
Try The Code
Series Navigation<< jQuery: More selectors
jQuery: Focus event >>