I am currently building a search bar for my application. I have been looking everywhere reading documentations on focusing an input field and I found out that HTML has a built in function ‘autofocus’ but I have not been able to figure out a solution on how to focus on the input field when for example I click on a blank area on the web page.
<input type="text" class="form-control srch-bar" id="myInput" onkeyup="myFunction()" title="Type in a name" autofocus>
2
Answers
I assume that your search bar should have the focus permanently. Even if the user clicks outside, the focus should not be removed. This is basically a very bad user experience and a bad design idea. Nevertheless, I will show you a possible solution.
You have already found the necessary attribute
autofocus
. This will cause your input field to automatically have the focus after the page is loaded. Now you have to prevent that the focus will be removed. You can achieve this with theonblur
event. The onblur event occurs when an element loses his focus. When this event is fired, you just have to set the focus on the input field again.Again, I strongly recommend not to use this implementation. Even if you think it is a solution to your problem, there will be a more useful approach.
I will not give too many explanations as it is extremely simple. I’ve added comments in the code:
I’m a beginner, and using JavaScript I don’t know if this is the better way to do this.