Reputation: 23
I've got a site which includes jQuery-Tabs, so I have a hashtag in my url to get a desired tab displayed:
www.abc.de/site#tab4
On this site I have a link which looks like this:
<a href="/site.html?option=1" name="optionslink" id="optionslink" onclick="javascript:test()">LINKTEXT</a>
With this link the user can choose an option for a product. The site gets reloaded on click. I want to achieve that on click the string after the hashtag in the url is read out and then this string will be added to the url or the link...
My function looks like this:
function test() {
var info=window.location.hash;
alert(info);
document.getElementById("optionslink").href+info;
return true;
}
So far the function is on click I get an alert-popup which shows the correct hashtag and it's string. But the site gets reloaded without having the hashtag+string added. It looks like this:
www.abc.de/site.html?option=1
It should look like:
www.abc.de/site.html?option=1#tab4
How can I get this working?
Upvotes: 2
Views: 1152
Reputation: 150253
Simply change the location:
function test() {
var info=window.location.hash;
window.location = document.getElementById("optionslink").href + info;
return false;
}
<a href="/site.html?option=1" name="optionslink" id="optionslink" onclick="return test();">LINKTEXT</a>
Another thing, you pass the current anchor to the function, and save the DOM query overhead:
function test(anchor) {
var info=window.location.hash;
window.location = anchor.href + info;
return false;
}
<a href="/site.html?option=1" name="optionslink"
id="optionslink" onclick="return test(this);">LINKTEXT</a>
Note that not using inline scripts
at all is the best practice with javascript events.
You should read about addEventListener
, you can read about it in MDN
Upvotes: 2
Reputation: 74036
You are not changing the href attribute. Try
document.getElementById("optionslink").href += info;
Your code document.getElementById("optionslink").href+info;
just has no effect, as there is just the concatination, but no assignment to the href attribute.
Upvotes: 3