Reputation: 97
Hey I'm having trouble reassigning a variable in my javascript/jquery code upon clicking a certain html element, is this valid?
var secret = false; /* assigning boolean */
$('#facebook2').click(function() { /*reassigning "secret" to true on click*/
secret = true;
$('#link-secret').attr('id', 'link-secret2');
});
if (secret == true) { /* should only work if "secret" is true */
$("#twitter2").click(function(){
$("body").css("background-color","yellow");
});
}
I've tried moving the initial "secret" value in and out of the $(document).ready tags to no avail. Am I missing something very obvious here?
Thanks for any help.
edit: Thanks for the quick answer, could anyone explain why this part of my code doesn't work?
$( "#link-secret" ).hover(function() {
$(".top-left-circle").addClass("circle-dupe");
$("#speech-bubble1, #speech-bubble2, #speech-bubblex, #speech-bubblex2, #speech-arrow" ).hide("250");
if (secret == false){
setTimeout(function() {
$( "#speech-bubblex, #speech-arrow" ).stop().show("slow");
}, 500);
} else {
setTimeout(function() {
$( "#speech-bubblex2, #speech-arrow" ).stop().show("slow");
}, 500);
}
setTimeout(function() {
$( "#speech-bubblex, speech-bubblex2, #speech-arrow" ).hide(2000);
}, 5000);
},
function() {
$(".top-left-circle").removeClass("circle-dupe")}
);
If secret is false both parts of the if/else statement execute and if it's true neither does.
Upvotes: 0
Views: 33
Reputation: 512
The issue is that your click handler is not being assigned to begin with because secret is false. Instead, assign the handler, and then only execute the color change if secret is true:
var secret = false; /* assigning boolean */
$('#facebook2').click(function() { /*reassigning "secret" to true on click*/
secret = true;
$('#link-secret').attr('id', 'link-secret2');
});
$("#twitter2").click(function(){
if (secret == true)
$("body").css("background-color","yellow");
});
Upvotes: 4
Reputation: 12213
The assignment secret = true;
occurs only when the click event handler is called. Your test if (secret == true)
occurs immediately after the handler is registered, and long before the click event occurs. You need to put that logic in a function and call it from your click event handler so that it runs after the click event occurs.
Upvotes: 0
Reputation: 55613
You code will only assign the click handler if secret
is true, which it isn't on page load. What you probably want is to change the background color when secret
is true:
$("#twitter2").click(function(){
if(secret) { $("body").css("background-color","yellow"); }
});
Upvotes: 3