Combining .click() and .hover() - using alternate code to what the lesson asks for


#1


Combining .click() and .hover()


So I don't need help with the exercise, I'm just more confused why this alternative method doesn't work. The exercise wants the div to change colour after you hover over it and uses a .addClass to change the it to red with a class rule in the .css for background-color: red; I figured I'd try out just modifying the css instead to make the code cleaner. What I used in my jQuery is listed below, but it doesn't work. I can get the .addClass to work, but I'm curious why my code doesn't work.


$('div').hover(function() {
  $("div").css("background-color", "red");
});

Thanks for anyone that can shed any light on this.


#2

which in fact it does not. Having the styles tucked away in the style sheet is much cleaner, and the reason we have style sheets. Separation of concerns is the main objective so the code is maintainable.

Something you should note with your above code is that it is universal and applies to all divs, not just the one you hover on.

Before hover:

After hover:

The triggering element is the one that should change color.

$('div').hover(function() {
  $(this).css("background-color", "red");
});

By it doesn't work do you mean it won't pass the exercise? We can see one reason why.


#3

Thanks for the response.

That's the wrong exercise. The one I'm referring to is where you change the planets colour from green to red, then make it disappear. Sort of irrelevant though. I do understand what you're saying about targeting certain divs and how my code is universal. It was an exercise with only one div though. Normally, I would use $(this) so I get what you mean in regards to that.

I didn't realize having more code would be considered cleaner, but I get what you're saying about it being more maintainable with css class in the style sheet.

When I say it doesn't work, I don't mean it just won't pass the exercise. I didn't expect it to because it would be totally different code to what the program would be looking for. Really, I'm just more curious why my code I provided didn't work in the browser. I feel like it's all correct, (it's also in a proper ready function which I know works because it works with the code the lesson is expecting that I used to pass to the next exercise). Are there no glaring flaws to what I've written. I'm just confused.


#4

But it did work, as we see. Unless of course your code does not have a .ready() wrapper. That may explain why. The code may have already run when there was no DOM content present so there are no event listener bindings.

When I run it without a wrapper, nothing happens.


#5

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