Home > database >  Why is my news-bar not hidden when I click on the close-button?
Why is my news-bar not hidden when I click on the close-button?

Time:12-16

const closeButton = document.getElementById('close-button');

// Listen for a click event on the close button
closeButton.addEventListener('click', () => {
    const newsBar = document.getElementById('news-bar');

    // Set the display of the news bar to "none" to hide it
    newsBar.style.display = 'none';
});
#news-bar {
    background-color: rgb(255, 221, 0);
    margin-top: -1em;
    display: block;

}

.news-message {
    display: inline-grid;

    margin: auto;
    margin-top: 1.3em;
    margin-bottom: 0.3em;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

#close-button {
    margin-left: 2em;

}
<div id="news-bar">
    <p > Our Website is currently being developed. Please stay patient.</p>
    <button  id="close-button">X</button>
</div>

I tried to change the element CSS so it's hidden by default, but that makes no sense because I want it to be here when a user visits the website

CodePudding user response:

Try change all const to var, and see if it works.

CodePudding user response:

Maybe your script is wrong linked or the document.getElementById() is not finding any element, please make a console.log of what the 2 document.getElementById() return. Also, the CSS can be blocking your style change, so I would recommend you to make two different ids. For example:

CSS FILE

#news-bar {
    background-color: rgb(255, 221, 0);
    margin-top: -1em;
    display: block;

}
#news-bar-hidden {
    display:none;
}

JS FILE

let closeButton = document.getElementById('close-button');

// Listen for a click event on the close button
closeButton.addEventListener('click', () => {
let newsBar = document.getElementById('news-bar');

// Set the id of newsBar to "news-bar-hidden"
newsBar.removeAttribute("id")
newsBar.setAttribute("id","news-bar-hidden")
});
  • Related