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
  • 32,893
  • 9
  • 77
  • 89
bart2puck
  • 2,432
  • 3
  • 27
  • 53

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
  • 9,325
  • 17
  • 71
  • 138
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
  • 32,893
  • 9
  • 77
  • 89
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,964
  • 1
  • 18
  • 32
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,430
  • 2
  • 33
  • 64