Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I improve this JQuery code

Tags:

jquery

I'm researching the optimising of JQuery code and was wondering if there is a way to better this code as it seems quite 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);
            }
        }
    );

Many thanks in advance!


2 Answers

You can eliminate your conditionals by passing a filter to the parent function:

$('#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 <a> elements are immediate children of the <li> elements, you should use Josh's solution.

like image 95
TM. Avatar answered Apr 29 '26 17:04

TM.


$("#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);
    }
);
like image 24
John Rasch Avatar answered Apr 29 '26 17:04

John Rasch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!