I’m working on an assignment that asks us to use Promise, and when I run the script, I am getting this error on line 37:
Uncaught TypeError: Cannot set property ‘onclick’ of null
I can’t understand why the onclick is throwing this error, because I have used buttons before with similar functionality, and never had an issue. Code is below:
<!DOCTYPE html> <html> <head> <title>Wanna See A Picture?</title> </head> <body> <div class="container"> <form action"/setup" method="post" id="setup"> <h1>Enter your random image size</h1> <p>Enter an image width and height by entering a number between 200 and 1200 in each field.</p> <p>Click "Get Your Pic!" when ready.</p> <div class="field"> <label for="width">Enter a width:</label> <input type="number" id="width" name="width" /> </div> <div class="field"> <label for="height">Enter a height:</label> <input type="number" id="height" name="height" /> </div> <div class="field"> <button type="submit">Get Your Pic!</button> </div> </form> </div> <div id="imgOutput"></div> <script> const SUBMITBTN = document.getElementById('submit'); let source = ""; SUBMITBTN.onclick = function(){ let imgWidth = document.getElementById('width'); let imgHeight = document.getElementById('height'); let source = `https://picsum.photos/${imgWidth}/${imgHeight}/?random`; //for grayscale add ?grayscale at end of url } let img = null; let imgPromise = new Promise(function(resolve, reject){ img = new Image(); img.addEventListener('load', resolve(img)); img.addEventListener('error', reject('Could not load image')); img.src = source; }); imgPromise.then(function(fromResolve){ let node = document.getElementById('imgOutput'); node.appendChild(img); }).catch(function(fromReject){ document.getElementById('imgOutput').innerHTML = fromReject }); </script> </body> </html>
Advertisement
Answer
const SUBMITBTN = document.getElementById('submit')
Null was returned because you used getElementById
and there are no ID assigned to the button. Try:
<button id="submit" type="submit">Get Your Pic!</button>
Note:
Hard-assigning id to the button may not be ideal if there are multiple submit buttons. Potentially look for a more descriptive name and find a query-selector that suits your needs.