Reputation: 27
I have looked and looked for an answer to this question. So I apologize in advance when the solution is very easy.
I want to take the url of the current page eg. www.example.com/example.html and put this in a link (among other uses) using javascript.
so it would look like this:
<a href"www.example.com/example.html"></a>
I've tried lots of things I know I need to use location.href but just can't seem to get it to work.
This is the closest I got to getting it to work,:
<a href"javascript:write.location.href;"></a>
Thanks, sorry again. I'm new to JS and html.
J
Upvotes: 1
Views: 651
Reputation: 7181
Name your element with an ID, like: <a id="pageLink"></a>
and then when the document loads you can run this snippet:
var link = document.getElementById("pageLink");
link.setAttribute("href", window.location.href);
Or, with something like jQuery:
$("#pageLink").attr("href", window.location.href);
EDIT In response to your question in the comments:
I'm not sure I'm understanding you completely but if it's fixed, then you'd simply concatenate to the href before setting it, e.g.
$("#pageLink").attr("href", staticUrl + window.location.href);
Upvotes: 1
Reputation: 2991
<script>
function gotolink(){
location.href = location.href;
}
</script>
<a href"#" onclick="gotolink();">Click here!</a>
Upvotes: 0
Reputation: 11895
you can use document.location.href
to find the address of the current page
<a id="cool-link">click it!</a>
<script>
jQuery('#cool-link').attr('href', document.location.href)
</script>
Upvotes: 0
Reputation: 66498
You can use this
in href (it's global object) but you can in onclick.
<a onclick="this.setAttribute('href', location);this.setAttribute('onclick', '');">foo</a>
It clear onclick so you get this only once so you can follow the link if you click it again.
Upvotes: 0
Reputation: 513
You can give this a try:
<a href="" onclick="window.location.href=document.URL">same url link</a>
you can keep the href empty and just use the onclick event.
Hope this helps.
Upvotes: 0
Reputation: 7507
I think you have to use window.location.href
. I'm no JS expert, so let me know if it worked.
Upvotes: 0