Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
How to show/hide an element on interval

So I have this button which onclick has a function that shows an element. Now I want to add a function by default that will hide this same element after some given interval. So if I click this button, div-container will be displayed after .5s. Now I want to check that if this div-container is displayed, the users can read it and then it will be hidden. So It's more like an alert.

Heres my snippet:

document.getElementById("mybtn").addEventListener("click",function(){

        let clock = setInterval(() => {
            clearInterval(clock)
            clock = null
            document.getElementById('alert').style.display = 'block'
        }, 500)
})


// this is where I tried to make it hide after some given interval but it's not working
var alert = document.getElementById('alert');
if(alert.style.display==="block"){

        let clock = setInterval(() => {
            clearInterval(clock)
            clock = null
            document.getElementById('alert').style.display = 'none'
        }, 500)
}
<button id="mybtn">Show/hide</button>

<div id="alert" style="display:none"><h3>this is an alert</h3></div>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I think you are looking for setTimeout.

let clockTimeout = null

document.getElementById("mybtn").addEventListener("click",function(){
        document.getElementById('alert').style.display = 'block'
        clearTimeout(clockTimeout)
        clockTimeout = setTimeout(() => {
          document.getElementById('alert').style.display = 'none'
        }, 1500)
})
<button id="mybtn">Show/hide</button>

<div id="alert" style="display:none"><h3>this is an alert</h3></div>

about 4 years ago · Juan Pablo Isaza Report

0

Inside your event you have first to show the alert div container. then you set the Timeout. inside the timeout function you hide the alert box again.

document.getElementById("mybtn").addEventListener("click",function(){
        document.getElementById('alert').style.display = 'block'
        let clock = setInterval(() => {
            document.getElementById('alert').style.display = 'none'
        }, 5000)
})
<button id="mybtn">Show/hide</button>

<div id="alert" style="display:none"><h3>this is an alert</h3></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!