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:
JavaScript
x
62
62
1
<!DOCTYPE html>
2
3
<html>
4
<head>
5
<title>Wanna See A Picture?</title>
6
</head>
7
<body>
8
<div class="container">
9
<form action"/setup" method="post" id="setup">
10
<h1>Enter your random image size</h1>
11
<p>Enter an image width and height by entering a number between 200 and 1200 in each field.</p>
12
<p>Click "Get Your Pic!" when ready.</p>
13
<div class="field">
14
<label for="width">Enter a width:</label>
15
<input type="number" id="width" name="width" />
16
</div>
17
18
<div class="field">
19
<label for="height">Enter a height:</label>
20
<input type="number" id="height" name="height" />
21
</div>
22
23
<div class="field">
24
<button type="submit">Get Your Pic!</button>
25
</div>
26
27
</form>
28
</div>
29
30
<div id="imgOutput"></div>
31
32
<script>
33
const SUBMITBTN = document.getElementById('submit');
34
35
let source = "";
36
37
SUBMITBTN.onclick = function(){
38
let imgWidth = document.getElementById('width');
39
let imgHeight = document.getElementById('height');
40
let source = `https://picsum.photos/${imgWidth}/${imgHeight}/?random`; //for grayscale add ?grayscale at end of url
41
}
42
43
44
let img = null;
45
let imgPromise = new Promise(function(resolve, reject){
46
img = new Image();
47
img.addEventListener('load', resolve(img));
48
img.addEventListener('error', reject('Could not load image'));
49
img.src = source;
50
});
51
52
imgPromise.then(function(fromResolve){
53
let node = document.getElementById('imgOutput');
54
node.appendChild(img);
55
}).catch(function(fromReject){
56
document.getElementById('imgOutput').innerHTML = fromReject
57
});
58
59
</script>
60
</body>
61
</html>
62
Advertisement
Answer
JavaScript
1
2
1
const SUBMITBTN = document.getElementById('submit')
2
Null was returned because you used getElementById
and there are no ID assigned to the button. Try:
JavaScript
1
2
1
<button id="submit" type="submit">Get Your Pic!</button>
2
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.