I am creating an autosuggest box that has a of suggestion returned to it, and I am trying to add/remove the class "searchsuggestinnerulhighlight" to individual links. Here is the dynamically returned ta
<DIV id="searchsuggestinner">
<UL id=searchsuggestinnerul>
<LI>
<A href="#" id="1" class = "hoverme" onMouseDown="searchsuggestSubmit('appalachian trail');">appalachian trail</A>
</LI>
</UL>
</DIV>
And here is my jQuery:
$(".hoverme").live("mouseover mouseout", function(event) {
if ( event.type == "mouseover" ) {
$("#" + mocount).removeClass("searchsuggestinnerulhighlight");
mocount = $(this).attr('id');
$("#" + mocount).addClass("searchsuggestinnerulhighlight");
} else {
$("#" + mocount).removeClass("searchsuggestinnerulhighlight");
}
});
Originally I had .css("background-color"... and now I've changed it to add class and remove class and it does not work. Any ideas?
I am creating an autosuggest box that has a of suggestion returned to it, and I am trying to add/remove the class "searchsuggestinnerulhighlight" to individual links. Here is the dynamically returned ta
<DIV id="searchsuggestinner">
<UL id=searchsuggestinnerul>
<LI>
<A href="#" id="1" class = "hoverme" onMouseDown="searchsuggestSubmit('appalachian trail');">appalachian trail</A>
</LI>
</UL>
</DIV>
And here is my jQuery:
$(".hoverme").live("mouseover mouseout", function(event) {
if ( event.type == "mouseover" ) {
$("#" + mocount).removeClass("searchsuggestinnerulhighlight");
mocount = $(this).attr('id');
$("#" + mocount).addClass("searchsuggestinnerulhighlight");
} else {
$("#" + mocount).removeClass("searchsuggestinnerulhighlight");
}
});
Originally I had .css("background-color"... and now I've changed it to add class and remove class and it does not work. Any ideas?
Share Improve this question edited May 20, 2011 at 21:30 Gabe 50.5k29 gold badges145 silver badges182 bronze badges asked May 20, 2011 at 21:14 AdamAdam 213 bronze badges3 Answers
Reset to default 5Change:
$("#" + mocount).add("searchsuggestinnerulhighlight");
To:
$("#" + mocount).addClass("searchsuggestinnerulhighlight");
mocount = $(this).attr('id');
$("#" + mocount)
That's seriously dodgy jQuery!
First, you don't need attr
to get the id
. You can get it with this.id
. This is far, far quicker.
Second, you don't need to get the id
to get a jQuery selection containing the clicked element. Just use $(this)
instead.
Finally, as Gabe has said, use addClass
rather than add
. So, all in all:
$(this).addClass('searchsuggestinnerulhighlight');
One other thing, though -- using a ID value starting with a number was not allowed in HTML before HTML5. Its behaviour is not guaranteed.
I would put this in a ment, but I can't. Implement lonesomeday's changes, but when he uses $(this).id, try just using this.id as 'this' should already be a jquery object. (We don't want $($(this)).)