简体   繁体   中英

Javascript else condition not triggering

I am trying to do a basic javascript/jquery animation. Basically, a div that is hidden under normal view, should come into view when clicking a button.

The problem I have is in the condition (the if else statement).

Here is the code that I am using.

$(document).ready(function () {
    animationClick('#animateThis', '#someElement', '#startHere');
});

function animationClick(element, secondElement, elementToBeClicked) {
    element = $(element);
    elementToBeClicked = $(elementToBeClicked);
    secondElement = $(secondElement);
    var state = 0;
    var containerWidth = $('#container').width();
    elementToBeClicked.on("click", function () {
        if(state == 0) {
            secondElement.animate({
                top: '27%',
            }, 500);
            element.animate({
                left: '0%',
            }, 500);
            elementToBeClicked.html("Hide");
            state = 1;
        } else {
            alert('hehehe');
        }
    })
};

So, basically, this is what happens. The whole function is put into document.ready. When I click on the button (which this function is bonded to),the if statement returns true , and the code gets executed. It also sets the state to 1 .

After the state gets set to 1 , the else if statement should come into action and show an alert("hehehe") , but it does not.

Can anyone give me some kind of an advice? What am I doing wrong ?

You have already bind a "click" event to "elementToBeClicked" at the first if statement. Try to unbind it at the end of the if statement and then see what happens, but generally in order to only check that the else is executing, just put the alert out of the click event.

your variable "state" is local to the function. That is why on subsequent calls of the function it is always 0. initialize the variable outside of the function.

I think the problem is that when you compare variables and zero in if statement you should use three ===. Like this : if (state === 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM