0

My question is: what is the most intelligent way to use a for loop which affects CSS via jQuery and a timer together?

Here's a fiddle:

http://jsfiddle.net/j6jLh2dn/

Below is my attempt at implementing a timer which defines a certain amount of time that you can either press the enter key, or not press the enter key, and depending on the situation, it will push a value to an array.

setTimeout(function(){
            if(e.which == 13){
                choice = 1;
            } else {
                choice = 0;
            }

            if(nBack == randomNumber){
                if(choice == 1){
                    correct.push(0);
                } else if(choice == 0){
                    incorrect.push(0);
                }
            } else {
                if(choice == 0){
                    correct.push(0);
                } else if(choice == 1){
                    incorrect.push(0);
                }
            }

        }, 1000 * i * y)();

and here's the portion which should select a certain css id, then edit it based on a random number being chosen:

randomNumber = Math.floor( Math.random() * (m+1) );

            while(randomNumber === history[i-1]){
                randomNumber = Math.floor( Math.random() * (m+1) );
            }

            $("." + randomNumber).css({ "background-color": "#ffe"});

            history[i] = randomNumber;

I have gotten it running without the timer with just alerts, and I have also gotten the timer to work, but upon trying to integrate the two and have it affect CSS, it won't work.

cornholio
  • 35
  • 4
  • Where does the `e` come from? A timer is not an event handler. If you'll take a look at the console, there's an error message: `ReferenceError: e is not defined.` – Teemu Jan 25 '15 at 08:30
  • if you mean e.which, that's just for the enter key being pressed – cornholio Jan 25 '15 at 08:32
  • It is not, `which` is a property of `event`, which is passed to event handlers, not timed functions. – Teemu Jan 25 '15 at 08:35
  • What do you suggest I do? I got the idea to do that from this http://stackoverflow.com/questions/302122/jquery-event-keypress-which-key-was-pressed – cornholio Jan 25 '15 at 08:36
  • To detect key presses, you've to [attach an event listener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener), like `keydown` or `keypress` to `window` for example. It's not clear to me, what you actually want to achieve, but an event listener is something to start from, when ever you want to detect key presses. – Teemu Jan 25 '15 at 08:47

1 Answers1

0

Try replacing the code

 $("." + randomNumber).css({ "background-color": "#ffe"});

with

  $("." + randomNumber).css({ "backgroundColor": "#ffe"});

jQuery does not accept "-" when entering css property via object

Hemant
  • 1,999
  • 2
  • 12
  • 8