Elnaz Elnaz - 11 days ago 5
HTML Question

Show loading on clicking on a link, except for ctrl+click

I want to show a

<div>
that contains loading, using a tag-helper. I want to show the loading anywhere I have a
<a>
tag, except for
href='#'
. (I don't have any ajax call, so I will see a new rendered page after clicking the link)

$('a:Not([class="NeedsConfirmation"])').click(function () {
var currentURL = window.location.href;
var element = $(this);
if ((element.attr("href") != "#") && (element.attr("href") != currentURL))
{
showLoading(element);
}
});


Now, I want to add additional exception: currently, If user presses the ctrl and then click the link, the new page will be shown but the previews page will show loading.

How can I discard calling
showLoading(element);
in this case? (I have no problem with right-click and 'open in new tab' or window)

Answer

You can use the event-object passed into .click. It has a property called ctrlKey. Check it and then do the stuff you want.

$('a:not([class="NeedsConfirmation"])').click(function (e) {
  e.preventDefault();
  // Check if ctrl was pressed...
  if(e.ctrlKey) {
    // Ctrl was pressed during click
    alert('ctrl click');
    // Do something else.
  }
  else {
    // Ctrl was not pressed during click
    alert('not ctrl click');
    var currentURL = window.location.href;
    var element = $(this);
    if ((element.attr("href") != "#") && (element.attr("href") != currentURL))
    {
      showLoading(element);
    }
  }
});

showLoading = function(element){
  element.text('loading...');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">click me!</a>
<a href="www.stackoverflow.com">click me with link!</a>