I am adding a class .error
on click and now after time interval of 2 seconds I want to remove this class, but without page reload/refresh.I used delay()
in jQuery as:
$('#username').addClass('error').delay(2000).removeClass('error');
but it's not working.
Then I tried setTimeout()
.
It's working, but reloading page. I want something that would add, and then remove, class after specific time but do not refresh/reload the page.
Please help, and thank you in advance.
I am adding a class .error
on click and now after time interval of 2 seconds I want to remove this class, but without page reload/refresh.I used delay()
in jQuery as:
$('#username').addClass('error').delay(2000).removeClass('error');
but it's not working.
Then I tried setTimeout()
.
It's working, but reloading page. I want something that would add, and then remove, class after specific time but do not refresh/reload the page.
Please help, and thank you in advance.
Share Improve this question edited May 14, 2016 at 19:56 David Thomas 254k53 gold badges382 silver badges419 bronze badges asked May 14, 2016 at 19:52 vinayofficialvinayofficial 4821 gold badge5 silver badges22 bronze badges 3-
4
can't use
delay()
for methods that aren't "queueable" like animations. Please show your code. No reason thatsetTimeout()
would reload page by itself – charlietfl Commented May 14, 2016 at 19:55 - This is my code (and its reloading the page which is not wanted): $('#username').addClass('error').setTimeout(function(){ $(this).removeClass('error'); },2000); – vinayofficial Commented May 14, 2016 at 20:00
-
that will throw error because you are trying to chain
setTimeout()
as jQuery method when it is a global window function. My guess is you are using this in a form submit handler and the error breaks the submit handler and form gets submitted by default process – charlietfl Commented May 14, 2016 at 20:02
2 Answers
Reset to default 5
var element = document.getElementById('username');
element.classList.add('error');
window.setTimeout(function () {
element.classList.remove('error');
}, 2000);
#username {
width: 100%;
height: 50px;
line-height: 50px;
color: white;
background-color: green;
text-align: center;
transition: background-color .25s linear;
}
#username.error {
background-color: red;
}
<div id="username">Username</div>
Using jquery and setTimeout function:
var $elm = $("#username").addClass("error");
setTimeout(function() {
$elm.removeClass("error");
}, 2000);
.error{
color:red;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="username">USER NAME</div>