Javascript Mouse Enter and Mouse Leave Events

Introduction:

This tutorial is going to be explaining the Javascript/jQuery events for mouse enter and leave.

jQuery Events?

jQuery or Javascript events are triggered when the appropriate event trigger occurs. The trigger is easily determined by simply looking at the event name, for example; this tutorial is on the 'mouse enter' and 'mouse leave' events, which are therefore triggered when the user moves their mouse in to, and out of, the given event area.

HTML:

Before we can start our jQuery we need some basic HTML. This HTML is going to simply consist of an image with the source of 'http://www.sexyli.com/wp-content/uploads/2013/05/Green-Snake-Image-Wallpaper.jpg'.
  1. <head></head>
  2. <body>
  3. <img src='http://www.sexyli.com/wp-content/uploads/2013/05/Green-Snake-Image-Wallpaper.jpg' />
  4. </body>
  5. </html>

Styling:

Next we are just going to give the image a width and height since it's default is 2000 width which is too large for my, and most other's, browsers/monitors...
  1. <img width='500' height='300' src='http://www.sexyli.com/wp-content/uploads/2013/05/Green-Snake-Image-Wallpaper.jpg' />

Inline Events:

Now for the actual Javascript events. First we can choose to opt for inline javascript events, this means we set the function to run on the javascript even trigger within the HTML element we want it to activate on. For our 'mouse enter' and 'mouse leave' events we use the following triggers/events...
  1. <img onmouseenter='entered();' onmouseleave='left();' width='500' height='300' src='http://www.sexyli.com/wp-content/uploads/2013/05/Green-Snake-Image-Wallpaper.jpg' />
As you can see from the above line, we are now running a function named 'entered' when the mouse enters the image area, and a function named 'left' when the mouse exits the image area.

Functions:

The next thing we want to do is create the functions that get ran on the event triggers. In this case they are called 'entered' and 'left'.
  1. <script>
  2. function entered() {
  3. alert(1);
  4. }
  5.  
  6. function left() {
  7. alert(2);
  8. }
  9. </script>
The above code goes in your 'head' tags of your current HTML page. As you can see from the functions, when the mouse enters, the 'entered' function gets ran, then an alert box pops up saying '1'. The same happens for the mouse leave event, except '2' is output instead of '1', but in the same format.

Finished!

That's all there is to it. Of course, you can now perform more helpful scripts on the events, such as animating the image when the mouse is over it.

Add new comment