1

This is my code and it's horizontal on desktop screen and on phone it's vertical and x button(closebtn) is only on phone displayed and closes the menu bar. How do I automatically display it again, after resizing the page to desktop size?

function oty() {
  document.getElementById("tab").style.display = "none";
}
<div class="icon-bar" id="tab">
  <button class="closebtn" onclick="oty()">X</button>
  <button class="tablink">Home</button>
  <button class="tablink">News</button>
  <button class="tablink">Contact</button>
  <button class="tablink">About</button>
    </div>
Omar Siddiqui
  • 1,625
  • 5
  • 18
adastani33
  • 13
  • 2

1 Answers1

2

RECOMMENDED: Stick to CSS @media

You can easily add media queries that determine a display of any given element based on viewport size, which is the foundation of responsive design anyways. In your case, keeping the markup as-is, the CSS could be something like...

@media screen and (max-width: 1024px) { // Adjust the break-point size as needed
  #tab {
    display: none;
  }
}

Not recommended: listen for resize event and check the viewport size

While I'd strongly advise against using JavaScript for something CSS is built for, it is possible with JavaScript. Try something like following.

  1. Add a resize event listener to window: (e.g. window.addEventListener('resize', handleResize))
  2. Write a function that toggles your tab element's visibility.
  3. Consider adding a throttle handler to prevent over-firing the events.
Bumhan Yu
  • 2,078
  • 1
  • 10
  • 20
  • yes i see but after i did it nothing happened and from inspect element i understood it's because java script's command is rathered than css's(@media screen and (min-width: 900px)) is there any solution for this or i should change the code completely – adastani33 Aug 09 '21 at 08:19
  • Based on the code you shared, clicking `.closebtn` button will hide its parent div `#tab`. After that point, you have to listen for window's resize event to restore its visibility based on viewport width. See [this answer](https://stackoverflow.com/questions/641857/javascript-window-resize-event) Again, I'd advise against it. My recommendation is to remove `.closebtn` button element, and take advantage of CSS more to toggle `#tab` visibility. See [this tutorial](https://www.freecodecamp.org/news/how-to-build-a-responsive-navbar-with-a-toggle-menu-using-flexbox-3438e1d08783/). – Bumhan Yu Aug 09 '21 at 14:51