Run code on hover

See more about:

Stop! Before you continue, check out the pattern Run code on click.

When you hover on an object, you move your mouse over it, without clicking. Try hovering on the image:

Renata
Ouch!

Here’s what happens:

   When mouse goes over the element:
       Do this
   When mouse leaves the element:
       Do that

So there are two pieces of code attached to an element. One runs when the mouse goes over the element. The other runs when the mouse leaves the element.

Here’s the code for the image above:

<p style="margin-left: 50px;">
  <img id="cute_thing" src="/content_media/patterns/run-code-on-hover/renata_puppy2.jpg" alt="Renata"><br>
  <span id="cute_message">Ouch!</span>
</p>

<script type="text/javascript">
$(document).ready(function () {
  //When page loads, hide the message.
  $("#cute_message").hide();
  $("#cute_thing").hover(
    //Hover enter - show message.
    function(){
      $("#cute_message").show();
    },
    //Hover leave - hide message.
    function(){
      $("#cute_message").hide();
    }
  )
});
</script>

Figure 1. The code, just the code, and nothing but the code

Line 2 shows the image. When the mouse goes over it, code runs.

Line 10 sets up the hover event for the image. It has two functions. The first one runs when the mouse goes over the image. It shows the “Ouch!” message. The second function runs when the mouse leaves the image. It hides the message.

Line 9 makes sure the message is hidden when the page is loaded.

You can do other things besides show and hide an element. You can change the text of an element, change its class, whatever you want.


Be an author

Want to write your own CoreDogish textbook? Check out FlippedTextbook.Com.

How to...

Lessons

User login


Dogs