Reputation: 139
I want to remove a class that is added right after the user click on a div.
I mean, after the div is clicked, I want the class to be removed.
https://codepen.io/jinzagon/pen/XWdVbgo
<script>
$(document).ready(function() {
$('.section').click(function(e) {
e.preventDefault();
var $responsiveDiv = $('.response')
$responsiveDiv.addClass('clicked');
setTimeout(function() {
window.location.assign($a.attr('href'));
}, 6700);
});
});
</script>
Upvotes: 0
Views: 351
Reputation: 11
One way to remove class name as you use jQuery is .removeClass()
Reference https://api.jquery.com/removeclass/
Another way which I prefer is to toggle class name. Here is a reference jQuery: https://www.w3schools.com/jquery/jquery_css_classes.asp Vanilla Javascript: https://www.w3schools.com/howto/howto_js_toggle_class.asp
Last but not least, the easiest way is to set the className equal to none. As an example in JavaScript
document.querySelector('.clicked').className = '';
Upvotes: 0
Reputation: 146
With javascript you can achieve this using .classList.remove("foo");
Read more about Element.classList
function addClassThenRemove(){
// grab h1 element
let h1Element = document.querySelector('h1')
// add class to the element
h1Element.classList.add('new')
setTimeout(function(){
//after 2 seconds remove class new
h1Element.classList.remove('new')
}, 2000)
}
.new{
color: blue;
}
<h1>Hello World</h1>
<button onClick="addClassThenRemove()">Click Me!</button>
Upvotes: 1
Reputation: 90
You can use the function toggleClass()
for this
<script>
$(document).ready(function() {
$('.section').click(function(e) {
e.preventDefault();
var $responsiveDiv = $('.response')
$responsiveDiv.toggleClass('clicked'); //Toggle class instead of Add
setTimeout(function() {
window.location.assign($a.attr('href'));
}, 6700);
});
});
</script>
Upvotes: 1
Reputation: 46
You need use setTimeout postpone remove
<script>
$(document).ready(function() {
$('.section').click(function(e) {
e.preventDefault();
var $responsiveDiv = $('.response')
$responsiveDiv.addClass('clicked');
setTimeout(function() {
$responsiveDiv.removeClass('clicked');
}, 1000);
setTimeout(function() {
window.location.assign($a.attr('href'));
}, 6700);
});
});
</script>
Upvotes: 1
Reputation: 442
jQuery has a toggleClass
function that you can use. Link
Here it is in your example - when you click the section the background color will toggle (for ease of observation).
.clicked {
background-color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="section">
<div class="response">
This is a response
</div>
</div>
<script>
$(document).ready(function() {
$('.section').click(function(e) {
e.preventDefault();
var $responsiveDiv = $('.response');
$responsiveDiv.toggleClass('clicked');
});
});
</script>
Upvotes: 3