I am currently trying to change the class of a set of images when I press a button on my keyboard (a). I have written the following code:
<div id="images" class="img"/>
<img src="spiderman.png" alt=""/>
<img src="superman.png" alt="" height="25%" width="25%"/>
<img src="batman.png" alt="" />
</div>
<Script type="text/javascript">
function keyDown(event) {
if (event.keyCode == 65) {
var canvas = document.getElementById('images');
canvas.innerHTML = '<img class="img2" />'
}
}
function keyUp(event) {
if (event.keyCode == 65) {
var canvas = document.getElementById('images');
canvas.innerHTML = '<img class="img" />';
}
}
</script>
css
.img {
position: absolute;
right: 15%;
top: 30%;
display: flex;
flex-direction: column;
align-items: flex-end;
}
.img2 {
box-shadow: 0px 0px 5px #fff;
position: absolute;
right: 15%;
top: 30%;
display: flex;
flex-direction: column;
align-items: flex-end;
}
I am very new to both html and JavaScript so have no idea why this isn't working or even if I have used JavaScript correctly within my html, is what I am trying to achieve even possible? A point in the right direction would be helpful :)
1 Answer 1
In your code you are not replacing the element class. You are replacing the image itself. If you want to change the clas use this:
document.getElementById("MyElement").className = "MyOtherClass"
So it's going to be something like:
(function() {
function keyDown(event) {
if (event.keyCode == 65) {
if (document.getElementsByClassName("img").length > 0) {
document.getElementsByClassName("img")[0].className = "img2"
} else {
document.getElementsByClassName("img2")[0].className = "img"
}
}
}
document.addEventListener('keydown', keyDown);
})();
.img {
width: 100px
}
.img2 {
width: 400px
}
<img class="img" src="http://www.axpe-blogs.com/wp-content/uploads/stackoverflow_logo.jpg" />
answered Mar 16, 2017 at 23:57
default
#images
actually acanvas
element? as that is not how you load images into acanvas
. Currently thoseimg
tags have nosrc
attribute, and so wont load an image. Is there a reason you're dynamically inserting theimg
tag rather than having it in the DOM already?