简体   繁体   中英

OnFocus/OnBlur events not registered

Guys i feel really stupid asking for this, but remarkably im banging my head for an hour already. Here is the code:

<div id="img1" onfocus="alert('test');" onblur="alert('test');">
 <img id="image1" name="image1" src="image1.jpg"  alt="Pciture 1">&nbsp;
</div>

Both events ( Focus / Blur ) should call a function, but even this simple test ( alert ) doesn't work. Both of these tags are in the body section, tried changing the DOCTYPE definition - no effect.

W3 spew an error:

there is no attribute "ONFOCUS"

My main goal is to use the events directly on the img tags, but for some reason that doesn't work either.

by default div is not an interactive element so it does not gain focus at all, try to add an tabindex attribute to div such as tabindex="1" then it will be focusable

<div> and <img> don't normally have a focus or blur event, but you can try setting a tabindex on it as a workaround. It's a bit strange though.

http://www.quirksmode.org/dom/events/blurfocus.html

The onfocus event occurs when an element receives focus either by the pointing device or by tabbing navigation. This attribute may be used with the following elements: A, AREA, LABEL, INPUT, SELECT, TEXTAREA, and BUTTON.

Source : w3c HTML4 spec

Neither a div nor an img can receive or lose focus, these are not interactive elements. You can enable them getting focus with setting tabindex .

there are nodes which are not focusable by default, like div, span, table, etc, but can receive focus if tabindex is applied

Source : http://nemisj.com/focusable/

The W3C validator is correct, the div tag does not have onfocus or onblur as attributes. See here: http://www.w3schools.com/tags/tag_DIV.asp

Maybe the events onmouseover and onmouseout are what you're looking for

You should not use inline JS for your event handlers. Use unobtrusive javascript instead.

Div Tag has no onfocus and onblur event. Please try mouseover,mouseout etc..

You can stop banging your head, first it hurts, secondly you can't ues onfocus or onblur on div elements.

Check da link: W3C

What are you trying to achieve?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM