3

By pressing the first button, you will animate the margin-left of the second one, by pressing the second one, you unbind the click event from the first one, but I want lets say a third button to bind the click event back to the first one.

Looking for a simple solution of course!

This is what the code looks like:

<div class="button"><a href="http://www.google.com">something</a></div>
<div class="button2"><a href="http://www.google.com">something2</a></div>
<div class="button3"><a href="http://www.google.com">something3</a></div>

​(function(){
    $('.button a').on('click', function(e){
         e.preventDefault();
        $('.button2').animate({'margin-left': '+=2'}, 100);       
    })

    $('.button2').on('click', function(e){
         e.preventDefault();
         $('.button a').unbind('click');       
    })

    $('.button3').on('click', function(e){
         e.preventDefault();
         $('.button a').bind('click');       
    })

})();​

and you can mess around with it here

akjoshi
  • 15,374
  • 13
  • 103
  • 121
  • I would bind everything and leave them bound. Handle activity with conditional logic in the event handlers. – Brad Nov 23 '12 at 06:47

1 Answers1

2

You can actually use named functions in .on(). What this means is that you can define a function marginFunc(), and then bind it to the click using

function marginFunc() {
 ...
}

$(someElement).on('click', marginFunc);

Then once you are done, you can unbind it using either .unbind('click', marginFunc) or .off('click', marginFunc).
Afterwards, you can rebind in the same fashion as you did at the beginning.

Working jsfiddle here.

rosshamish
  • 1,160
  • 12
  • 15