1

I have a button and I want my variable click to be set to true when the button is clicked, and false when the button is clicked again (I want toggle functionality).

When click == true, I want it to output clicked into the console and when click == false I want it to output not clicked.

var click = false

Here's my toggle function:

$('.button').toggle(
    function(){
        click = true;
        $('.bmw').show();

    }, function() {
        click = false;
        $('.bmw').hide();

    });

And what I want it to do:

if(click = true) {
    console.log('clicked');
} else {
    console.log('not clicked');
}

When I load the page the console shows not clicked but when I press the button it doesn't switch to true. The bmw objects** .bmw do however show and hide when I toggle the button so that seems to be working fine.

What am I doing wrong?

Bojangles
  • 99,427
  • 50
  • 170
  • 208
KriSp
  • 13
  • 1
  • 3

1 Answers1

4

You are assigning not comparing the value of click

You should be doing this with == not =

if(click == true) {
    console.log('clicked');
} else {
    console.log('not clicked');
}

However you do not even need to use if(click == true). You can in fact just use if(click) instead.

EDIT: From what we discussed in the comments it looks like you were calling the if statement only once when the code was first run, not everytime you toggled. I suggest creating a seperate function with the if statement inside, then calling this method in both parts of the toggle.

Jon Taylor
  • 7,865
  • 5
  • 30
  • 55
  • This may not be your only problem however it is a problem in your code. Once you fix and test this you will be able to see if there are other problems with your code. – Jon Taylor Jul 11 '12 at 12:18
  • Thanks for answering so fast. So I tried that and unfortunately it doesn't seem to be the only problem.. it still doesn't work. Thanks though! – KriSp Jul 11 '12 at 12:33
  • Where do you have your if statement? When is it called? Are you actually calling it everytime you toggle? – Jon Taylor Jul 11 '12 at 12:36
  • Do I have to call it everytime I toggle? I didn't know that. Right now I'm calling it after the toggle function. So am I supposed to move it into the toggle function? – KriSp Jul 11 '12 at 13:23
  • @KristinaSaskia Yes you will need to call it everytime you toggle since it is a check to see if the variable is at this moment true or false. I would create a seperate function witht he if statement in and call this from within the toggle. – Jon Taylor Jul 11 '12 at 13:24
  • I see. Do I call it twice in the toggle (for both clicked and unclicked)? – KriSp Jul 11 '12 at 13:27
  • Yes you will need to call it once in each section of the toggle. – Jon Taylor Jul 11 '12 at 13:40
  • @KristinaSaskia great, I will edit my answer slightly to add what we discussed. If it fixed your problem just click the accept next tot he answer. – Jon Taylor Jul 11 '12 at 13:51