Eren
Eren

Reputation: 183

Prevent navigation and get the target link

I want to make my website faster by changing the content code via Ajax instead of navigating and reloading the page. But I also care about non-Javascript users so I want to use normal links instead of onclick event. And I want to prevent navigating and getting the target href link to change the content.

Is there a way to achieve that with Javascript/jQuery? Apparently jQuery supports event.preventDefault(); but I don't think it gives you an ability to get target link from that event...

Upvotes: 3

Views: 2750

Answers (2)

uladzimir
uladzimir

Reputation: 5689

This can be done in JavaScript (without using jQuery)

To catch all the clicks in document you can use

document.body.addEventListener('click', function(e) {
  e.preventDefault()
  const href = e.target.href
})

also you should add additional check that clicked element is exactly a link with href:

e.target.tagName.toLowerCase() === 'a'

So an example of working code:

document.body.addEventListener('click', function(e) {
  if (e.target.tagName.toLowerCase() === 'a') {
    e.preventDefault()
    const href = e.target.href
  } 
})

With this function you will be able to catch all the clicks, check, if user clicked on a and get href attribute with just plain javascript. http://youmightnotneedjquery.com

Update Based on @AVAVT comment if you need to handle case with something nested inside a, like

<a href="https://google.com"> 
  <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a"> 
</a>

just use e.target.closest('a')

document.body.addEventListener('click', function(e) {
  if (e.target.closest('a')) {
    e.preventDefault()
    const href = e.target.closest('a').href
  } 
})

because target property will lead to exactly clicked item (in this case img) we need to check is it a child of a and then prevent default behavior.

Note:

jQuery solution is simple, so it's preferred, if you already have jQuery on the page.

Otherwise you can go without it with plain javascript.

Upvotes: 3

AVAVT
AVAVT

Reputation: 7133

I think jQuery's .attr() can help you:

$('body').on('click', 'a', function(e){
  e.preventDefault();
  doSomethingWith($(this).attr('href'));
});

Upvotes: 3

Related Questions