.addClass to red planet


#1

https://www.codecademy.com/courses/web-beginner-en-JwhI1/0/4

$(document).ready(function() {
   $('div').click(function() {
       $(this).hover(function(){
           $(this).addClass('red');
               $(this).fadeOut('fast'); 
       });
   });
});

#4

It is not wise to declare a listener inside another handler.

The click handler should be independent of the hover handler.

   $('div').click(function() {
       $(this).fadeOut('fast'); 
   });
   $('div').hover(function(){
       $(this).addClass('red');
   });

Alternately since they are both bound to the same selector,

   $('div').hover(function(){
       $(this).addClass('red');
   }).click(function() {
       $(this).fadeOut('fast'); 
   });

This is commonly known as method chaining. Both listeners will have bindings to the same object(s).

There is an even more refined approach using on if you are interested. Ping this topic if you would like to see it.


#5

Thanks for your advice!! To separate the function looks right.

I am stuck on the addClass part which i missed out on. Can’t recall what I should put here or how to find it?


#6

When the listeners are separated, your addClass statement is correct. However, if your would like the color to revert back to green on mouseleave, then use, toggleClass instead. Recall that the green class is the default. jQuery preserves the className that is present when it toggles another class into that node.


#7

Toggle is great but doesn’t seem to do the trick to turn the planet red.

$(document).ready(function(){
$(‘div’).click(function() {
$(this).fadeOut(‘fast’);
});$(‘div’).hover(function(){
$(this).toggle(‘red’);
});
});


#8

toggleClass('red')

As for method chaining, think of the order of the mouse events. hover comes first, click comes after that.

Check my example above, but use toggleClass instead of addClass.


#9

what i need instead of toggle class is a class that will change the planet to red when my mouse hovers over it or clicks it. Any ideas?


#10

The exercise is to have the planet turn red when we hover, and fade out when we click. The code I gave you above is all you need. If you are trying to do something else, then that falls under, experimentation and will mean moving this topic to Corner Bar for open discussion of ideas. We do not take that road in the Q&A.

If you have locked in your thinking upon a certain set of ideas which are wrong or not practical, then all you have done is blind yourself. In programming this is never a good thing to do. It will keep you from accepting working solutions while you force your own into being.

We must keep an open mind and toss aside the blinders. Ideas come from all directions, and we need to be receptive to them else we stymie our own ability to think creatively and out of the box.


#11

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