jasmine
jasmine

Reputation:

shorthand in jquery

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

Upvotes: 3

Views: 272

Answers (4)

Om Shankar
Om Shankar

Reputation: 8069

$('#masthead ul li, #intUL li').mouseover(function() {
    $(this).addClass('cr').siblings().removeClass('cr');
});

Upvotes: 1

Parrots
Parrots

Reputation: 26902

function toggleCRClass(event) {
    $(event.target).siblings().removeClass('cr');
    $(event.target).addClass('cr');
}

$(document).ready(function() {
    $("#masthead ul li, #intUl li").mouseover(toggleCRClass);
}); 

Upvotes: 1

Erik
Erik

Reputation: 20722

$('#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 :)

Upvotes: 6

Jamie Ide
Jamie Ide

Reputation: 49291

Try this:

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

Upvotes: 1

Related Questions