Paste the current URL into the link using JS and HTML

So, I read similar things, but I still can’t find an answer that is more closely related to what I am doing. I am trying to use JS to get the current page URL and add it to the link for sharing social networks, for example:

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

Using Javascript, I was able 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 that it worked by checking it. So what exactly is the correct method / syntax for actually placing "x" instead of CURRENTPAGE.html ???

I know this is a STUPID question, but I'm really at a dead end. Specific help, because part of the problem is that I have very little knowledge about JS. Thoughts?

+5
source share
7 answers

This should do it:

 <script> baseurl="http://www.facebook.com?" function buildURL(item) { item.href=baseurl+window.location.href; return true; } </script> </head> <body> <a onclick="return buildURL(this)" href="">Google</a> </body> 
+1
source

Using only pure JavaScript, you can set href links just by having the base href as a string, and then add the variable where you need it.

 var x = window.location.href; document.getElementById("linkid").href = "http://reddit.com/submit?url="+encodeURIComponent(x); 
+2
source

Get the current href elements that have no url value and add 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> 
+1
source

Using jQuery is as simple as:

 $('a').attr("href",x); 
0
source

You should just replace innerHTML with href :

 document.getElementById("smsharing").href = x; 

Hope this helps.

0
source

Once you have access to the current URL, you want to find this element and replace CURRENTPAGE.html. To do this, you will need to somehow select the item. Let him give him an ID:

 <a id="myLink" href="http://reddit.com/submit?url=CURRENTPAGE.html"></a> 

Now we can capture the link like this:

 var link = document.getElement('myLink'); 

Return the URL again and give it the best variable name:

 var url = window.location.href; 

Now update the HREF link attribute:

 link.href = link.href.replace('CURRENTPAGE.html', url); 

What is it!

0
source

Create another variable for the full href attribute of your link:

var myURL = "http://reddit.com/submit?url=" + x;

Then replace the current href attribute with this variable:

docment.getElementById("YourLinkTagID").href = myURL

0
source

Source: https://habr.com/ru/post/1237615/


All Articles