How to change the background color of the focused element for a few seconds?

Here the code focuses on the second div. Now I want to set the background color for the focused element to a different color for several seconds, and then return to the original color. How to do it?

$(function(){ $("#two").focus(); }); 
 body{color:white;} #fis{height:600px;width: 60px;background-color:red;} #two{height:600px;width: 60px;background-color:green;} #thr{height:600px;width: 60px;background-color:blue;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="fis">hello </div> <div id='two' tabindex='1'>mr </div> <div id='thr'>john </div> 
+5
source share
3 answers

In the following way, you can change the color over a period of time. At first it will turn yellow in a few seconds until it turns green.

 $(function(){ $("#two").focus(); setTimeout(function() { $('#two').css("background-color", "green"); }, 2000); }); 
 body{color:white;} #fis{height:600px;width: 60px;background-color:red;} #two{height:600px;width: 60px;background-color:yellow; transition:background-color 1s ease;} #thr{height:600px;width: 60px;background-color:blue;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="fis">hello </div> <div id='two' tabindex='1'>mr </div> <div id='thr'>john </div> 
+2
source

Here is a solution using setTimeout in the focus event.

 $(function(){ $('div').on('focus', function() { var $this = $(this); $this.addClass('highlight'); setTimeout(function(){ $this.removeClass('highlight'); }, 2000); }) $("#two").focus(); }); 
 body{color:white;} #fis{height:600px;width: 60px;background-color:red;} #two{height:600px;width: 60px;background-color:green;} #thr{height:600px;width: 60px;background-color:blue;} #fis.highlight{background-color:yellow;} #two.highlight{background-color:yellow;} #thr.highlight{background-color:yellow;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="fis">hello </div> <div id='two' tabindex='1'>mr </div> <div id='thr'>john </div> 
+4
source
 $(document).ready(function(){ $("#two").focus(function(){ $(this).css("background-color","green"); setTimeout(function(){ $("#two").css("background-color","yellow"); },1000); }); }); 

try it...

+2
source

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


All Articles