2

I have the following jQuery code which works as just the class, but the :hover causes it not to work.

$('.dd_question:hover').css('border','1px dashed #333333');

Is there some special code I can use inside th $() method? Or is :hover simply not allowd?

4
  • 2
    simply not allowed. Well, it is allowed, but think about it and you'll probably realize why it doesn't work. Commented May 20, 2013 at 17:50
  • 2
    try $('.dd_question').hover(function() { $(this).css('border','1px dashed #333333'); }); Commented May 20, 2013 at 17:50
  • 1
    Just curious, if you are just toggling the CSS, why not simply use CSS? Commented May 20, 2013 at 17:51
  • @Swordfish0321: The obvious answer is that he only sometimes wants hovering over the dd_question elements to toggle the border. If it is behavior that should always happen, then you are of course correct, and straight CSS is the way to go. Commented May 20, 2013 at 17:56

2 Answers 2

6

The jQuery selector selects elements that match the selector when the code is executed, not when the user hovers over an element.

With that in mind, $('.dd_question:hover') will only select elements that have that class and that were currently being hovered over when the code was executed which most likely was 0 elements.

You need to either use the mouseenter and mouseleave events (or hover for short), or simply use css.

Sign up to request clarification or add additional context in comments.

Comments

6

Other people have already explained why the code you're using isn't working, but the other question is how to fix it. Probably the best way to get the effect you're looking for is to have

.hoverborder:hover {border: 1px dashed #333333;}

in your css, and then use

$('.dd_question').addClass('hoverborder');

in your javascript.

1 Comment

Thanks, I'm looking for work arounds now since it's clear that simply :hover inside my jQuery method won't work, and this looks like it may do the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.