Eder Iraizoz
Eder Iraizoz

Reputation: 113

jQuery performance | Avoid repeating code

Note

I think I can explain this without a jsfiddle. I'll avoid to show the whole code because there is too much HTML with lots of classes that I would have to adapt to the example.

Also, excuse my bad English. I hope you understand me. Im learning.

The point is

I have some modules that overlays my interface when the user activates the respective button. I want all the modules do the same animation when opening.

How is it now?

Now I am repeating again and again the same code (below), but pointing to each module and its respective button... I'm a newb in terms of javascript but I know this is anti-performance... I feel like I can do it cleaner.

My doubt

Is there a way to make a function or something with this code to allow it to work for all the modules I want, without repeating it again and again?

$('#btn-moduleX, #close-moduleX').on('click', function(){
    $( "#btn-moduleX" ).toggleClass('layout-color-subBase');
    $( "#overlay-moduleX" ).toggleClass('overlay--hidden');

    var currentOpacity = $('.fx-appear-soft').css('opacity');
    $( ".fx-appear-soft" ).animate({
        'opacity': 1 - currentOpacity
    }, 300);
});

Upvotes: 1

Views: 50

Answers (1)

Andrew Surzhynskyi
Andrew Surzhynskyi

Reputation: 2776

Lets imagine your button was looking like this:

<a id="btn-moduleX" href="#">Button</a>

What we do is removing the id and adding the class name that will be the same for all the buttons and the data-module attribute, where we do write the related module name.

<a class="jsCloseModule" href="#" data-module="moduleX">Button</a>

new JavaScript code:

$('.jsCloseModule').on('click', function(){
    var moduleName = $(this).data('module');
    $( "#btn-" + moduleName ).toggleClass('layout-color-subBase');
    $( "#overlay-" + moduleName ).toggleClass('overlay--hidden');

    var currentOpacity = $('.fx-appear-soft').css('opacity');
    $( ".fx-appear-soft" ).animate({
        'opacity': 1 - currentOpacity
    }, 300);
});

This is just an example. Your application could be optimized much more, all that id's like "#btn-" + moduleName could be changed to classes too.

Upvotes: 1

Related Questions