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?