0

I have written a code in javascript :

  1. When user click on a link, a loading image should be shown till next page loads.

  2. 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.

Barmar
  • 596,455
  • 48
  • 393
  • 495
  • http://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached?answertab=active#tab-top – Álvaro Touzón Feb 20 '17 at 10:43
  • Not Clear Alvari Touzon, Please help. if link open in new tabe how can we will be sbale to tell back to preovious tabe that target page is loaded. – Ranjan Kumar Feb 20 '17 at 10:48

3 Answers3

1

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.)

Chris G
  • 7,957
  • 4
  • 17
  • 29
0

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?

Community
  • 1
  • 1
Dawid Dworak
  • 190
  • 1
  • 11
0

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);
  • Downvoters, kindly leave your comments below, this will help me to improve my post. –  Mar 10 '17 at 01:49