Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a links href after click with jQuery

Tags:

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?

like image 649
JCHASE11 Avatar asked May 07 '13 17:05

JCHASE11


People also ask

What will href =# do?

Scroll to Top: href="#" doesn't specify an id name, but does have a corresponding location - the top of the page. Clicking an anchor with href="#" will move the scroll position to the top.

Can we use value attribute in anchor tag?

To do that, you can use the ping attribute of the anchor tag. A ping attribute accepts one or more URLs as values.

What is link href in JavaScript?

In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).


1 Answers

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)

like image 135
Gerwald Avatar answered Oct 16 '22 11:10

Gerwald