user1472878
user1472878

Reputation:

JQUERY if :last:visible

if( $("div:last").is(":visible") ) {
    $("p").css("color", "red");
}

why the script don't work correctly?

http://jsfiddle.net/8Rrm2/8/

Upvotes: 0

Views: 124

Answers (1)

Nick
Nick

Reputation: 9154

The script only checks if its visible at the time of running. It doesn't check if it is ever visible. So when the user uses the right arrow key to make it visible, the script has already passed and it remains not-red. You would have to move that logic into your event handler.

Here is a working fiddle. All I did was cut and paste your logic.

Now, every time the user presses an arrow key, it updates the button and changes the color appropriately.

Also, just FYI: KnockoutJS has some amazing tools for model-binding. With almost no scripting, you can have a model and view-model automatically update each other. The arrow key updates your view-model value, which in turn automatically creates changes in your view. It's really worth looking into, and their tutorials are quite fun.

Here is an example of your script, modified to work with Knockout, in case you're curious. In this example, its not a ton less code, but I do think its a little cleaner to read and to handle "exceptional cases". For example, if you wanted it to be red on values 2, 5, and 7, it just requires changing the one function called iAmRed.

Upvotes: 1

Related Questions