Image is loading as null - javascript

I am new to javascript but I am trying to have the default image set with the onload() and I don't think that it is reaching the image that I set up in the array and I cannot figure out why.
I am going to have it rotate images after I click on the button but I can't even get the default image to add.
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=1;
function loadPage()
{
document.getElementById("pictures").src = images[0].src;
}
function nextImage(pictures)
{
var img = document.getElementById("pictures");
document.getElementById("pictures").src = images[1].src;
console.log(num++); // I have this just to make sure that it is catching something
}
<div id="maincontent">
<div id="pictures">
<img src="img/mountain.jpg">
</div>
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>

You just need to have your id="pictures" on the image tag, not the div.
Like this:
<img id="pictures" src="img/mountain.jpg">
Also leave off the .src in loadPage() and nextImage()
document.getElementById("pictures").src = images[1];

Here images is an javascript array. So you cannot use .src as it is not an HTML img element
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=1;
//This function will run on body onload
function loadPage()
{
document.getElementById("pictures").src = images[0];
}
//This function will run on button click
function nextImage()
{
var img = document.getElementById("pictures");
document.getElementById("pictures").src = images[1];
console.log(num++); // I have this just to make sure that it is catching something
}
<body onload="loadPage()">
<div id="maincontent">
<img id="pictures" src="img/mountain.jpg">
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>
</body>

I have updated your code please check.
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=0;
loadPage();
function loadPage()
{
console.log(num);
document.getElementById("picture").src = images[num];
num++;
}
function nextImage(pictures)
{
if(typeof images[num] === 'undefined') {
// does not exist
num = 0;
}
console.log(num);
document.getElementById("picture").src = images[num];
num++;
}
<div id="maincontent">
<div id="pictures">
<img src="img/mountain.jpg" id="picture">
</div>
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>

Try this one:
<script>
var images = ['img/profile.jpg', 'img/mountain.jpg', 'img/sanfran.jpg'];
var num=0;
function loadPage()
{
document.getElementById("pictures").src = images[0].src;
}
function nextImage(pictures)
{
if(num<images.length-1) {
num = num+1;
} else {
num = 0;
}
var img = document.getElementById("pictures");
document.getElementById("pictures").src = images[num];
console.log(num); // I have this just to make sure that it is catching something
}
</script>
<div onload="loadPage()">
<div id="imageholder">
<img id="pictures" src="img/mountain.jpg">
</div>
<div id="paragraph">
<p>
</p>
<button onclick="nextImage()">Switch Images</button>
</div>
</div>

Related

Random image from html on button click

