javascript - If hasClass help and subtracting from variables -
i trying make when '.main' clicked, toggle class become '.second', new class become red element have been classed '.main' already, thus, can still refer '.main'. after want add 'count' variable and, if clicked again, revert appearance of '.main' class, subtracting 'count' variable!
html
<div class="container"> <div id="box" class="main"></div> <div id="box" class="main"></div> <div id="box" class="main"></div> <div id="box" class="main"></div> </div> relevent css
.main { background: #888888; } .second { background: red; } #box { width: 10px; height: 10px; border-radius: 10px; margin: 1% 1%; line-height: 100px; text-align: center; } and, jquery
$(document).ready(function() { var count = 0; $('.main').click(function() { $(this).toggleclass('second') $(this).toggleclass('main') if ($(this).hasclass('main')) { count++; } else if ($(this).hasclass('second')) { count--; } if (count === 4) { alert('success') } }); }); so need because jquery keep adding 'count' variable if 'this' hasclass '.second'!
if think have answer check in jsfiddle , click 1 box 4 times, if prompt 'count--;' isn't subtracting still
you may need change these.
- remove
countvariable , instead use jquery's length. - do not use same value
id.
$(document).ready(function() { $('.main').click(function() { $(this).toggleclass('second').toggleclass('main') if ($('.main').length == 4) alert('success') }); }); .main { background: blue; } .second { background: red; } #box1, #box2, #box3, #box4 { width: 10px; height: 10px; border-radius: 10px; margin: 1% 1%; line-height: 100px; text-align: center; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="container"> <div id="box1" class="main"></div> <div id="box2" class="main"></div> <div id="box3" class="main"></div> <div id="box4" class="main"></div> </div>
Comments
Post a Comment