3

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?

1
  • As a sidenote: blur() is not everywhere supported for <div> elements. Older browsers support this event only for input elements. Commented Jan 19, 2011 at 11:36

1 Answer 1

2

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..

Sign up to request clarification or add additional context in comments.

3 Comments

You need to also reset buttonClicked to false in the blur conditional, but otherwise though hacky this works. +
Very true — I'm updating the example. Cheers!
Thanks, that should do the trick if there is no neater way to deal with the issue. An 'else' case for when buttonClicked is true within the blur handler also lets me manage the case when both the blur and click events were raised.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.