Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple concurrent event handling in jQuery

Tags:

jquery

I am attempting to handle multiple concurrent events using jQuery but I am having problems finely managing when the events are fired.

<html>
  <head>
  <title></title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  </head>
  <body>

    <div id="edit" contenteditable="true">Edit some content</div>
    <button id="button" type="button">Click the button</button>

    <script type="text/javascript">
      $(document).ready(function () {
        $('#button').click(function (e) {
          alert('I have been clicked.');
        });
        $('#edit').blur(function (e) {
          alert('I have been edited.')
        });
      });
    </script>

  </body>
</html>

What I wish to achieve is for the content of the DIV to be edited by a user and when the button is clicked, for that event to be raised before the blur event on the DIV. It may be the case that the button is never clicked in which case the blur event may fire on its own. As you can see using the code above, once you edit the content and click the button only the blur event is fired.

Please can someone advise how I may achieve the desired functionality?

like image 575
wolfyuk Avatar asked Dec 05 '25 16:12

wolfyuk


1 Answers

One — admittingly very hacky — way would look like this:

$(document).ready(function() {
    var buttonClicked = false;
    $('#button').bind('click', function(e) {
        buttonClicked = true;
        alert('I have been clicked.');
    });
    $('#edit').bind('blur', function(e) {
        setTimeout(function() {
            if (!buttonClicked) alert('I have been edited.');
            buttonClicked = false;
        }, 100);

    });
});

This example doesn't prevent the firing of the event, though. It only handles the callback.

Here it is working: http://jsfiddle.net/Dp6b5/1/ You can adjust the timeout delay and don't necessarily have to use bind in this case either.

It's an interesting question, but I don't see any "proper" way to handle this atm., since the blur event is de facto fired before the click. Maybe someone else has a better idea I can't see atm..

like image 140
polarblau Avatar answered Dec 08 '25 07:12

polarblau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!