6. Hover


#1



https://www.codecademy.com/courses/web-beginner-en-JwhI1/1/2?curriculum_id=50a3fad8c7a770b5fd0007a1


I'm pretty sure this is correct. Can someone tell me why it is wrong, and tell me where the mistake is? The error message I get is "Oops, try again. It doesn't look like your background color changed, is your hover adding the class active? "


$(document).ready(function(){

  $('div').hover(
    function(){
        $('div').addClass('active');
    },
    function(){
        $('div').removeClass('active');
    }
  );

});


#2

@hauboldj,

<!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>

( the interpretation of the DOM )

                html
                 |
           +-----+------------+
           |                  |
         head                body
           |                  |
  +-----+--+---+          +---+----+---------+
  |     |      |          |        |         |
title  link script       div      div       div

Now if you use

$('div' ).hover();

you will =attach= the hover() Eventhandler to each of the div-HTML-Elements separately.
And after reading
https://api.jquery.com/hover/
you will know
that if you define the hover()-Eventhandler to have 2 function's separated by a comma-,
the 1st is interpreted as a mouseenter() function
the 2nd is interpreted as a mouseleave() function

So what must be clear,

  • is that each div-Tag has its own hover() Eventhandler attached
  • and that if you hover-your-mouse over 1 of the div's
    you can use the reference-keyword this
    in your jQuery-Selector.....
    Thus you will have to use

$('div' ).hover(
      // mouseenter
      function(){
           $(this).addClass('active')
      },
      // mouseleave
      function(){
           $(this).removeClass('active')
      }
 );

============================================

Depending on your Browser the opacity property may differ....
To circumvent eventual Browser specifity
i would recommend to use following code in your stylesheet CSS file

div {
    border-radius: 5px;
    background-color: #ABCDEF;
    transition: background-color 0.5s ease;
    display:inline;
    font-size:25px;
    padding:20px;
    border:1px solid #ccc;
    margin-top:10px;
    opacity: 1;
}

.active {
    background-color:#556677;
    opacity: 0.25;
}

#3

There is no problem with your code. If you click "save and submit code", then first hover on "HOME",then on "About US" and then on "Contact". you will get no error message.


#4

Thanks, @netwhiz08927