myDIV1 and myDIV2, shown and disappeared by turn

I like to make like the quote below.

The pages at http://form.kr/q/toggle04.php and http://form.kr/q/toggle05.php are two of my trials for making a page like the quote above.
However, it seems not to work as I want like the quote above.

Can I make it work correctly like the quote above with your help?

The easiest way to reliably achieve that is to hide all of the relevant divs, then only show the one that you need.

1 Like

At the risk of stepping in where I’m not wanted and until @Paul_Wilkins helps you arrive at the correct solution I can point out a couple of errors. :slight_smile:

You are checking the style property here:

if (y.style.display === "none") {

The style property only applies to styles that have been set inline like this;

<div style="display:block">test</div>

It does not refer to the display property as set in the stylesheet for which you would need getComputedStyle instead.

If you are only toggling two divs then you don’t need to do any comparisons; just turn one off and the other one on.

e.g.

function myFunction1() {
  var x = document.getElementById("myDIV1");
  var y = document.getElementById("myDIV2");
  x.style.display = "block";
  y.style.display = "none";
}
function myFunction2() {
  var x = document.getElementById("myDIV1");
  var y = document.getElementById("myDIV2");
  y.style.display = "block";
  x.style.display = "none";
}

I’ll leave it to @Paul_Wilkins to explain why you should not use inline click handlers or use duplicated functions when one would do.:slight_smile: It’s also usually better to let CSS handle the display toggles rather than interfering directly with JS. Let JS just add the appropriate class.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.