cult3

jQuery Mouse Events

Nov 28, 2012

Table of contents:

  1. How Events work
  2. Anonymous functions
  3. Ready Event
  4. Click
  5. Double click
  6. Hover
  7. Mouse Down
  8. Mouse Up
  9. Mouse Enter and Mouse Over
  10. Mouse Out and Mouse Leave
  11. Mouse Move
  12. Scroll
  13. Conclusion

Manipulating style or content are the building blocks to really being able to do useful stuff with jQuery. However, in reality, you aren’t going to be writing jQuery to manipulate the DOM or the style of your page on load as you would just change the HTML or CSS in the first place.

One of the real advantages of jQuery is the ability to take actions on events. Say for example, you want to do a certain action when you “clicked” on an element in the DOM. This would be an event.

Today we will be looking at the jQuery Mouse Event functions and how you can use them to interact with the DOM.

How Events work

In order to trigger an Event, we need to listen for it. When you click on something in the DOM, Javascript will work it’s way through the elements to look for an attached event. So If you were to click on a span, it would first look to see if any events had been attached to the span, then the paragraph then the div and so on as it works it’s way up the DOM. When you listen for an event, you need to pass it a function in order get it to actually do something. Take a look at the Javascript functions tutorial to refresh your memory on functions.

Anonymous functions

When passing a function to the Event handler, the function will be anonymous. This simply means the function has no name.

// Regular version
function helloWorld() {
    console.log("Hello world");
}

// Anonymous version
function () {
    console.log("Hello world");
}

Anonymous functions can’t be trigged in the usual fashion of a function because they have no name. Instead, you pass them to another function as an argument.

Ready Event

As I mentioned in the Introduction to jQuery tutorial, when we load a web page that has jQuery code, we need to wrap it in a Document Ready block so that the jQuery isn’t fired too early. This is because jQuery will look for the elements you have selected before they have been loaded into the DOM. To get around this, we need to ensure the DOM has loaded, before we run the jQuery.

Here is an example of a document ready block.

$(document).ready(function () {});

Ready is a jQuery event that will wait for the DOM to load before running. If you search for jQuery example code, it will nearly always be wrapped in the Document Ready block.

From now on I won’t be writing this out in every example. Just remember, if you want to use any of the examples within a Javascript file, you will need to wrap them in this block to ensure they are run once the DOM has loaded.

Click

The first event we will be looking at is the Click event, probably one of the most common events you will end up using.

The Click event is fired when you click on the selected element.

Say you wanted to show some meta data about the status when a user clicks on it, how would we do that?

First we select the element from the DOM and add the Click method:

$("div#timeline p").click();

Next we pass it an anonymous function:

$("div#timeline p").click(function () {});

And finally we use the Append method to add in the meta data.

$("div#timeline p").click(function () {
  $("div#timeline p").append("<p>3 retweets</p>");
});

Say you wanted to write a rule for all span tags, but you only wanted the span tag you clicked on to have the event run on, how could you achieve this?

First we write out the click event for span tags:

$("span").click(function () {});

Next we use the this keyword to refer to the current element, and hide it. If you take a look at the Javascript Objects tutorial, you’ll find a deeper explanation of the this keyword.

$("span").click(function () {
  $(this).hide();
});

So you can specify a rule like “Hide span tags when you click on them”, then use the this keyword to refer to the element you just clicked on.

Double click

The double click event is obviously just the same as the click event but for double clicks so it doesn’t really need much of an explanation. It’s worth highlighting though, just so you know this event is available to you.

$("p").dblclick(function () {
  $(this).append("<span>extra stuff</span>");
});

Hover

The Hover event allows you to bind two handlers to the element for moving the mouse over it, and then moving the mouse away.

The syntax for the Hover event is:

$(selector).hover(handlerIn, handlerOut);

So first you select the element, next you attach the Hover method, and then you pass it two functions for the mouse enter and the mouse leave.

For example:

$("p").hover(
  function () {
    $(this).prepend($("<span>→</span>"));
  },
  function () {
    $(this).find("span").remove();
  }
);

In this example, we prepend the span when the user hovers over the paragraph. Then we use the Find method to get the span and remove it when the user moves away from the paragraph. The Find method searches for descendant elements, in this case, it looks for span tags that are descendants of the current paragraph element. If our markup was more complicated, you could make this search more specific by including an id, class or pseudo class.

Mouse Down

The Mouse Down event is similar to the click event in that it is fired when you hover over an element and click it. You can use the Mouse Down event on any type of element.

$("#more").mousedown(function () {
  alert("So you want to see more?");
});

Mouse Up

The Mouse Up event works in the same way as the Mouse Down event, but is fired when the mouse is hovered over an element and the mouse button is released. Again, any element can use this event.

$("#more").mouseup(function () {
  alert("Show some more");
});

Mouse Enter and Mouse Over

The Mouse Enter and Mouse Over events are very similar, but with slightly different results. It is worth grouping these two events together so you can distinguish which one you want to use to achieve your desired outcome.

Both of these events are triggered when the mouse hovers over an element, however they handle event bubbling differently. As I mentioned in the How do Events work section, when an event is triggered it will bubble it’s way up the DOM looking at the parent elements.

When you use the Mouse Enter event, the event won’t bubble up the DOM, whereas if you use the Mouse Over event, it will.

If you take a look at the jQuery documentation for Mouse Enter, there is an excellent working example of the two events running side-by-side which might make this explanation clearer.

These two events might not seem very different, but using the wrong one could have undesirable effects. Mouse Enter is better when you want to isolate the event to just the current element and not have it bubble up to the parent elements. This will usually be the case.

Mouse Out and Mouse Leave

Similar to the Mouse Enter and Mouse Over events, the Mouse Out and the Mouse Leave events are triggered when the Mouse moves away from an element.

Again the two events differ by how they handle bubbling. The Mouse Leave event will only trigger it’s handler when it leaves the element it is bound to.

Take a look at the jQuery document for Mouse Leave for a working example of the two events side-by-side.

Again, this difference might not seem that great in the context of this tutorial, but it will matter when you want to create an interface using these events. Using the incorrect event will usually end up having undesirable consequences.

Mouse Move

The Mouse Move event is useful when you need to track the position of the mouse within an element. When you move the mouse into an element that has the Mouse Move event attached, you are passed the coordinates of the mouse as it is tracked around the element.

$("#target").mousemove(function (e) {
  var msg = "The mouse is at ";
  msg += e.pageX + ", " + e.pageY;
  console.log(msg);
});

Here we are tracking the X and Y position of the mouse and then printing a message to the console.

Scroll

The Scroll event can be attached to either elements in the DOM or the window object itself and is fired when the user scrolls.

$(window).scroll(function () {
  console.log("Weeeeeeeeee");
});

A common application of the Scroll event is to load in additional content when the user hits the bottom of the screen. This is known as Infinite Scrolling.

To achieve this effect, you could write something like this.

$(window).scroll(function () {
  if ($(document).height() == $(window).scrollTop() + $(window).height()) {
    alert("You can load more stuff now");
  }
});

Conclusion

Those were the main jQuery Mouse Events as an introduction to jQuery events. Events are crucial to building interactive websites that feel like applications in the browser.

Events form an integral part of jQuery, and so I’ve split this tutorial over two weeks. Come back next week to learn all about Form Events.

Philip Brown

@philipbrown

© Yellow Flag Ltd 2024.