I want to prevent two events from being watched for an element (mouseenter and mouseleave to be specific) if that certain element doesn’t have a css class defined.
The flow of this system is
-
On document ready, I add the class .selected to the #menu_top_option_1 element
$("#menu_top_option_1").addClass("selected"); -
There is a sensor for those two events
$("#menu_top_option_1").not(".selected").on({ mouseenter: function(){ $(this).addClass("highlighted"); }, mouseleave: function(){ $(this).removeClass("highlighted"); } }); -
When there is a click event I add the class .selected to the #menu_top_option_1 element.
$("#menu_top_option_1").click(function () { $("#menu_top_arrow_img").animate({left: position_menu_top_option_1+'px'}, 500); $(this).removeClass("highlighted"); $("#option_wrapper div.option").removeClass("selected"); $(this).addClass("selected"); });
The problem: this does not work as expected. The elements still have the same hover events as they did before being assigned the .selected even after adding .selected to them. Except for the #menu_top_option_1 element, because I suspect it does have that class added at document ready.
Any suggestions?
You should bind the event handler to all of the elements and then inside that event handler, check to see if the current element being clicked has the
selectedclass:Here is a demo: http://jsfiddle.net/g8W4z/
Some documentation:
.hasClass(): http://api.jquery.com/hasclass.siblings(): http://api.jquery.com/siblings