0

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?

Scimonster
  • 31,931
  • 8
  • 74
  • 86
bart2puck
  • 2,224
  • 3
  • 24
  • 48

4 Answers4

1

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');
});
roryok
  • 8,965
  • 16
  • 67
  • 134
1
$('#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.

Scimonster
  • 31,931
  • 8
  • 74
  • 86
1

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;
});
Jonast92
  • 4,891
  • 1
  • 15
  • 30
0

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';
});
atmd
  • 7,260
  • 2
  • 31
  • 63