I have an anchor tag like:
<a href="#actions" data-toggle="tab">Actions</a>
There is a click function for the above anchor
tag:
$('a[href="#actions"]').off('click').on('click', function (e) {
show_overlay_loading($("body"), "Loading actions tab...");
// some stuff runs (takes about 5 secs)
remove_overlay_loading();
});
As you can see, the above function takes about 5 secs to complete. So, I called the function show_overlay_loading
at the beginning of click function. It adds a loading spinner to the body.
After the rest of the code completes, I removed the spinner by calling remove_overlay_loading
at the bottom of the click function.
The two functions are below:
var show_overlay_loading = function(element, helper_text){
var overlay_div = document.createElement("div");
overlay_div.className = "overlay-div-cont";
var overlay_html = `
<div class="overlay-img-cont">
<img src="ajax-loader.gif" class="overlay_image_gif">
<span class="overlay_helper_text">${helper_text}</span>
</div>
`
`
overlay_div.innerHTML = overlay_html;
element.append(overlay_div);
}
var remove_overlay_loading = function(element){
$(".overlay-div-cont").remove();
}
As you can see, the show_overlay_loading
function creates a overlay div and appends it the element passed (in this case, it’s body)The remove_overlay_loading
simply removes the div.
The problem is, when i click, the spinner is not getting added to body. But when i debug, it’s getting added.
Possible cause: the spinner is not getting added because, though function is running, it is appending the element after some time. But by that time, we remove the spinner by calling remove_overlay_loading
. (It’s just my view, idk if it’s correct.)
I arrived at the above cause by modifying the remove_overlay_loading
to the following:
var remove_overlay_loading = function(element){
setTimeout(function(){
$(".overlay-div-cont").remove();
}, 10000)
}
After modifying remove_overlay_loading
to above, the spinner is displayed but after the full click function got completed. The spinner got removed after the timeout
.
Note: The show_overlay_spinner
and remove_overlay_spinner
are being called only once in the whole code and that is inside click function.