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,413
  • 3
  • 30
  • 54

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
  • 48,394
  • 7
  • 105
  • 133
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
  • 331,213
  • 40
  • 305
  • 339
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
  • 671
  • 5
  • 8