Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Chrome Javascript Link Bug

When clicking a link in google chrome the focus event fails to fire. All other browsers fire the focus event for links.

<a href=# onfocus="console.log('focus')">Link</a>

I do not want to attach the event onmousedown, but onfocus.

Anyone have an idea for a workaround.

EDIT:

I would definitely consider this a bug because all other focusable elements trigger focus on click.

Even non focusable elements with a tabindex trigger focus on click in google chrome.

<div tabindex="-1" onfocus="console.log('focus')">div</div>

I can't attach to both click and focus because then onclick, other browsers would call the function twice. I can't detect this functionality because it requires user interaction, and I won't do user agent string detection, because well its wrong.

Using this html:

<a href=# onfocus="console.log('focus')" onmousedown="console.log('mousedown')">Link</a>

Is they any way to invalidate the second onmousedown call to prevent the function being called twice in non google browsers.

EDIT 2:

After some further testing <input type=radio> also fails to call focus in google chrome. Why in the world is google chrome like this, while Opera, IE and firefox are all okay. What is crazy is that the mobile webkit browser even triggers focus on links when I tried it on my Android device.

like image 824
Lime Avatar asked Jun 19 '11 19:06

Lime


2 Answers

That actually works just fine, except that the focus event isn't triggered simply by clicking on the link (try tabbing and you'll see the event firing). I don't think it's a bug, why not just safe guard and use both?

like image 156
John Leidegren Avatar answered Sep 18 '22 15:09

John Leidegren


One work around you could do to avoid the double focus events from popping on the working browsers while still getting the focus event to pop on Chrome, is to on a click event check whether anything has focus on the page, and if not, then trigger the focus event.

With jQuery it could be done like this:

$('a').click(function(e){
     if(!$('*:focus').length) $(this).trigger('focus');         
});

example: http://jsfiddle.net/niklasvh/qmcUt/

like image 20
Niklas Avatar answered Sep 19 '22 15:09

Niklas