2

I want to call my custom function (or simply execute certain logic) whenever user clicks on any a that does not open in a new window and has href attribute which is not empty and does not start with # and does not have javascript:.

Basically I need all those links that, if clicked will lead to the current page be unloaded. But all other links like #point1 or javascript:alert('');, etc. should be excluded (because if clicked the user will still remain on the page). What is the proper jQuery for that?

Ideally should be compatible with older jQuery - version 1.7.2

Fit Dev
  • 3,223
  • 3
  • 25
  • 49

3 Answers3

3

Try this:

$(document).on('click', 'a[href][href!=""]:not([href^="#"],[href^="javascript:"],[target="_blank"])', function() {
    // do something
})

But, you have to consider that it's not a very readable code to maintain. Passing a filter function (like in @Rory McCrossan answer) can be more readable.

See Fiddle

P.S Have you considered using the beforeunload event instead?

haim770
  • 47,051
  • 7
  • 96
  • 126
2

As that's quite a complex set of rules you could use a filter():

$('a').filter(function() {
    var href = $(this).attr('href');
    return href != '' && href != '#someanchor' && this.target != '_blank';
}).click(function() {
    // do your thing here...
});
Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
  • A single delegated handler, no matter how complex the jQuery selector, will always perform better than loads of individual click handlers. – Gone Coding Oct 29 '15 at 17:19
  • I agree, although @haim770 laid claim to that answer :) – Rory McCrossan Oct 29 '15 at 17:20
  • @RoryMcCrossan, +1 But, any reason you insist on `attr('href')` instead of `this.href`? – haim770 Oct 29 '15 at 17:22
  • @Haim770 thanks for the edit, however I specifically used the `href` via `attr()` as it gives you the attribute value from the DOM. Using `this.href` means that the URL is made absolute which can lead to differences. Example: http://jsfiddle.net/zcgrpdum/ – Rory McCrossan Oct 29 '15 at 17:22
  • @RoryMcCrossan, I see – haim770 Oct 29 '15 at 17:24
0

You could use jQuery's .not() method. See: http://api.jquery.com/not/

$('a')
   .not('[target=_blank]')
   .not('[href=""]')
   .not('[href=#someanchor]')
   .on('click', function() {
      //code here
   });
alvarodms
  • 601
  • 5
  • 8