Home > Enterprise >  on button click, show message for x seconds without alert() function - is it possible?
on button click, show message for x seconds without alert() function - is it possible?

Time:11-03

In my NEXT.JS project, I want a simple <p> element to show below my button for x amount of time, and then I want it to disappear. I don't want to use alert() function. How can I manage that?

CodePudding user response:

You can achieve that with a simple js event trigger. All you need to do is create a click event listener for the button, and then attach your 'p' element to the desired view.

Btw this has nothing to do with next.js this is core js DOM manipulation. You should learn about DOM and how to work with it, and then explore frameworks like next. Only with good knowledge of core js, and DOM manipulation, You will be able to really learn frameworks.

CodePudding user response:

In case anyone needs it, here is the solution using useState and simple handler...

const [myAlert, setMyAlert] = useState(false)
  
  const handleMyAlert = () => {
    setMyAlert(true);
    setTimeout(() => {
      setMyAlert(false)
    }, 5000);
  } 

You can use it like this: <button onClick={handleMyAlert}>Click me</button>

and for <p> set style={myAlert ? {display: "block"} : {display: "none}}

CodePudding user response:

I'm too late but I post it anyway to try the snippet method.

function setMsg(e){
            let inter = alertMsg(e);
        }
        
        function alertMsg(e){
            document.getElementById("alertP").innerHTML="Click-me!";
            document.getElementById("alertP").style.display="inline";
            inter= setInterval("hideOutput()",3000);
        }
        function hideOutput(){
            document.getElementById("alertP").style.display="none";
            clearInterval(inter);
        }
html, body{
        font-family:"sans-serif";
            font-size:1em;
        }
        button{
            font-size:1.2em;
        }
        #buttonContainer{
            width:200px;
            margin:auto;
        }
        #alertP{
            display:none;
            text-align: center;
            border:1px solid #000000;
            background-color:red;
            color:#FFFFFF;
        }
<div id="buttonContainer">
        <button id="clickableArea" onm ouseOver="setMsg()">Alert Button</button>
        <p id="alertP"></p>
    </div>

CodePudding user response:

function hide(){
  const div = document.getElementById("alert")
  div.parentNode.removeChild(div);

}
#alert{
  background-color:lightgreen;
  width:200px;
  height:100px;
}
<html>
<body>
<button onclick="hide()">Hide</button>
<div id="alert">
<h1>Alert</h1>
<p>Message</p>
</div>
</body>
</html>

  • Related