Search code examples
javascriptarrayssrc

Style .src property on array elements


So I have the following code that when space bar is pressed, images are switched. My issue is that each of my images have different resolution and as w3schools explained: "Note: The src property can be changed at any time. However, the new image inherits the height and width attributes of the original image, if not new height and width properties are specified." But, as you may see on code, my images are arrays elements. Does someone know how to style elements of arrays? Thanks!!

Switch between images:

setTimeout(function() {
let icon = document.getElementById("icon-p1")
icon.style.display = 'block'
let spaceship1 = "Photo/Spaceship.png"
let spaceship2 = "Photo/Spaceship1.png"
let spaceship3 = "Photo/Spaceship2.png"
let spaceship4 = "Photo/Spaceship3.png"
let hits = 0;
const images = [spaceship1, spaceship2, spaceship3, spaceship4]
document.body.onkeyup = function(e) {
if (e.keyCode === 32) {hits++; icon.src = images[hits % 4]}}}, 4000)}

Initial image

<img src="Photo/Spaceship.png" id="icon-p1" style="display:none">

Solution

  • You wouldn't style the array element, but the actual HTML element instead.

    You can use javascript to detect the next image and set the height and width that way.

    You can also use a 2D array to store them as well, something like this:

    const images = [[spaceship1,"1920px","1080px"],[spaceship2,"1366px","768px"]];
    

    And then set the height and width with javascript dynamically using the specified height and width for that image.

    Setting the image source would stay the same, and set the height and width like so:

    icon.height = images[0][1]
    icon.width = images[0][2]
    

    Where the first array index is the image you want.