24

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?

JCHASE11
  • 3,901
  • 19
  • 69
  • 132
  • It can be done but just curious about the use-case... – Ejaz May 07 '13 at 17:41
  • I need the href for everything but mobile...So within my js, I am using a conditional. I want the link to trigger different urls based on screen size. – JCHASE11 May 07 '13 at 17:43

4 Answers4

35

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)

Gerwald
  • 1,549
  • 2
  • 18
  • 42
21

It would be easier to just change the location immediately:

e.preventDefault();
location.href = $(this).data('wpurl');
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 1
    this. if you're going to take the user to a new page, there's no reason to actually update the href of the link. – user428517 May 07 '13 at 17:44
10

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>
Dan
  • 593
  • 8
  • 16
6

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.

Ross Angus
  • 1,070
  • 8
  • 6