Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Text Field Autofocus in Javascript

Is there a way in Javascript to forcibly disable text field autofocus on page load?

I know of the focus() method, but not how to disable it. My actual problem is that autofocusing in a modal window forces the window to appear with the scrollbar halfway down already and scrolled to the first input field, whereas I would like to disable this entirely.

Thanks!

like image 219
sichinumi Avatar asked Jul 20 '11 17:07

sichinumi


People also ask

How do you Unfocus an element in JavaScript?

Use the blur() method to remove the focus from an element, e.g. input. blur() . If you need to remove the focus from the currently active element without selecting it, call the blur method on the activeElement property - document.

How do I turn off auto focus in CSS?

If you want to remove the focus around a button, you can use the CSS outline property. You need to set the “none” value of the outline property.

What is Textfield autofocus?

The autofocus global attribute is a Boolean attribute indicating that an element should be focused on page load, or when the <dialog> that it is part of is displayed. <input name="q" autofocus /> No more than one element in the document or dialog may have the autofocus attribute.


2 Answers

You can use .blur() ,

var elelist = document.getElementsByTagName("input");
for(var i = 0; i < elelist.length; i++){
    elelist[i].blur();
}

If you want to disable focus on all the textfields,

var elelist = document.getElementsByTagName("input");
for(var i = 0; i < elelist.length; i++){
    elelist[i].addEventListener("focus", function(){
        this.blur();
    });
}
like image 50
Derek 朕會功夫 Avatar answered Oct 03 '22 20:10

Derek 朕會功夫


You can use in jQuery

$(function(){
    $('input').blur();
});
like image 26
Warface Avatar answered Oct 03 '22 20:10

Warface