Skip to content Skip to sidebar Skip to footer

Separating Code For Qrcode Image Generator Javascript/html

When I tested the code only on HTML it worked just fine, but when I separate it doesn't show -surprise - here's my code:

Solution 1:

Your problem could simply be that you've forgotten the id attribute within this line of your HTML<img = 'qrcode' />

Try changing that to this: <img id='qrcode' src=''>

However, if after trying... the problem at hand still persists then I'd recommend you to try the examples below.

Change your HTML markup to this:

<body><imgid='qrcode'src=''><buttonid="Btn">Gerar QRcode</button><scripttype="text/javascript"src="script.js"></script></body>

Within your javascript file simply implement this:

document.getElementById("Btn").addEventListener("click", function(){
    var x = (Math.random() * 99999999999999999);
    document.getElementById('qrcode').src ="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + x;
});

or this version of javascript if you prefer:

document.getElementById("Btn").addEventListener("click", newQR);

functionnewQR() {
   var x = (Math.random() * 99999999999999999);
   document.getElementById('qrcode').src ="https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + x;
}

Solution 2:

What you are missing right now is the order of reference js files which must be placed in-order. The first js file you need to attach is the QR js file and then, your own script.

By the way, it is always recommended to have your your js files appended at the body tag. By the way, here is another tip that you should be knowing that you need to ensure that all dom elements have been loaded by simply putting your js methods in a simple block:

(function() {
 // You are ensuring that the page is loaded completely.newQR();
})();

Here is the sample HTML code:

//// my myownsrc.jsfunctionnewQR() {
    var x = Math.floor((Math.random() * 99) + 1);
    document.getElementById('qrcode').src = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" + x
  }
   (function() {
   // You are ensuring that the page is loaded completely.newQR();

})();
<!DOCTYPE html><html><body><imgid='qrcode'src=''><buttononclick="newQR()">Gerar QRcode</button><scriptsrc="qrimage.js"></script><scriptsrc="myownsrc.js"></script></body></html>

Post a Comment for "Separating Code For Qrcode Image Generator Javascript/html"