Understanding the hover event exercice


#1

I have two questions :
- First : Why using $(this).hover instead of $('div').hover doesn't work ? From what I understand, you're basically saying IF you are hovering the element below your mouse cursor => addClass to this element.

  • Second : If you translate the correct code you're telling to addClass to the element below your mouse IF you're hovering any div element. So for example if you're hovering the "HOME" div, it'll add the class="active". No issue there.
    But I don't really understand the removeClass part. If you're using the same reasoning, you're also saying to removeClass when hovering this element.
    I personnally thought using toggleClass makes more sense.
    (I hope I was clear)


<!DOCTYPE html>
<html>
	<head>
		<title>Ghostly Divs</title>
        <link rel='stylesheet' type='text/css' href='stylesheet.css'/>
        <script type='text/javascript' src='script.js'></script>
	</head>
	<body>
        <div>Home</div>
        <div>About Us</div>
        <div>Contact</div>   
	</body>
</html>

// JavaScript code 
$(document).ready(function(){

  $('div').hover(     // Why $(this).hover doesn't work ?
    function(){
        $(this).addClass('active');
    },
    function(){
        $(this).removeClass('active');
    }
  );

});


#2

Inside the ready() handler, $(this) is document, the context object. We need to assign event binding to an object in the document, which here is div. Any DIV.

The hover function senses when the mouse is in a hot zone, whereupon it runs the first function, and when the mouse leaves it runs the second function. They always run in that order,


#3

Got it! Thank you, didn't catch that the function acts as parameters.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.