views:

53

answers:

4
+1  Q: 

JavaScript counter

Everytime a specific action is made in JavaScript for example this:

<script type="text/javascript">
$(function() {
    $('#typing').keyup(function () {
     switch($(this).val()) {
       case 'containment':
// HERE
break;
     }
    });
});
</script>

inside the //HERE would be where the 'counter' was made. Then add 1 everytime the case 'containment' is run if it's not already run. So if I run containment case once.. it adds. If I run it again.. it will not -- see what I am talking about?

+1  A: 

How's this:

<script type="text/javascript">
var shouldRunContainment = true;

$(function() {
    $('#typing').keyup(function () {
     switch($(this).val()) {
       case 'containment':
       if(shouldRunContainment) {
         shouldRunContainment = false;
         // Run containment
       }
       break;
     }
    });
});
</script>
Coding Gorilla
That's one way -- but waht about the counter? Could be handled via cookies?
Dan
What exactly do you want to count?
Litso
A simple variable. I want to count how many 'first-runs- of a case was initiated.
Dan
+2  A: 

You have to define the counter before the counting starts. Then you can add to it later, like this:

<script type="text/javascript">
var count = 0;  //(or any number you need)
$(function() {
    $('#typing').keyup(function () {
     switch($(this).val()) {
       case 'containment':
          count++;
break;
     }
    });
});
</script>
Litso
Sorry I am JavaScript newb. How would I display the counter on a web page? :P
Dan
If you have a <span> or <div> that you would want to show the counter in it, like this: `<span id="counter"></span>` you can insert the counter (and even update it when it changes) by putting `$('#counter').text(count);` directly below the `count++;` rule
Litso
Ok cool. How would I divide the counter by a certain number... let's say.. 43 and make it round like 00.00% that?
Dan
This is not working: if(moviesRun) { count++; newPercent = count/34; $('#counter').text(newPercent); moviesRun = false; }
Dan
Ok whoops - it works now. But now I get: 0.03333333333333333% How do I round that to like 00.03%?
Dan
Nevermind -- got it! :D
Dan
+1  A: 

Instead of using a counter you can add/remove a class from $('#typing').

For example:

var count = 0;
$('#typing').keyup(function () {
    switch($(this).val()) {
        case 'containment':
        // Will only run if the element does NOT have the containment class
        if(!$(this).hasClass('containment'){
            // Add containment class
            $(this).addClass('containment');
            // Counter
            count++;
        }
        break;
    }
});
Rocket
Where does the counter fit in all of this?
Dan
Is this better?
Rocket
A: 

Yep, I can go with the approach Coding Gorilla proposed - works for me :)

Dick Lampard
Please add a comment on the Coding Gorilla instead of creating another answer...
romaintaz