Home > Net >  Javascript pop up
Javascript pop up

Time:12-18

Im kinda new to the world of web development , right now I have knowledge in CSS & HTML and trying and learn TypeScript. Im trying to make this message icon to open up and close up this notifications bar. right now this is i got so far:

document.getElementById("bar").addEventListener("click", function(){
    document.querySelector(".messagebar").style.display = "flex";
})
    

I tried to make:

document.getElementById("bar").addEventListener("click", function(){
    document.querySelector(".messagebar").style.display = "none";

it`s not working. ty for help!

I tried to make:

document.getElementById("bar").addEventListener("click", function(){ document.querySelector(".messagebar").style.display = "none";

it`s not working. ty for help!

CodePudding user response:

You are adding 2 of the same event listeners to the same element. This means that the event listener you are creating here:

document.getElementById("bar").addEventListener("click", function(){
    document.querySelector(".messagebar").style.display = "flex";
})

and the event listener created here:

document.getElementById("bar").addEventListener("click", function(){
    document.querySelector(".messagebar").style.display = "none"
)}

are both being executed at the same time upon click. This means that the display is first being set to flex and secondly to none hence why you are unable to make it work.

In order to fix this we want to condense this into one event listener. The following works:

document.getElementById("bar").addEventListener("click", () => {
    const messageBar = document.querySelector('.messagebar')
    const display = messageBar.style.display
    // if display is flex sets it to none else sets it to flex
    messageBar.style.display = display === 'flex' ? 'none' : 'flex'
});

CodePudding user response:

If you want to toggle with the same button, or html element, you will have to track the currect state of the .messagebar.style.display.

document.getElementById("bar").addEventListener("click", function(){
    const current = document.querySelector(".messagebar").style.display;
    if (current === "none") {
      document.querySelector(".messagebar").style.display = "flex";
    } else {
      document.querySelector(".messagebar").style.display = "none";
    }
})
  • Related