bart2puck
bart2puck

Reputation: 2522

How can i make a link do some jquery then go to destination

I have a link in a page that I need to do some jquery on before I go to the destination page. Im sure there are dozens of ways to do this, what is most recommended?

$('#link').click(function(){
alert('you clicked'); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a href='google.com' id='link'>Google</a>

obviously fails. thoughts?

Upvotes: 0

Views: 483

Answers (4)

Jonast92
Jonast92

Reputation: 4967

Do the following:

  • Disable the default behavior by using event.preventDefault.
  • Do what you wish to do.
  • Redirect.

Something like this:

$('#link').on('click', function(event)
{
    event.preventDefault(); 
    // Do something
    // ...
    var url = $(this).attr('href');
    location.location.href = url;
});

Upvotes: 1

Scimonster
Scimonster

Reputation: 33409

$('#link').click(function(e){
    e.preventDefault();
    alert('you clicked'); 
    window.location.href = $(this).attr('href');
});

Set the location after doing whatever you want to do.

Upvotes: 1

roryok
roryok

Reputation: 9645

This should work.

$('#link').click(function(e){
    e.preventDefault(); // this stops the url from being loaded
    // do whatever js you want to here
    alert('you clicked'); 
    // then send the user on their way
    window.location.href = $(this).attr('href');
});

Upvotes: 1

atmd
atmd

Reputation: 7490

To change the url there is no need for jquery

  document.getElementById('link').href = 'new url here'

However if you want to do something onClick first, you'll need to prevent the default action

$('#link').click(function(e){
    e.preventDefault():
    // do what ever you need here
    window.location.href = 'new url here';
});

Upvotes: 0

Related Questions