skip to Main Content
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 class="news-message"> Our Website is currently being developed. Please stay patient.</p>
    <button class="news-message" 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

4

Answers


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

    check your html id name!
    [![enter image description here][1]][1]

    this error means it couldn’t get the defined id
    [1]: https://i.stack.imgur.com/gaE4Q.jpg

    Login or Signup to reply.
  2. 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")
    });
    
    Login or Signup to reply.
  3. Your code is working fine.

    Make sure you didn’t forget to import the js file into the html, Ex:

    <script src="src/index.js"></script>
    
    Login or Signup to reply.
  4. I found what problem do you have, I was thinking that it was a problem with the JS file but it´s not, the problem is that you´re linking the js file in the head of the document when the elements doesn´t even exist (because HTML files create the elements reading from the top to the bottom of the file). You need to put the <script src="script.js"></script> at the end of the <body> tag.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search