1

I'm working on a website where I want to show and hide images by clicking on a button/word. I used bit of code and it's working:

function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

Similar to the one used in a previous stack overflow question on this topic:

var button = document.getElementById('button'); // Assumes element with id='button'

button.onclick = function() {
    var div = document.getElementById('newpost');
    if (div.style.display !== 'none') {
        div.style.display = 'none';
    }
    else {
        div.style.display = 'block';
    }
};

However, I want the image to be hidden when you enter or refresh the site instead of shown. So instead of it starting by showing the image and hiding it when you click on the word, I want it to be hidden and shown when you click the word. How do I change the script to make that happen?

I tried to switching the "none" and "block" but it didn't work haha...

Thanks

gakalokay
  • 11
  • 1

1 Answers1

0

You can hide the image when the script runs, which is when the page is loaded or refreshed. So just adding one line is enough.

const button = document.getElementById("button") // Assumes element with id='button'
const imageElement = document.getElementById("newpost")

// Hide the image at the start
imageElement.style.display = "none"

// Toggle it on click
button.addEventListener('click', () => {
    imageElement.style.display =
        imageElement.style.display === "none" ? "block" : "none"
})

I also modified your code to make it a bit easier to read by using a ternary operator.

And in case you are using the .onClick method from the example: Prefer using addEventListener over .onX methods. More about that on MDN and on this answer.

Woww
  • 344
  • 2
  • 10