How to optimize code that shows one block and hides others? (javascript)

I have 3 blocks, when opening one, all should hide. I wrote the simplest code (I'm a beginner), I understand that it can and should be optimized. How can I do that? I'm thinking of using "if else" construction, but not sure how to do it correctly.

function openLink(){
  document.getElementsByClassName('open_link')[0].style.display = 'block';
  document.getElementsByClassName('open_images')[0].style.display = 'none';
  document.getElementsByClassName('open_video')[0].style.display = 'none';
}

function openImages(){
  document.getElementsByClassName('open_images')[0].style.display = 'block';
  document.getElementsByClassName('open_link')[0].style.display = 'none';
  document.getElementsByClassName('open_video')[0].style.display = 'none';
}

function openVideo(){
  document.getElementsByClassName('open_video')[0].style.display = 'block';
  document.getElementsByClassName('open_images')[0].style.display = 'none';
  document.getElementsByClassName('open_link')[0].style.display = 'none';
}

function closeForm(){
  document.getElementsByClassName('open_link')[0].style.display = 'none';
  document.getElementsByClassName('open_images')[0].style.display = 'none';
  document.getElementsByClassName('open_video')[0].style.display = 'none';
}
<a onclick="openLink()" href='#'>One</a>
<a onclick="openVideo()" href='#'>Two</a>
<a onclick="openImages()" href='#'>Three</a>


<div class="open_link" style="display: none;">
<button onclick="closeForm()">Save 1</button>
<button onclick="closeForm()">Close 1</button>
</div>

<div class="open_video" style="display: none;">
<button onclick="closeForm()">Save 2</button>
<button onclick="closeForm()" >Close 2</button>
</div>

<form class="open_images" style="display: none;">
<input onclick="closeForm()" value="Upload 3"/>
<button onclick="closeForm()" >Close 3</button>
</form>



Read more here: https://stackoverflow.com/questions/65704776/how-to-optimize-code-that-shows-one-block-and-hides-others-javascript

Content Attribution

This content was originally published by Sasha at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: