So I am creating a video game where an icon moves with pc controllers. Also, I want that when I press the space bar, my icon (spaceship which moves with controllers) switches be
Using your DOM you have to keep track which img
is currently displayed. For that I added two classes to toggle (None and Block), which you can rename/restyle how you see fit.
//REM: Shows the first hidden image
function showFirst(){
//REM: Get the first "none" element (=.None)
var tFirst = document.querySelector('.None');
//REM: Show it
if(tFirst){
tFirst.classList.remove('None');
tFirst.classList.add('Block')
}
};
document.addEventListener("keydown", function(event){
if(event.keyCode === 32){
event.preventDefault();
//REM: Get the current "display" element (=.Block) or the first "none" one (=.None)
var tCurrent = document.querySelector('.Block');
//REM: If found...
if(tCurrent){
//REM: Hide current
tCurrent.classList.remove('Block');
tCurrent.classList.add('None');
//REM: Get the next image in the markup
var tNext = tCurrent.nextElementSibling;
//REM: Show it, if exists
if(tNext && tNext.tagName === 'IMG'){
tNext.classList.remove('None');
tNext.classList.add('Block')
}
//REM: Else show the first image again
else{
showFirst()
}
}
//REM: Else show the first image
else{
showFirst()
}
}
})
.None{display: none}
.Block{display: block}
<img src="Photo/Spaceship.png" id="icon-p1" class="None" alt="1">
<img src="Photo/Spaceship1.png" id="icon-p2" class="None" alt="2">
<img src="Photo/Spaceship2.png" id="icon-p3" class="None" alt="3">
<img src="Photo/Spaceship3.png" id="icon-p4" class="None" alt="4">
The second way is to have only one image
and change the src
of that one arrcoding to an object.
var imgs = [
{src: '', alt: '1', active: true},
{src: '', alt: '2', active: false},
{src: '', alt: '3', active: false},
{src: '', alt: '4', active: false}
];
document.addEventListener("keydown", function(event){
if(event.keyCode === 32){
event.preventDefault();
//REM: The element
var tIMG = document.getElementById('icon-p1');
if(tIMG){
//REM: Getting index of current
var tIndex = imgs.findIndex(element => element.active);
//REM: Getting the next or first object
var tNext = (tIndex < imgs.length-1) ? imgs[tIndex + 1] : imgs[0];
//REM: Assigning the properties
tIMG.src = tNext.src;
tIMG.alt = tNext.alt;
//REM: Toggling the activity in the object
imgs[tIndex].active = false;
tNext.active = true
}
}
})
<img src="Photo/Spaceship.png" id="icon-p1" alt="1">
Be aware that those are all basic examples and not productive code.