Reputation: 41
So far I have done
jQuery:
function addURL(element)
{
var baseZipCode = 48180;
$(element).attr('href', function() {
return this.href + baseZipCode;
});
}
html:
<a onclick="addURL(this)" href="http://www.weather.com/weather/today/" target="_blank">Click this</a>
My problem is when user clicks on link and the new window open everything is ok, but when the user clicks on the link again without a refresh, the variable is added twice to the link.
For example:
First time: http://www.weather.com/weather/today/48180
Second time: http://www.weather.com/weather/today/4818048180
It doesn't act right until you do a page refresh, any help would be appreciated. Thanks in advance
Upvotes: 1
Views: 1963
Reputation: 10407
You can try it with jQuery.fn.one
Javascript:
jQuery("a").one("click", function(){ // Set a handler that execute once
var baseZipCode = 48180;
this.href += baseZipCode; //same as "this.href = this.href + baseZipCode"
});
HTML:
<a href="http://www.weather.com/weather/today/" target="_blank">Click this</a>
Maybe you will need to add some class to <a> tags to differ it from another ones
Upvotes: 1
Reputation: 196236
Replace your addURL
function with
function addURL(element)
{
var baseZipCode = '48180';
if (element.href.slice(-baseZipCode.length) !== baseZipCode){
element.href += baseZipCode;
}
}
there is no jQuery involved..
Upvotes: 1
Reputation: 4561
return this.href.indexOf(baseZipCode) != -1 ? this.href : this.href + baseZipCode;
Upvotes: 0
Reputation: 22261
This should be:
function addURL(element)
{
var baseZipCode = 48180;
element.href = (element.href + baseZipCode)
.replace(baseZipCode + baseZipCode, baseZipCode);
}
Upvotes: 0