To avoid duplicating web pages, I am looking for a way to change the link in a button according to the relative link of the page.
Let's imagine that we are on the site https://mywebsite.com/ and we want to send users to https://othersite.com/ (These websites are given as examples
Here is what I would like to do:
- If the current link is https://mywebsite.com/ then the button should offer this link https//othersite.com/
- If the current link is https://mywebsite.com/?utm_source=facebook then the same button must propose this link https://othersite.com/?value=facebook
- If the current link is https://mywebsite.com/?utm_source=twitter then the same button must propose this link https://othersite.com/?value=twitter
- etc
In short, I'm looking for a way to vary the link of a button in an href attribute depending on the current link of the page.
I'm just starting in javascript. I'm far from understanding all the subtleties of this language.
Here is what I tried but it (obviously) doesn't work:
<html>
<head></head>
<body>
<a href="javascript:location.assign" >Click here</a>
<script>
if (location.pathname === "/") {
location.assign("https//othersite.com/");
}
if (location.pathname === "/?utm_source=facebook") {
location.assign("https://othersite.com/?value=facebook");
}
if (location.pathname === "/?utm_source=twitter") {
location.assign("https://othersite.com/?value=twitter");
}
</script>
</body>
</html>
Here are also resources that I think are useful but I can't apply to my problem:
- Change href based on condition of URL on current page
- How to change href of <a> tag on button click through javascript
- Change part of link with part of current URL
Thanks for your help and your time!