views:

322

answers:

3

I met one troublesome web page whose structure is complicated. If one DIV is clicked by mouse, everything is OK. However, if it is focus-ed by javascript(i.e. divElement.focus). The layout turns to messy. This only happens in IE7/8.

So, is there any difference between click-to-focus and focus-by-javascript in IE?

+3  A: 

Firing a Javascript focus event does not fire a click event. Without seeing the relevant code, I'm led to guess that some click handler is in place that is not being called in the case where you fire a focus event.

You might try, instead, firing a click:

var clickEvent;
if(document.createEvent) {
    clickEvent = document.createEvent('click');
    clickEvent.initMouseEvent('click');
    divElement.dispatchEvent(clickEvent);
} else {
    // Semi-pseudocode for IE, not tested, consult documentation if it fails
    clickEvent = document.createEventObject();
    divElement.fireEvent('onclick');
}

Or if you're into the jQuery thing:

$(divElement).click();

There's similar solutions for Prototype as well (search for Event.simulate).

eyelidlessness
Actually, there is no other click event.The focus is invoked in other element's onbeforedeactivated event handler.
Morgan Cheng
Morgan Cheng, I may be wrong but I doubt anyone can give you a more definite answer without seeing the relevant code.
eyelidlessness
A: 

The definition of the Focus action is to bring the input (keyboard or mouse) to a certain element, usually an input field. When an element gains focus, an OnFocus event is fired. When it loses focus, an OnBlur event is fired.

What you usually get by clicking is the OnClick event, which is not necessarily related to the above two.

MaxVT
A: 

This only happens in IE7/8.

Hmm, then I'm sure it's an IE related bug. Not surprising. If there is legitimate Javascript events involved, then they should fire uniformly across all browsers.