Home > Blockchain >  how can i make an element's display onchanged after the user closed the menu
how can i make an element's display onchanged after the user closed the menu

Time:02-03

i want to change display of an element to none when the user open my website menu i used on click event and changed the display by DOM but i want to make the display unchanged when the user close the menu what should i do?

}

function removeSearch(){
    document.getElementById("search-id").style.display = "none"; 
}
<button type = "button" onclick="removeSearch()" class = "navbar-toggler">

CodePudding user response:

Here's an example where you can keep track of the menu state and toggle the element you want to show and hide by it's data attribute.

const menuToggle = document.querySelector('.menu_toggle');
const menu = document.querySelector('.menu');
const someElement = document.querySelector('.some_element');
menuToggle.addEventListener('click',e=>{
    if(menu.dataset.state==='closed'){
        menu.dataset.state='opened'
        someElement.dataset.state='closed'
    }else{
        menu.dataset.state='closed'
        someElement.dataset.state='opened'
    }
})
.menu{
    background: rgb(152, 152, 233);
}
[data-state="closed"]{
    display: none;
}

.some_element{
    background: rgb(36, 36, 36);
    color: white;
    padding: 2em;
}
<button >Toggle Menu</button>
   <div  data-state="closed">
       <h2>Menu</h2>
       <ul>
           <li>Apple</li>
           <li>Orange</li>
           <li>Grapes</li>
       </ul>
   </div>
   <div >Element to Show and Hide</div>

CodePudding user response:

Since you are using jquery, you can use the .toggle() method to toggle the element. Try this

$(document).ready(function(){
    $('.navbar-toggler').click(function(){
        $("#search-id").toggle();
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button >Toggle Menu</button>
<ul id="search-id" style="display:none;">
    <li>Dog</li>
    <li>Cat</li>
    <li>Mouse</li>
</ul>

  •  Tags:  
  • Related