Artur Udod
Artur Udod

Reputation: 4743

Focus button from javascript withour clicking it

I call

element.focus();

Where element is HTMLInputElement of type=button. But then the browser clicks the button! That's in mozilla and chrome.

How do i highlight the button with selection, but not initiate the click event?

Upvotes: 1

Views: 3671

Answers (2)

Artur Udod
Artur Udod

Reputation: 4743

Well, i've identified the reason. I was handling the onkeydown event for Enter key. The solution is to use e.preventDefault();

function ConvertEnterToTab(s, e, numSkipElements) {
            var keyCode = e.keyCode || e.htmlEvent.keyCode;
            if (keyCode === 13) {
                var tabIndex = s.tabIndex || s.inputElement.tabIndex;
                if (numSkipElements == undefined) {
                    numSkipElements = 0;
                }

                var nextElement = FindNextElementByTabIndex(tabIndex + numSkipElements);
                if (nextElement != undefined) {
                    nextElement.focus();
                    return e.preventDefault ? e.preventDefault() : e.htmlEvent.preventDefault(); // this is the solution
                }
            }
        }

        function FindNextElementByTabIndex(currentTabIndex, maxTabIndex) {
            if (maxTabIndex == undefined) {
                maxTabIndex = 100;
            }

            var tempIndex = currentTabIndex + 1;
            while (!$('[tabindex='+ tempIndex+ ']')[0] || tempIndex === maxTabIndex) {
                tempIndex++;
            }

            return $('[tabindex=' + tempIndex + ']')[0];
        }

Upvotes: 1

Misha Reyzlin
Misha Reyzlin

Reputation: 13906

No .focus() doesn't click the button or submits the form: http://jsbin.com/onirac/1/edit

It does exactly what you want it to.

Upvotes: 1

Related Questions