Reputation: 156
Using javascript i want to show error message, and the message will hide/disappear after 2 second . The error show perfectly and hide after 2 second but it does not work for the second time. if i reload my page it work perfectly again and so on.
JavaScript
if(task_hour == "hour" || task_minute == "minute"){
document.getElementById("error").innerHTML = "Add Time for the Task";
setTimeout(function(){ document.getElementById("error").style.display="none"; }, 2000);
return false;
}
HTML
<div id="errordiv" align="center" style="margin-left: auto; margin-right: auto;">
<span id="error" style="color: red"> </span>
</div>
Upvotes: 3
Views: 8299
Reputation: 843
The second error appears in hiden div
you have to create a span, append it to wrapper with error text and after 2 seconds destroy it:
function showError(message){
var span = document.createElement('span');
var errorWrap = document.getElementById("error");
span.appendChild(document.createTextNode(message));
errorWrap.appendChild(span);
setTimeout(function(){ span.parentNode.removeChild(span); }, 2000);
return false;
}
if(task_hour == "hour" || task_minute == "minute"){
showError('Add Time for the Task');
}
Upvotes: 0
Reputation: 3129
You should set the div to be initially hidden (display: none
) and use display: block
to show it:
JS:
var timer = null;
function showError(message) {
if (timer !== null) {
// Clear previous timeout:
clearTimeout(timer);
timer = null;
}
var errorElement = document.getElementById("error");
errorElement.innerHTML = message;
errorElement.style.display = 'block';
timer = setTimeout(function(){ errorElement.style.display = 'none'; }, 2000);
}
showError('Error!');
HTML:
<div id="errordiv" align="center" style="margin-left: auto; margin-right: auto;">
<span id="error" style="color: red; display: none"></span>
</div>
Upvotes: 5