1

I've found lots of examples on this topic.. however, I do not fully understand. Does my logic seem correct? I have a div as button (class of .myClass) and I don't want it clickable unless myCount >= 1.

// I want to unbind if myCount == 0
if ( myCount == 0) {
 $('.myClass').unbind().css("opacity","0.5");
} else {
 // **would this rebind?**
 $('.myClass').click(callMyFunction);
}
user1040259
  • 6,369
  • 13
  • 44
  • 62

3 Answers3

2

I'm not sure exactly what you're trying to achieve, but .unbind() removes all handlers attached to the element when called with no arguments. Therefore, $('.myClass').unbind() removes all event handlers attached to the elements with a class of .myClass. Since you only seem to be adding one event handler, click, it would be better to only unbind the click handler, like so: $('.myClass').unbind('click'). This way you won't be confused why other events are being unbinded if you add additional events later on.

jeff
  • 8,300
  • 2
  • 31
  • 43
2

click(callMyFunction) is shorthand for .bind("click", callMyFunction) or .on("click", callMyFunction).

To bind use on() to unbind use off(). Those are the preferred methods since jQuery 1.7. If you are using an older version use bind(), unbind(), or delegate() and undelegate()

$('.myClass').off('click')

and to bind

$('.myClass').on('click', function(){});

As mentioned in another post, using namespaces is an additional way to categorize your events such as click.mynamespace for example.

See this post for much more detail on the different available binding methods and which were introduced when and have replaced what and why.

Some more resources:

Community
  • 1
  • 1
Nope
  • 22,147
  • 7
  • 47
  • 72
2

You could use namespaced events, with on(). bind() has been deprecated.

var foo = function () { ... }

if (myCount)
  $('.myclass').on('click.foo', foo)
else
  $('.myclass').off('.foo')
elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • 1
    Nice one. Just caution with `.foo` on the `off()`. I think that will unbind all events associated with the namespace. Might be better to use `$('.myclass').off('click.foo')` unless you want to unbind all off course. – Nope Aug 02 '12 at 19:41