Alistair Lee
Alistair Lee

Reputation: 81

jquery bind event depends on situation

I want to know about jquery. Can we bind event depending on the variables / situation / another event?

for example, If the var X is 0, a div could be clicked, meanwhile if the var X is 1, the same div could not be clicked.

I made this jsfiddle http://jsfiddle.net/hKkVD/4/ .of course it's not working, but you get the idea.

EDIT : Sorry I made some confusion. I need the variable to be checked BEFORE the click event is triggered.

So basically the variable is to check (and toggle) whether the event is permitted or not. Thanks

Upvotes: 1

Views: 196

Answers (4)

cchana
cchana

Reputation: 4990

Your JavaScript wasn't far off, but for me (in Chrome anyway), the alert keyword seems to have caused problems. Check out my updated code here http://jsfiddle.net/cchana/6UeeG/

var alertMe = 0;

$("#toggle").click(function(){
   if (alertMe == 0){
       $("#toggle").text('turn alert off');
       alertMe = 1;
   }   
   else {
       $("#toggle").text('turn alert on');
       alertMe = 0;                
   }       
});

$("#clickme").click(function() {
    if(alertMe == 1) {
        alert("hey i could be clicked");
    }
});

It makes sense to do the check inside the function, rather than define two separate function calls as only the first condition that is met will be bound to the element.

Upvotes: 2

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

First, don't use alert as a variable name. That will deny access to the native alert() method.

Also, As written your code tests the value of alert before putting the click handler in place. I expect that what you want is to test the value of alert inside a click handler.

var b_alert = false;//boolean_alert
$("#toggle").click(function() {
    b_alert = !b_alert;
    $(this).text(b_alert ? 'turn alert off' : 'turn alert on');
});

$("#clickme").click(function() {
    if (b_alert) {
        alert('Hey I could be clicked!');
    }
    else {
        //do nothing
    }
});

See fiddle

Upvotes: 0

gion_13
gion_13

Reputation: 41533

If you used any other name for your flag your code would have worked. The thing is that ny defining a flag 'alert', you are overwriting the initial alert function. So all you have to do is change the name of your flag or specifically call the global function like this : 'window.alert()'. Here's a fiddle with the flag name changed : http://jsfiddle.net/hKkVD/2/

Upvotes: 0

erimerturk
erimerturk

Reputation: 4288

i am not sure if you looking for something like this but you can check this url.I updated your demo.

http://jsfiddle.net/hKkVD/1/

Upvotes: 0

Related Questions