jQuery code is too long, need help to simplify [closed]

This code is working, but I was looking to get this simplified. I don’t know how to make this work in a very simple way. Looking forward for everyone’s help. Any idea is welcome.

jQuery("#state-of-the-art .fl-tabs-label").click(function() {
    stateOftheArt();
});

jQuery("#everything-you-need .fl-tabs-label").click(function() {
    everythingYouNeed();
});

jQuery("#monitor-your-sites .fl-tabs-label").click(function() {
    monitorYourSites();
});


function stateOftheArt() {
    jQuery("#state-of-the-art .fl-tabs-panel").addClass("tab-animation-fadeup");
    setTimeout(function () {
        jQuery("#state-of-the-art .fl-tabs-panel").removeClass("tab-animation-fadeup");
    }, 400);
    return
}

function everythingYouNeed() {
    jQuery("#everything-you-need .fl-tabs-panel").addClass("tab-animation-fadeup");
    setTimeout(function () {
        jQuery("#everything-you-need .fl-tabs-panel").removeClass("tab-animation-fadeup");
    }, 400);
    return
}

function monitorYourSites() {
    jQuery("#monitor-your-sites .fl-tabs-panel").addClass("tab-animation-fadeup");
    setTimeout(function () {
        jQuery("#monitor-your-sites .fl-tabs-panel").removeClass("tab-animation-fadeup");
    }, 400);
    return
}

Without having your html code, i can only guess but this could be a solution:

function tabAnimation(obj) {
    var _obj = jQuery(obj);
    _obj.addClass("tab-animation-fadeup");
    setTimeout(function () {
        _obj.removeClass("tab-animation-fadeup");
    }, 400);
}

jQuery(".fl-tabs-label").click(function () {
    tabAnimation(this);
});

You can move the content of tabAnimation inside the click function.

Demo

function tabAnimation(obj) {
    var _obj = jQuery(obj);
    _obj.addClass("tab-animation-fadeup");
    setTimeout(function () {
        _obj.removeClass("tab-animation-fadeup");
    }, 400);
}

jQuery(".fl-tabs-label").click(function () {
    tabAnimation(this);
});
.tab-animation-fadeup{
  color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fl-tabs-label">
  div1
</div>

<div class="fl-tabs-label">
  div2
</div>

<div class="fl-tabs-label">
  div3
</div>

You can create a function that takes your html element as an argument.

function anyFunction(element) {
    jQuery(`${element} .fl-tabs-panel`).addClass("tab-animation-fadeup");
    setTimeout(function () {
      jQuery(`${element} .fl-tabs-panel").removeClass("tab-animation-fadeup`);
    }, 400);
}

//call that function 
jQuery("#state-of-the-art .fl-tabs-label").click(function() {
    anyFunction('#state-of-the-art')
});

jQuery("#everything-you-need .fl-tabs-label").click(function() {
    anyFunction('#everything-you-need')
});

jQuery("#monitor-your-sites .fl-tabs-label").click(function() {
    anyFunction('#monitor-your-sites')
});

Leave a Comment