简体   繁体   中英

Loading on click on all “a” HTML elements

I want to show loader when someone clicks on any element on my site.

My Code:

(function ($) {
    $('body').append("<div id='loader-box'></div>");
    $("loader-box").html("");
    $("a").on('click', function (e) {
        $("loader-box").html("<div class='loader-wrapper'><div class='loader-image'></div></div>");
    });
}(jQuery));

The problem is that append does not work. I do not understand why. Thanks!

--- UPDATE ---

I found a solution, thanks to all especially Andrei Cristian Prodan who helped me to solve the problem with .on() function. I also use the wrong function to add "loader-box" div.

This is my code:

(function($){
    $("body").prepend('<div id="loader-box"></div>');
    $("#loader-box").html("");
    $("html").on("click", "a",function(){
        $("#loader-box").html('<div class="loader-wrapper"><div class="loader-image"></div></div>');
    });
}(jQuery));

Thanks!

You are missing a "#" in your selector $("#loader-box");

Also if you are executing this code before the anchors exist in your page (for eg at the top of your body or inside the header), the click will not be assigned because $('a') will be empty.

Do this instead: $('html').on('click', 'a', function() {...} );

Your selectors are just a little off; missing #:

<script>
$(function($){
    $('body').append("<div id='loader-box'></div>");
        $("#loader-box").html("");
        $("a").on('click', function(e){
            $("#loader-box").html("<div class='loader-wrapper'><div class='loader-image'></div></div>");
        });
});
</script>

And DOM ready needs to be written correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM