*I want the background colour of a text box to change to lightgreen when the textbox gets focus and its background colour to revert to white when it loses focus. My code works perfectly on localhost and when the browser is Safari.
However, with all the other browsers (Chrome, Edge, Firefox, Opera ) nothing happens. I'm doing something stupid, but what?!
<script>
function test(id)
{
var ctrl_name = id;
document.getElementById('Name').value = ctrl_name;
}
</script>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery
/1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.clickOnMe').blur(function(){
$(this).css('background', 'white' );
});
$('.clickOnMe').mousedown(function(){
$(this).css( 'background', 'lightgreen');
});
});
</script>
and in the textboxes -
onclick="test(this.id)" class="clickOnMe"
No error messages/ Simply won't work except on localhost and Safari.*
This can be done with css
without javascript. Example:
.custom-textarea:focus { background-color: lightgreen; }
<textarea class="custom-textarea">Click on me</textarea>
If you would like to use js
and jQuery
anyway: You can use .focus()
event instead of .mousedown()
.
- This method is a shortcut for
.on( "focus", handler )
in the first and second variations, and.trigger( "focus" )
in the third.- The
focus
event is sent to an element when it gains focus.- Source: api.jquery.com
Example:
$('textarea').focus(function() { $(this).css("background-color","lightgreen"); }); $('textarea').blur(function() { $(this).css("background-color","white"); });
<script src="https://code.jquery.com/jquery-3.4.1.js"></script> <textarea class="custom-textarea">Click on me</textarea>
Or in ES6
$('textarea').focus((e) => $(e.currentTarget).css("background-color","lightgreen")); $('textarea').blur((e) => $(e.currentTarget).css("background-color","white"));
<script src="https://code.jquery.com/jquery-3.4.1.js"></script> <textarea class="custom-textarea">Click on me</textarea>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.