Sorry, if this is a stupid question, I'm new to JavaScript. I'm trying to create links which will automatically update according to the page you're on. It worked fine when I just had one of them, but apparently, the first link also gives me the same output as the first one. Here's what I'm trying to achieve:
<html>
<head>
<!-- QR API generator call -->
<script>
baseurl="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data="
function buildQR(item)
{
item.href=baseurl+window.location.href;
return true;
}
</script>
<!-- Sharing append link via JavaScript -->
<script>
baseurl="whatsapp://send?text="
function buildURL(item)
{
item.href=baseurl+window.location.href;
return true;
}
</script>
</head>
<body>
<a onclick="return buildQR(this)" href="">Generate QR</a>
<a onclick="return buildURL(this)" href="" data-action="share/whatsapp/share">Share on WhatsApp</a>
</body>
</html>
Thanks for helping me out.
P.S. I'm trying to achieve this, but with two links this time.
1 Answer 1
The problem is due to the scope of the baseurl variable. It's being declared as a global variable, which means in your first script tag it gets set with the initial value, then in the second script tag it gets set to a new value. Both of those scripts are executed when the page loads, so it's pretty much immediately setting baseurl equal to the second value.
I would recommend reading more about variable scoping (https://developer.mozilla.org/en-US/docs/Glossary/Scope) and closures (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) to better understand the issue.
To fix it, you can either use a different variable name for the second instance of baseurl (something like baseurl1, maybe), or move the variable declarations inside the function declarations to wrap them inside those closures.
Something like this should work:
<!-- QR API generator call -->
<script>
function buildQR(item) {
var baseurl="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=";
item.href=baseurl+window.location.href;
return true;
}
</script>
<!-- Sharing append link via JavaScript -->
<script>
function buildURL(item) {
var baseurl="whatsapp://send?text=";
item.href=baseurl+window.location.href;
return true;
}
</script>
onclick, get your elements and thenaddEventListenerwhatever it needs - also, unless it's a true link, don't use<a>, use<button>because that's what it is, and then use CSS to style that however it needs to look. Also, say what kind of variable you're using.var?let?const? etc.<!doctype html>at the top to indicate this is true HTML5, you're missing a charset meta and a title, all that JS should be in its own file so you can load it with<script src="..." defer></script>, etc. -- it just looks like the kind of HTML/JS that highly outdated tutorials/books would teach you to use.