-4

The following code's else part isnt working, i.e. click is not getting enabled.

if

    $("#section1").click(function(event){
        return false;
    });

else

    $("#section1").click(function(event){
        return true;
    });

So basically, I want to remove the click functionality over a certain div section, which is working fine but while returning the click functionality back it is not working. Any suggestions?

MacMac
  • 30,042
  • 53
  • 142
  • 217
Rohit Sharma
  • 103
  • 1
  • 3
  • 9
  • 4
    your code isn't complete. You've missed the conditional statement on the `if`. – zzzzBov Nov 18 '11 at 14:35
  • @locrizak pretty crap psuedo code if it doesn't even mention what the condition should be ;) – Rory McCrossan Nov 18 '11 at 14:46
  • @locrizak, "pseudo code" is the correct spelling, and even pseudo code can be blatantly incorrect. You can't expect to ask a question on StackOverflow to debug an issue by posting the pseudo code. At some point *real* code needs to be used to solve *real* problems. Also, don't ever call me "brah". – zzzzBov Nov 18 '11 at 14:47
  • Im just saying in this situation it doesn;t matter what the conditions are. He wants to know how to add and remove an event listener in an if statement. And my bad I knoew it was spelt like that as well – locrizak Nov 18 '11 at 15:10

4 Answers4

2

You probably want to remove the click event rather than add another one that returns true.

Try (instead of the else bit):

$('#section1').unbind('click');
Richard Dalton
  • 34,315
  • 6
  • 69
  • 88
  • Correct, and this elaborates on this point a bit more: http://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery – kasimir Nov 18 '11 at 14:36
1

You need to unbind the click event. The reason being is if say this block of code gets called 3 times, that is putting 3 event handlers on #selection1 and each time it is clicked all three of those functions are called.

if
    $("#section1").unbind('click');

else
    $("#section1").bind('click', function(event){
        return true;
    });
locrizak
  • 11,687
  • 11
  • 56
  • 80
1
$("#section1").click(function(event){
        return false;
    });

will disable its functionality

$("#section1").unbind('click')

will remove attached click event and let it do its work

Utku Yıldırım
  • 2,197
  • 14
  • 20
1
$("#section1").click(function(event){
    return false;
});

This will disable the click event from happening, whereas true continues the click event, I'm not sure what you want to achieve but you can use bind to attach an event, like so:

$("#section1").bind('click', function(){
    alert('You clicked on it');
});

But to remove a click event, you would use the opposite; unbind.

MacMac
  • 30,042
  • 53
  • 142
  • 217