How can I improve this jQuery code

I am studying jQuery code optimization and wondered if there is a way to improve this code as it seems rather long ...

$("#tabs-nav li a").hover(

        function(){
            if($(this).parent().hasClass('active')) {
            } else {
                $(this).stop().animate({ opacity: 1, marginTop: '24px'}, 200);
            }   
        },
        function(){
            if($(this).parent().hasClass('active')) {
            } else {
                $(this).stop().animate({ opacity: 0.4, marginTop: '29px'}, 200);
            }
        }
    );

Thank you very much in advance!

+3
source share
4 answers

You can eliminate your conditional conditions by passing a function filter parent:

$('#tabs-nav li a').hover(function() {
    $(this).parent(':not(.active)').children('#tabs-nav li a').stop().animate({ opacity: 1, marginTop: '24px'}, 200);
}, function() {
    $(this).parent(':not(.active)').children('#tabs-nav li a').stop().animate({ opacity: 0.4, marginTop: '29px'}, 200);
});

If your elements <a>are immediate children of the elements <li>, you should use the Josh solution.

+2
source
$("#tabs-nav li:not(.active) a").hover(
    function(){
        $(this).stop().animate({ opacity: 1, marginTop: '24px'}, 200);
    },
    function(){
        $(this).stop().animate({ opacity: 0.4, marginTop: '29px'}, 200);
    }
);
+2
source
$(".active #tabs-nav li a")...

, , if. , , . .

0

, :

 function(){
                if($(this).parent(':not(".active")')) {
                        $(this).stop().animate({ opacity: 1, marginTop: '24px'}, 200);
                }   
        }
0

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


All Articles