Javascript / Jquery onclick function condensation

I was wondering if what can I do with my codes to make it shorter. Here is my code, it is like a simple tabs. Btw, this codes are already working, but I'm thinking that if i have many tabs then I have to repeat many click functions. Is there a way to make my script shorter, Thanks in advance.

$(function () {
    $(".invMer, .invEq").hide();

    $(".mergers a").click(function () {
        $(".invMer").fadeIn();
        $(".invEq, .invPe").hide();
    });

    $(".equity a").click(function () {
        $(".invEq").fadeIn();
        $(".invMer, .invPe").hide();
    });

    $(".privateEq a").click(function () {
        $(".invPe").fadeIn();
        $(".invMer, .invEq").hide();
    });

Answers 1

  • Use a data attribute

    <a data-show=".invPe">
    

    and do

    $("a[data-show]").on("click", function () {
        var selector = $(this).data("show"); 
        $(".invMer, .invEq, .invPe").hide();
        $(selector).fadeIn();
    });
    

Related Articles