Reputation: 15
I have written a code in javascript :
When user click on a link, a loading image should be shown till next page loads.
It is working fine when user simply click on link, Loading image is visible till next page loads. But the problem is when a user clicks on link with CTRL button. target page open in new tab of browser and on page from where link was click, loading div continuously shown.
function ShowLoading(e) {
var div = document.createElement('div');
var img = document.createElement('img');
img.src = 'pageloaderB.gif';
img.style.cssText = 'border:0px';
div.innerHTML = "<b style=color:black;font-size:40px;font-family:calibri>Processing Request Please Wait</b><br><br><br>";
div.style.cssText = 'padding-top:200px;position: fixed; top: 0px; left: 0px; z-index: 5000; width: 100%; height:100%; text-align: center; background:white;opacity: .8;';
div.appendChild(img);
document.body.appendChild(div);
return true;
}
<a href="dashboard.php" class="ico1" onclick="ShowLoading()">Dashboard</a>
Javascript:
Please help me to close this. Either simple click or CTRL+Click, Loading div must be invisible when page loads completely.
Upvotes: 0
Views: 114
Reputation:
Instead of using onclick
of link use event beforeunload
. So this will avoid unnecessary call to ShowLoading
.
In case of plain javascript:
window.onbeforeunload=ShowLoading;
With jQuery:
$(window).on('beforeunload',ShowLoading);
Upvotes: 0
Reputation:
Use localStorage
to introduce a "global" variable, i.e. one that spans multiple tabs.
When a link is clicked, you set localStorage['loading']
to true, and in each page's window.onload
event you set it back to false.
When you show the image, you start an Interval that keeps checking the variable. When the page in the new tab has loaded and the variable is set to false, the interval function will hide the image and stop its interval.
(This answer is much more convoluted than simply checking whether the Ctrl key was pressed, but it will even work with a middle mouse click or other ways of opening a link in a new tab.)
Upvotes: 1
Reputation: 335
You can examine the Ctrl, Shift, and Meta key properties of the event object. If either is true, the key control, shift, or meta (Apple's command) key is being held. You'll find a useful JavaScript snippet that will help with solving the problem here: How to detect if user it trying to open a link in a new tab?
Upvotes: 0