admin管理员组文章数量:1402960
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>
本文标签: javascriptAdd then remove class after delay but without page refreshStack Overflow
版权声明:本文标题:javascript - Add then remove class after delay but without page refresh - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744633627a2616689.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论