vinayofficial vinayofficial - 6 months ago 63
Javascript Question

Add then remove class after delay but without page refresh

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.

Answer

Using jquery and setTimeout function:

var $elm = $("#username").addClass("error");
setTimeout(function() {
  $elm.removeClass("error");
}, 2000);
.error{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="username">USER NAME</div>