Shortcut in jquery

I have these 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 I write a shorthand for two similar jquery codes? thanks in advance

+3
source share
4 answers

Try the following:

 $(document).ready(function() {
    $("#masthead ul li, #intUl li").mouseover(function(){
        $(this).removeClass("cr");
        $(this).toggleClass("cr");
    });
 }); 
+1
source
$('#masthead ul li, #intUL li').mouseover(function() {
    $(this).siblings().removeClass("cr");
    $(this).toggleClass("cr");  
});

It has the same meaning as the source code; not sure why you are deleting a read-only class. If you are trying to make it flare up or something else, I am sure that it will not work as you expect.

Unknown initial intention; the commenter clarified for me and I fixed it :)

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

$(document).ready(function() {
    $("#masthead ul li, #intUl li").mouseover(toggleCRClass);
}); 
+1
source
$('#masthead ul li, #intUL li').mouseover(function() {
    $(this).addClass('cr').siblings().removeClass('cr');
});
+1
source

Source: https://habr.com/ru/post/1729565/


All Articles