I am trying to make a script that will take the images from one div element and put it to div rndmImage randomly on button click, I should see images when document is loaded, but the new div where images should go after click must be empty until click heapends. And I need only JavaScript, no jQuery, alse i can not change the html, and it has to work for any number of images. So if you have some ideas that would be great. Here's my code.
window.addEventListener('load', start, false);
function start() {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('ekran');
var pictures = document.getElementsByTagName('img');
var choose = Math.floor(Math.random()*pictures.length);
butt.addEventListener('click', menjaj, false);
function menjaj(e) {
var new = e.button;
var img = [];
for(var i = 0; i< pictures.length; i++) {
var dodaj = img[i];
img.push(dodaj);
}
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
<body>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
</body>
This is a working snippet of your code:
window.addEventListener('load', start, false);
function start () {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('rndmImage')[0]; //Change selector to existing class and select the first (the only) one
var pictures = document.getElementsByTagName('img');
butt.addEventListener('click', menjaj, false);
function menjaj (e) {
// var new = e.button;// 'new' is reserved word in JS, you can't use it as variable name
// var btn = e.button;// but this line is useless
var choose = Math.floor(Math.random() * pictures.length); //better move this line inside this function to get rundom image every button clicks
var img = document.createElement('img'); //creates new img tag
img.src = pictures[choose].src;
rnImg.innerHTML = ''; //to delete previous image
rnImg.appendChild(img);
// var img = []; //useless lines of code
// for(var i = 0; i< pictures.length; i++) {
// var dodaj = img[i];
// img.push(dodaj);
// }
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
welcome to StackOverflow!
I would first hide the .wrapper > div img as that will prevent the images to show, then, append a data-pos to help select the position and simply randomize them and pick the src to show on the placeholder
and remember that you have a <div> as placeholder, so you can't assign src, only if you change it to <img>
so, something like this 😊
function chooseImg() {
// get total images available
var totalImages = document.querySelectorAll('.wrapper > div img').length
log('totalImages', totalImages)
// get a random position
var rndPosition = Math.floor(Math.random() * totalImages)
log('rndPosition', rndPosition)
// get hold of the image for such position
var rndImage = document.querySelector('.wrapper > div img[data-pos="' + rndPosition + '"]')
log('rndImage', rndImage)
// assign the source to the DIV
document.querySelector('.rndmImage').style = 'background-image: url("' + rndImage.src + '")'
}
function log(txt, obj) {
console.log(txt, obj)
}
.wrapper > div img {
display: none;
}
.rndmImage {
background-size: contain;
background-repeat: no-repeat;
width: 100px;
height: 100px;
}
<div class="wrapper">
<div>
<img data-pos="0" src="https://randomwordgenerator.com/img/picture-generator/54e5d2434953a514f1dc8460962e33791c3ad6e04e507440742f7cd09645cc_640.jpg" alt="leto1">
<img data-pos="1" src="https://randomwordgenerator.com/img/picture-generator/54e2d1404a57a814f1dc8460962e33791c3ad6e04e5074417c2d78d19f44c4_640.jpg" alt="leto2">
<img data-pos="2" src="https://randomwordgenerator.com/img/picture-generator/57e2d5444851a414f1dc8460962e33791c3ad6e04e50744172287ad2914fc4_640.jpg" alt="leto3">
<img data-pos="3" src="https://randomwordgenerator.com/img/picture-generator/51e8d0444f56b10ff3d8992cc12c30771037dbf85254794e722c73d19245_640.jpg" alt="leto4">
<img data-pos="4" src="https://randomwordgenerator.com/img/picture-generator/53e4d2464a56a914f1dc8460962e33791c3ad6e04e507440722d7cd39345c1_640.jpg" alt="leto5">
<img data-pos="5" src="https://randomwordgenerator.com/img/picture-generator/57e9dc434b5ba414f1dc8460962e33791c3ad6e04e50744172297bd5934cc4_640.jpg" alt="leto6">
<img data-pos="6" src="https://randomwordgenerator.com/img/picture-generator/55e1dc4b4254ad14f1dc8460962e33791c3ad6e04e507440722d72d09249c7_640.jpg" alt="leto7">
<img data-pos="7" src="https://randomwordgenerator.com/img/picture-generator/57e9d4474e54a814f1dc8460962e33791c3ad6e04e50744172297cdd974cc0_640.jpg" alt="leto8">
<img data-pos="8" src="https://randomwordgenerator.com/img/picture-generator/53e6dc404951b10ff3d8992cc12c30771037dbf852547848702e7ed19348_640.jpg" alt="leto9">
</div>
<div>
<button type="button" onclick="chooseImg()">choose</button>
</div>
<div class="rndmImage"></div>
</div>
<div class="wrapper">
<img src="../Assets1/Image/1.svg" alt="" />
<img src="../Assets1/Image/2.svg" alt="" />
<img src="../Assets1/Image/3.svg" alt="" />
</div>
<button>Click</button>
<div class="randomImageContainer"></div>
const button = document.querySelector('button');
button.addEventListener('click', randomImage);
function randomImage() {
const image = document.querySelectorAll('.wrapper > img');
const randomImageContainer = document.querySelector('.randomImageContainer');
let randomNumber = Math.floor(Math.random() * image.length);
const img = document.createElement('img');
img.src = image[randomNumber].src;
randomImageContainer.appendChild(img);
}
You can do this with plain javascript like this:
document.querySelector("button").addEventListener("click", () => {
var imgElements = document.querySelectorAll(".wrapper img");
document.querySelector(".rndmImage").innerHTML = imgElements[Math.floor(Math.random() * imgElements.length)].outerHTML;
});
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
If you're able to use randojs, you can even simplify the randomness and make it all cryptographically secure like this:
document.querySelector("button").addEventListener("click", () => document.querySelector(".rndmImage").innerHTML = rando(document.querySelectorAll(".wrapper img")).value.outerHTML);
<script src="https://randojs.com/2.0.0.js"></script>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
Try this:
this is my image in HTML file
<snap id="image" class="btn btn-warning" onclick="changeImage()">Image</snap>
<image id="imagechange" src="https://picsum.photos/200/300" ></image>
my javascript file
imgcount = 0;
function changeImage() {
document.getElementById("imagechange").src =
"https://picsum.photos/200/" + (300 + imgcount);
imgcount++;
}
everytime you click button you get a new image

Swap innerHTML for specific time

I was trying to change the innerHTML of a div and retrieving it again after a certain amount of time.
For that I have implemented sleep(miliseconds) function and used jQuery built-in function as below snippet. The strange thing is that, the code works well in Chrome's debugging mode.
Edited:
I edited the snippet just to show using setTimeout()
is not satisfactory in my special case.
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>");
sleep(time);
$(".classname").html(temp);
}
function foo() {
swap(2000);
$(".tab1").slideToggle("slow");
$(".tab2").slideToggle("slow");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab1">
<div class="classname">
<p>Orginal Content in tab1</p>
</div>
</div>
<div class="tab2" style="display:none;">
<div>
<p>Orginal Content in tab2</p>
</div>
</div>
<button type="button" onclick="foo()">Enter</button>
JavaScript is single-threaded, so your sleep method freezes up the UI and prevents it from refreshing. You should be using setTimeout for this purpose instead.
function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>")
setTimeout(function(){
$(".classname").html(temp)
}, time)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="classname">
<p>Orginal Content</p>
</div>
<button type="button" onclick="swap(2000)">Enter</button>
Your code just locks up the browser and prevents rendering. You should be using a timeout. This code will make sure that multiple clicks do not mess up the default text.
function swap(selector, time) {
var elem = document.querySelector(selector);
if (!elem.dataset.orgText) elem.dataset.orgText = elem.innerHTML;
if (elem.dataset.timer) window.clearTimeout(elem.dataset.timer);
elem.innerHTML = "<p>Swap Content</p>";
elem.dataset.timer = window.setTimeout( function () {
elem.innerHTML = elem.dataset.orgText;
// delete elem.dataset.orgText;
// delete elem.dataset.timer;
}, time);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="classname">
<p>Orginal Content</p>
</div>
<button type="button" onclick="swap('.classname', 2000)">Enter</button>
written for jQuery
function swap(selector, time) {
var elem = $(selector);
if (!elem.data('orgText')) elem.data('orgText', elem.html());
if (elem.data('timer')) window.clearTimeout(elem.data('timer'));
elem.html("<p>Swap Content</p>");
elem.data('timer', window.setTimeout( function () {
elem.html(elem.data('orgText'));
// elem.removeData('orgText');
// elem.removeData('timer');
}, time));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="classname">
<p>Orginal Content</p>
</div>
<button type="button" onclick="swap('.classname', 2000)">Enter</button>
You can easily do it with two JQuery Lines:
function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>");
setTimeout(function () {
$(".classname").html(temp);
}, time)
}
Please check the Snippet for demo
function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>");
setTimeout(function () {
$(".classname").html(temp);
}, time)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab1">
<div class="classname">
<p>Orginal Content in tab1</p>
</div>
</div>
<div class="tab2" style="display:none;">
<div>
<p>Orginal Content in tab2</p>
</div>
</div>
<button type="button" onclick="swap(2000)">Enter</button>
can you try this instead?
function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>")
setTimeout(function(){
$(".classname").html(temp);
}, time);
}
function swap(time) {
temp = $(".classname").html();
$(".classname").html("<p>Swap Content</p>")
setTimeout(function(){
$(".classname").html(temp)
}, time)
}
This is the best option!

Why will my pictures not go through my if statements [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to make it so that every time that I click on the button that I created it cycles through the photos. Right now it won't do anything that I want
I think that a for loop would be the best way to go about this but I don't know what I am doing
var images = ["img/profile.jpg", "img/mountain.jpg", "img/sanfran.jpg"];
function loadPage() {
document.getElementById("pictures").src = images[0];
}
function nextImage() {
if (document.getElementById("pictures").src = images[0]) {
document.getElementById("pictures").src = images[1];
} else if (document.getElementById("pictures").src = images[1]) {
document.getElementById("pictures").src = images[2];
} else(document.getElementById("pictures").src = images[2]) {
document.getElementById("pictures").src = images[0];
}
}
<body onclick="loadPage()">
<div id="maincontent">
<div>
<img id="pictures">
</div>
<div id="paragraph">
<button class="button" onclick="nextImage()">Switch Images</button>
</div>
</div>
</body>
While Jet is on the right track. It will stop working after the last image, as index will be out of bounds.
EDIT Jet has updated their code, and the way of keeping index in bounds is quite elegant.
See the below example:
<body>
<div id="maincontent">
<div>
<img id="pictures">
</div>
<div id="paragraph">
<button class="button" onclick="nextImage()">Switch Images</button>
</div>
</div>
<script>
var images = [
"https://via.placeholder.com/150x150.png?text=1",
"https://via.placeholder.com/150x150.png?text=2",
"https://via.placeholder.com/150x150.png?text=3"
];
let currentImage = -1;
function nextImage() {
currentImage++; // Add 1 to the currentImage variable
if (currentImage === images.length) {
currentImage = 0; // If we've reached the last image, go to the first image
}
document.getElementById("pictures").src = images[currentImage]; // Set the src image to the current image in our images array
}
nextImage();
</script>
</body>
Bascially i cycle through the names of images stored in the array. i used the modulo (%) to ensure that i wont go out of bound of the array
<body>
<div id="maincontent">
<div>
<img src="img/profile.jpg" id="pictures">
</div>
<div id="paragraph">
<button class="button" onclick="nextImage()">Switch Images</button>
</div>
</div>
<script type="text/javascript">
var index = 1;
var images = ["img/profile.jpg", "img/mountain.jpg", "img/sanfran.jpg"];
function nextImage(){
document.getElementById('pictures').src = images[index%3];
index++;
}
</script>
</body>
var images = ["https://via.placeholder.com/150", "https://via.placeholder.com/500",];
var imageElement = document.getElementById("pictures");
function loadPage() {
imageElement.src = images[0];
}
function nextImage() {
if(imageElement.src == images[0])
imageElement.src = images[1];
else if (imageElement.src == images[1])
imageElement.src = images[2];
else if (imageElement.src == images[2])
imageElement.src = images[0];
}
<body onclick="loadPage()">
<div id="maincontent">
<div>
<img id="pictures">
</div>
<div id="paragraph">
<button class="button" onclick="nextImage()">Switch Images</button>
</div>
</div>
</body>
The issue was simple, inside IF conditions use ==
== is for comparison, = is for assignment
P.S instead of calling document.getElementById repeadetly to get the same element, you can also store the element's reference once in a variable and use it, to increase performance
== is used for conditions, and = is used for assignment. However, I would advise using a switch in this case instead of an if statement as below:
<body onclick="loadPage()">
<div id="maincontent">
<div>
<img id="pictures">
</div>
<div id="paragraph">
<button class="button" onclick="nextImage()">Switch Images</button>
</div>
</div>
<script>
let images = ["img/profile.jpg", "img/mountain.jpg", "img/sanfran.jpg"];
let src = document.getElementById("pictures").src
function loadPage() {
src = images[0];
}
function nextImage() {
switch (document.getElementById("pictures").src) {
case images[0]:
src = images[1];
break
case images[1]:
src = images[2];
break
case images[2]:
src = images[0];
break
}
}
</script>
</body>
EDIT: It seems others have come up with an even more efficient way to do this, but I'll leave it here as a reference to an alternative.

Display text in time intervals with CSS and JS

I would like to create, using the setInterval() JS function, a visual effect that displays text one character at the time with an interval of 100ms per character, on an Angular application.
Note that this happens in the index.html within the <app-root> tags, so it will appear only while the app is bootstrapped.
After reading the setInterval() page i thought that this would make the job, so this is my code:
var divs=['rBox','aBox','tBox','sBox'];
var index=-1;
function displayChars(){
for(container of divs){
document.getElementById(container).style.visibility='hidden';
}
var fun = setInterval(display,100);
}
function display(){
if(index < 4){
document.getElementById(divs[++index]).style.visibility='visible'
}else{
clearInterval(fun);
}
}
displayChars();
<app-root>
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
</app-root>
But it does not display anything, the divs containing the numbers are there with visibility set to hidden but it seems like they are never set to visible
I can't see where the problem lies. If I look at the code from an algorithmic point of view, I guess I probably don't understand very well the inner working of setInterval().
fun was not declared globally
And index was incremented too much
A rough update to the code:
var divs=['rBox','aBox','tBox','sBox'];
var index=-1;
var fun
function displayChars(){
for(container of divs){
document.getElementById(container).style.visibility='hidden';
}
fun = setInterval(display,100);
}
function display(){
if(index < 3){
document.getElementById(divs[++index]).style.visibility='visible'
}else{
clearInterval(fun);
}
}
displayChars()
<app-root>
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
</app-root>
After minor modifications it's working, see below. I changed index to start at 0 and to be used with divs[index++] (so use-then-increment), and to compare it with divs.length instead of hardcoded 4. Also I put variable fun at the global level.
var divs = ['rBox', 'aBox', 'tBox', 'sBox'];
var index = 0;
var fun = -1; // timer handle
function displayChars() {
for (container of divs) {
document.getElementById(container).style.visibility = 'hidden';
}
fun = setInterval(display, 100);
}
function display() {
if (index < divs.length) {
document.getElementById(divs[index++]).style.visibility = 'visible'
} else {
clearInterval(fun);
}
}
displayChars();
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
Your variable fun needs to be global, otherwise display() can't
access it
Don't forget to declare container in your for...of loop as an actual variable
You where incrementing index too often
var divs = ['rBox', 'aBox', 'tBox', 'sBox'];
var index = -1;
var fun;
function displayChars() {
for (var container of divs) {
document.getElementById(container).style.visibility = 'hidden';
}
fun = setInterval(display, 100);
}
function display() {
if (index < 3) {
document.getElementById(divs[++index]).style.visibility = 'visible';
} else {
clearInterval(fun);
}
}
displayChars();
<app-root>
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
</app-root>
Pure CSS solution, if an option, looks something like this:
.rats-div > div {
opacity: 0; /* or "visibility: hidden" */
animation: opacity .1s forwards;
}
.rats-div > div:nth-child(2) {animation-delay: .1s}
.rats-div > div:nth-child(3) {animation-delay: .2s}
.rats-div > div:nth-child(4) {animation-delay: .3s}
#keyframes opacity {
to {opacity: 1} /* or "visibility: visible / initial" */
}
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
var divs=['rBox','aBox','tBox','sBox'];
var index=0;
var fun=null;
function displayChars(){
for(container of divs){
document.getElementById(container).style.visibility='hidden';
}
fun = setInterval(display,100);
}
function display(){
if(index < 4){
document.getElementById(divs[index]).style.visibility='visible'
index++;
}else{
clearInterval(fun);
}
}
displayChars();
<app-root>
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
</app-root>
try this code. it should do your job.

Why is addEventListener returning as not a function

I have a simple script that is trying to register a click on a button. However, I keep getting the error *element*.addEventListener is not a function.
Can anyone explain what I'm doing wrong?
HTML
<div id="game">
<canvas id="gameScreen" width="550" height="500"></canvas>
<div id="output"><p></p></div>
<div id="controls">
<button id="north">North</button>
<button id="east">East</button>
<button id="west">West</button>
<button id="south">South</button>
</div>
</div>
JS
window.addEventListener("load", function(){
var canvas = document.getElementById("gameScreen");
var ctx = canvas.getContext("2d");
var output = document.getElementById("output");
var outputText = output.querySelector("p");
var controls = document.getElementById("controls");
var directionButtons = controls.getElementsByTagName("button");
directionButtons.addEventListener("click", function(){
console.log(this);
})
})
Error
TypeError: directionButtons.addEventListener is not a function
The getElementsByTagName() method will return a list of nodes and you should loop through them and attach listener to every one :
function my_click(){
alert(this.id);
}
var directionButtons = controls.getElementsByTagName("button");
for(i=0; i<directionButtons.length; i++) {
directionButtons[i].addEventListener("click", my_click, false);
}
Hope this helps.
function my_click(){
alert(this.id);
}
var directionButtons = document.getElementsByTagName("button");
for(i=0; i<directionButtons.length; i++) {
directionButtons[i].addEventListener("click", my_click, false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='1'>Button 1</button>
<button id='2'>Button 2</button>
<button id='3'>Button 3</button>
<button id='4'>Button 4</button>
Variable directionButtons is an array of multiple elements. You'll need to use loop here in order to add listeners.
window.addEventListener("load", function() {
var canvas = document.getElementById("gameScreen");
var ctx = canvas.getContext("2d");
var output = document.getElementById("output");
var outputText = output.querySelector("p");
var controls = document.getElementById("controls");
var directionButtons = controls.getElementsByTagName("button");
for (i = 0; i < directionButtons.length; i++) {
directionButtons[i].addEventListener("click", function() {
console.log(this);
});
}
})
<div id="game">
<canvas id="gameScreen" width="550" height="500"></canvas>
<div id="output">
<p></p>
</div>
<div id="controls">
<button id="north">North</button>
<button id="east">East</button>
<button id="west">West</button>
<button id="south">South</button>
</div>
</div>

Categories