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.

  1. remove count variable , instead use jquery's length.
  2. 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

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -