Lesson 4: jQuery Events

Posted by Niall Doherty in jQuery

In this tutorial, we’ll look at how to use jQuery events, such as click and hover.

YouTube Preview Image

Video highlights

[1:10] Creating a link to click
[2:20] Coding a jQuery click event
[3:35] Testing the click event
[3:50] Disabling the default click behavior (return false)
[4:30] Using preventDefault instead of return false (learn why here)
[6:25] More jQuery events (see the full list on jQuery.com)
[6:55] Demonstrating the hover event
[7:31] Demonstrating the mousetover event

Source code

Here’s the final source code for our click event, using preventDefault:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

  <title>jQuery Test</title>

  <script type="text/javascript" src="javascripts/jquery-1.6.1.min.js"></script>

  <script type="text/javascript">

    $(document).ready(function(){

      $("a").click(function(event){

        alert("You clicked the link!");
        event.preventDefault();

      });

    });

  </script>

</head>

<body>

 <p>Look at me. I'm learning jQuery.</p>

 <ul>
   <li><a href="http://www.google.com">First item</a></li>
   <li>Second item</li>
 </ul>

</body>
</html>

And here are the relevant jQuery snippets for the hover and mouseover events in the tutorial:

      $("a").hover(function(){

        alert("You hovered over the link!");

      });
      $("a").mouseover(function(){

        alert("You mouseover'd the link!");

      });

Mouseover’d? Sure, that’s a word.

Let me know in the comments if you have any questions.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>