Skip to content

Instantly share code, notes, and snippets.

@jamesarosen
Created July 6, 2015 22:13
Show Gist options
  • Select an option

  • Save jamesarosen/d42e20185a814d832449 to your computer and use it in GitHub Desktop.

Select an option

Save jamesarosen/d42e20185a814d832449 to your computer and use it in GitHub Desktop.
jQuery Focuses on Second Call

I'm trying to test some code that involves focus and blur handlers using event delegation. $(...).focus() doesn't work, but $(...).focus().focus() does!

The tests pass fine on PhantomJS and Safari, but fail on Chrome and Firefox. (No, I've never seen that happen before either!)

Here's a simple reproduction:

$('body').append("<div class='my-container'><input /></div>");
var $div = $('.my-container');
$div.on('focus', 'input', function(e) {
  console.log('focus', e.target);
});
$div.find('input').focus(); // nothing logged
$div.find('input').focus(); // console logs
$div.find('input').focus(); // console logs again!

I'm running on jQuery 1.11, which happens to be what GitHub currently uses, so you can test this out by opening up a console on this very page. I haven't been able to replicate it in a JSBin. It seems isolated to console / programmatic driving.

I know that focus and blur don't bubble like normal events. (See http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html) But what surprises me is that calling it twice does work. Why would all subsequent ones bubble properly?

@jamesarosen
Copy link
Author

@jamesarosen
Copy link
Author

Also odd: if I put only up to the first .focus() call in the console, then click on the page, the handler fires.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment