Learn JQuery Step By Step Part 2: Events

Events in JQuery are nothing more than user or browser actions, you probably used then in Javascript, remember “onload”, “onclick”, “onkeyup”, “onsubmit” etc? well, that’s exactly what events are and you’ll be glad to know that they kept the same name in JQuery, except for the “on” part, so hey! there is less typing to do!

To use events in JQuery all you have to do is attach the event at the end of an object. Let me illustrate this by covering my favorite event first.

click( ) or click( fn )

All events in JQuery have two forms, in this case click(), for which I have not found a good use for, and click(fn), meaning that you can pass a function to the event.

Of this two forms I will cover click(fn) first. What we are going to to is nothing more than a button that when it’s clicked alerts a string. Go ahead and make a button using the <button> tag in html.

<button>Click Me!!!</button>

Once you’ve loaded JQuery add the followings snippet of code to your file.

$(document).ready(function(){

$("button").click(function(){alert("Boo!");});

});

Which you can also write in several lines if you prefer.

$(document).ready(function(){

  $("button").click(function(){
    alert("Boo!");
  });

});

You can see from my code that to attach an event to a selector all you have to do is put a dot after the selector followed by the event. In our snippet, when the button tag is clicked the function inside the click event gets executed – and no, you don’t have to name your functions.

Now let’s talk about the second other form of click, “click()” without a function been passed to it. To make this example work you’ll need a textarea and a button.

<textarea>

</textarea>
<button>Am a Button</button>

Now add the following snippet in your JQuery section.

$(document).ready(function(){
    $("textarea").keyup(function(){
         $("button").click();
     });

    $("button").click(function(){
       alert("ha ha!");
     });
});

Here I’ve introduced another event, keyup, which has the same forms of click – keyup() without a function and keyup(fn) with a function. This event goes on when the user presses and releases a key.

The keyup event in this example is attached to the textarea tag, and it contains a function that triggers a click on the button which triggers our second click function that alerts the string “ha ha!”.

So there you go, that’s how you use events. Next time we’ll cover JQuery effects which is where you’ll begin to see why JQuery is so popular, in the mean time here is the full list of events for you to try.

blog comments powered by Disqus