Focus and highlight input control

When the page loads, I want to focus and highlight (border color or change the background color) the input control. How can I do it? This is what I got so far.

<script type="text/javascript"> $(function () { $("#txt1").focus(); }); </script> 
+4
source share
3 answers

Take a look at the CSS :focus selector. And just specify the CSS class, for example:

 #txt1:focus { border-color:red; } 

Since it is not supported by older browsers (IE7 plus some others). You can do this with JS.

 $("#txt1").focus(function(){ $(this).addClass("focused")}); $("#txt1").blur(function(){ $(this).removeClass("focused")}); 

Where focused is defined as follows:

 #txt1.focused { border-color:red; } 

EDIT:

Jquery.focus docs.

 $("#txt1").focus(function(){ $(this).addClass("focused")}); 

The line above simply binds the handler to focus the event and does not change focus or execute it immediately. To get a field focused on page loading, add the following line after it:

 $("#txt1").focus(); 

This parameter will focus on the selected element and start the handler attached earlier. Shorter designations:

 $("#txt1").focus(function(){ $(this).addClass("focused")}).focus(); 

Demo with autofucused element on page load

+5
source

You will have the element focused. You can use the :focus pseudo-selector in CSS to style input as needed:

 #txt1:focus { border: 1px solid #C00; background: #CCC; } 
+1
source

here you can use some css to apply frame color, backgroung color. see below css which changes color when you focus on input

 input:focus { font-family:Verdana, Geneva, sans-serif; border-color:#9ecaed; box-shadow:0 0 5px #9ecaed; } 

enter the css attributes you want to highlight after focusing.

0
source

Source: https://habr.com/ru/post/1444142/


All Articles