JCHASE11
JCHASE11

Reputation: 3941

Changing a links href after click with jQuery

I am trying to create a link that when clicked on, switches its href attribute, and then goes to that location.

My html is:

<a href="http://google.com" rel="group" data-wpurl="http://yahoo.com"></a>

When clicked, I would like the browser to go to the data-wpurl location, not href location. The reason I am using a data attribute is because of the application I am using requires use of the href...not relevant here.

My jQuery is:

$('a[rel="group"]').on('click', function(e) {
      e.preventDefault();
      var wpurl = $(this).attr("data-wpurl");
      $(this).attr('href', wpurl);
});

I am using e.preventDefault(); to prevent the browser from taking the user to the href. After the data attribute is assigned to the href, how do I then trigger a click? Using trigger('click') and click(); do not work!

Any ideas?

Upvotes: 24

Views: 55371

Answers (5)

sanjeev
sanjeev

Reputation: 1

To replace parts of a string, used replace() method .

jQuery(".mylink").on('click', function() {
  var url =  jQuery(this).attr('href')
  url = url.replace('us-test', 'replaced-text')
  jQuery(this).attr('href', url) 
 });

Upvotes: 0

Gerwald
Gerwald

Reputation: 1589

Similar solution, but without the need of calling e.preventDefault()

$('a[rel="group"]').on('click', function(e) {
    e.originalEvent.currentTarget.href = $(this).data('wpurl');
});

from my point of view, this is a more general, cleaner solution, as this will not change the default browser behaviour (e.g.: when the user clicks with the mouse wheel on the link, with Jacks solution no new tab will be opened)

Upvotes: 36

Ross Angus
Ross Angus

Reputation: 1078

I think your original jQuery is fine, except for the e.preventDefault(): this will stop the event firing, no matter what you do to the href attribute after that point.

$('a[rel="group"]').on('click', function(e) {
      var wpurl = $(this).attr("data-wpurl");
      $(this).attr('href', wpurl);
});

All of the above code will execute before the page refreshes.

Upvotes: 6

Dan
Dan

Reputation: 614

Use onmousedown. Google uses this method on their search results page so they can track what you clicked. If you want to see where the link will go, right click instead of left. They both trigger the onmousedown event.

http://jsfiddle.net/afLE3/

<a href="http://google.com" data-wpurl="http://yahoo.com" onmousedown="rwt(this)">CLICK HERE</a>

<script type="text/javascript">
  rwt = function(e){
    e.href = $(e).data('wpurl');
  }
</script>

Upvotes: 10

Ja͢ck
Ja͢ck

Reputation: 173662

It would be easier to just change the location immediately:

e.preventDefault();
location.href = $(this).data('wpurl');

Upvotes: 21

Related Questions