Tried to make a while-loop. failed miserably


#1

https://www.codecademy.com/en/courses/web-beginner-en-JwhI1/0/4?curriculum_id=50a3fad8c7a770b5fd0007a1
Hey guys,

Code is fine, but I tried to get fancy. When I hover over the

in this exercise, I want it to change from green to red as many times as possible. When I added a green class to make the
switch back to green, it worked. But then it wouldn't switch back to red.

Pretty much every (while) or (for) loop I tried to use either crashed the browser or had no effect. Any ideas on how to make the hover not be permanent? AKA change from Green---->to Red---->back to Green--- as many times as I hover over it?

In my CSS code there is a new class called .green. That is why you see a reference to ('green') in my code. It is the exact copy of CSS for

.

Help would be much appreciated!

Michael

$(document).ready(function() {
    $('div').click(function() {
       $('div').fadeOut('fast'); });
    $('div').mouseenter(function() {
        $('div').addClass('red');});
    $('div').mouseleave(function() {
        $('div').addClass('green');});
});

#2

In your CSS write the default for the element. If you want RED on mouseover, then set the other as the default.

div {
    background-color: green;
}
.red {
    background-color: red;
}

Now just removeClass('red') on mouseleave().


#3

You know what I just found that worked...
.toggleClass()

brilliant.


#4

That worked just as well, even better!
Thank you.


#5

toggleClass() is better used in a hover() event handler.

$('div').hover(
    function() {
        $(this).toggleClass('red');
    }
);