Insert current URL into a link using JS and HTML

Darkseven picture Darkseven · Dec 8, 2015 · Viewed 12.5k times · Source

So, Ive read through similar things but I still can't find an answer that applies more closely to what I'm doing. I am attempting to use JS to get the current page URL and append it to a social media sharing link like this:

<a href="http://reddit.com/submit?url=CURRENTPAGE.html; title="This is a post!" target="_blank">

Using Javascript, I've managed to assign the current URL to a variable:

<script>
var x = window.location.href;
document.getElementById("smsharing").innerHTML = x;
</script></p>

And I made sure it worked by doing a test display of it. So what exactly is the proper method/syntax for actually putting 'x' in place of CURRENTPAGE.html???

I know this is a STUPID question, but I'm really stumped. Specifics help, because part of the problem is that I have precious little knowledge of JS. Thoughts?

Answer

Victory picture Victory · Dec 8, 2015

Get the elements current href which doesn't have the url value and append the current url.

Modified HTML

<a id='smsharing' 
   href="http://reddit.com/submit?url="
   title="This is a post!"
   target="_blank">link</a>

Script

<script>
var x = window.location.href;
var link = document.getElementById("smsharing"); // store the element
var curHref = link.getAttribute('href'); // get its current href value
link.setAttribute('href', curHref + x);
</script>