0

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 :)

asked Mar 16, 2017 at 23:48
2
  • Is #images actually a canvas element? as that is not how you load images into a canvas. Currently those img tags have no src attribute, and so wont load an image. Is there a reason you're dynamically inserting the img tag rather than having it in the DOM already? Commented Mar 16, 2017 at 23:51
  • is this what you're trying to do? toggle the box-shadow when you press "a"? codepen.io/anon/pen/qrVjMO Commented Mar 16, 2017 at 23:55

1 Answer 1

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.