Jump to content

Recommended Posts

ok so I've checked my syntax and everywhere I checks says I'm right so I thought I'd ask one of you folks.

So load this up and click the little black <div>, it should deincrement to a max of -4 and then reset to 0 but it just deincrements without end.

 

http://jsfiddle.net/xyLfP/

Link to comment
https://forums.phpfreaks.com/topic/259823-if-not-working-for-this-noob/
Share on other sites

your if/else is done initially when the page is loaded and index is 0

 

try this instead..

 

$(document).ready(function() {
    var index = 0;
    $("#left-button").click(function() {
        if(index > -5)
            index--;
        else
            index = 0;
        $("#index").html("<span>" + index + "</span>");
    });       
});

to clarify the problem with your original code:

$(document).ready(function() {
    var index = 0;
    if (index > -5) {
        $("#left-button").click(function() {
            index--;
            $("#index").html("<span>" + index + "</span>");
        });
    }
    else if(index == -5){
        $("#left-button").click(function() {
            index = 0;
            $("#index").html("<span>" + index + "</span>");
        });
    }
   
        
});​

 

this was basically saying to do this when the page was loaded..

 

index = 0

if(index > -5)

  initialize the function that listens for a click on left-button and decrements index when clicked

else

  initialize the function that listens for a click on left-button and sets index to 0 when clicked

syntax is not different. you can wrap in curly brackets if that is what you mean, it's just unnecessary if there is only 1 line in the block.

 

your problem wasn't syntax, it was the logic.

 

you didnt have a function that did something differently depending on a value. you had two separate functions with the same object and trigger, which function was basically created and used depended on what the value of index was the first time through, on document ready... as index was set to 0 right before this, it always used the first one.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.