michaelmcgurk
michaelmcgurk

Reputation: 6519

Click elements and set as 'Active' using jQuery

I have a simple script that shows 6 boxes.

The plan is when the user clicks any of these boxes, they should turn to grey background. However, this doesn't work. Is there something wrong with how I'm using .on?

Demo: http://jsfiddle.net/szzqe8L1/

$(".thumb-overlay-content").on('click',function() {
    $(this).removeClass('rotateOut').addClass('rotateIn');
}, function() {
    $(this).removeClass('rotateIn').addClass('rotateOut');
});
.thumb-overlay-content { margin:10px; background:#CCC; float:left; text-align:center; padding:50px; }
.animated { background:red; }
.rotateOut { border:3px solid blue; }
.rotateIn { border:3px solid green; background:#ccc; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>

Upvotes: 0

Views: 42

Answers (1)

void
void

Reputation: 36703

.on('click' expects one callback function which says what to do when the user clicks on element matching the selector.

You can get the functionality you want using .toggleClass()

$(".thumb-overlay-content").on('click',function() {
    $(this).toggleClass('rotateOut rotateIn');
});
.thumb-overlay-content { margin:10px; background:#CCC; float:left; text-align:center; padding:50px; }
.animated { background:red; }
.rotateOut { border:3px solid blue; }
.rotateIn { border:3px solid green; background:#ccc; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>
<div class="thumb-overlay-content animated rotateOut">Box1</div>

Upvotes: 2

Related Questions