Cannot focus input using javascript in IE11

I cannot get IE11 to focus the input element after inserting it into the DOM. The item will not receive text input after focusing, but its placeholder text is no longer displayed. The element is created by React, and I access it through the React refs object in componentDidMount :

 componentDidMount() { this.refs.input.getDOMNode().focus(); } 

I tried to add a little delay using setTimeout :

 componentDidMount() { setTimeout(() => this.refs.input.getDOMNode().focus(), 10); } 

I also tried adding tabIndex of "1" to the tab.

In case this is useful, here is the JSX rendering:

 <div style={style}> <div style={labelStyle}>Enter a name to begin.</div> <form onSubmit={this.submit} style={formStyle}> <input tabIndex="1" ref="input" value={this.state.username} onChange={this.updateUsername} placeholder="New User Name" style={inputStyle} /> <button {...this.getBrowserStateEvents()} style={this.buildStyles(buttonStyle)}>Create</button> </form> </div> 

Is there any trick to focus on IE11 that I don't know about?

+5
source share
3 answers

The problem was that a violation was fixed in IE11 when the css -ms-user-select: none property is applied to the input. So by changing:

 * { -ms-user-select: none; } 

in

 *:not(input) { -ms-user-select: none; } 

I was able to solve the problem. Here is the code to reproduce the problem: http://codepen.io/anon/pen/yNrJZz

+7
source

I don't think your problem comes from the focus () function, I think this comes from the selector.

To prove this, I just opened my IE11 and tried to focus the SO search in the upper right corner of the page using the following command:

 document.getElementById('search')[0].focus() 

So, just open your IE console (F12) and enter it, it should focus the search input. If so, then the problem comes from a selector that is not an input, as you think.

It works on my IE 11.0.9600.17905

+2
source

As stated in fooobar.com/questions/1602284 / ... , running element.focus() works in IE11 when the css -ms-user-select: none property is set. Workaround may be

 element.style['-ms-user-select'] = 'auto'; element.focus() element.style['-ms-user-select'] = ''; 

Doesn't work in IE: https://codepen.io/macjohnny-zh/details/WPXWvy
(Code: https://codepen.io/macjohnny-zh/pen/WPXWvy )

Works in IE too: https://codepen.io/macjohnny-zh/details/LqOvbZ
(Code: https://codepen.io/macjohnny-zh/pen/LqOvbZ )

0
source

All Articles