tags:

views:

82

answers:

3

I have this jquery codes:

 $(document).ready(function() {
$("#masthead ul li").mouseover(function(){
    $("#masthead ul li").removeClass("cr");
    $(this).toggleClass("cr");
});
   }); 

  $(document).ready(function() {
$("#intUl li").mouseover(function(){
    $("#intUl li").removeClass("cr");
    $(this).toggleClass("cr");
});
}); 

Can we write shorthand for two similar jquery code? Thanks in advance

+6  A: 
$('#masthead ul li, #intUL li').mouseover(function() {
    $(this).siblings().removeClass("cr");
    $(this).toggleClass("cr");  
});

Does the same as the original code; not sure why you're removing a class only to readd it, however. If you're trying to get it to flash or something, I'm fairly sure it won't work as you're expecting.

Misunderstood original intent; a commenter clarified for me, and I fixed it :)

Erik
dammit, I type too slow. +1
Ed Woodcock
That won't actually do what he's trying to achieve. You're removing the cr class from the same element you mousedover and then toggle it. He wants to remove it from all the siblings first and then add it to the moused over. So only one LI will have 'cr' at a time.
Parrots
you're right, editing to fix with .siblings
Erik
Much better ;) +1
Parrots
@Parrots I'd missed that, well played
Ed Woodcock
toggleClass should be addClass since removeClass won't apply to the source element unless you do .siblings().andSelf()?
Dave Cluderay
+1  A: 
function toggleCRClass(event) {
    $(event.target).siblings().removeClass('cr');
    $(event.target).addClass('cr');
}

$(document).ready(function() {
    $("#masthead ul li, #intUl li").mouseover(toggleCRClass);
}); 
Parrots
+1  A: 

Try this:

 $(document).ready(function() {
    $("#masthead ul li, #intUl li").mouseover(function(){
        $(this).removeClass("cr");
        $(this).toggleClass("cr");
    });
 }); 
Jamie Ide