0

I've written this function:

(function($){
    $.fn.loaderHolder = function(action){
        var loaderHolder = $(document.createElement('div'))
                                .addClass('loaderHolder'),
            safeImage = $(document.createElement('img'))
                            .attr("src", "/static/images/icons/vault-bg.svg")
                            .addClass("safe"),
            lockImage = $(document.createElement('img'))
                            .attr("src", "/static/images/icons/vault-lock.svg")
                            .addClass("lock"),
            loader = loaderHolder.append(safeImage, lockImage);

        return this.each(function(){
            if(action === "add"){
                $(this).append(loader); 
            } else if(action === "remove"){
                $(this).children('.loaderHolder').remove();
            };
        });
    };
}(jQuery));

This function generates or deletes a loader. I can run the function like this: $('.foo').loaderHolder('add');.

But if I want to add loaders to elements which are dynamically generated, I need to write my code like this:

$('.holder').on('click', '.foo', function(){
   $(this).loaderHolder('add'); 
});

I really don't like the anonymous function. Is there any other way to write this without the anonymous function?

Thanks!

Edit: thanks for all the responses. Edited my code to be correct, forgot the use the parent-selector in the dynamically-generated part.

But I was just wondering about a markup something like this:

$('.holder').on('click', '.foo', {action: 'add'}, $(this).loaderHolder); 

I know this is wrong, but is there any way to do it right like this? Or do you just need to anonymous function?

DavidWorldpeace
  • 519
  • 2
  • 7
  • 22

1 Answers1

2

Give function name in place of anonymous function

$('.foo').on('click', youfun);

For dynamically added elements you need event delegation.

$('staticParentSelector').on('click', '.foo', youfun);

Event delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

Adil
  • 146,340
  • 25
  • 209
  • 204