Mariraj Sankar
Mariraj Sankar

Reputation: 69

How do I change Background color of textbox when onfocus?

I tried this code but its not working; when I on-focus textbox it shows an error:

function ChangeBgColor(obj, evt) 
 { 
        if(evt.type=="focus") 
            style.background ="lightgrey";
        else if(evt.type=="blur") 
        {
           style.background="white";
        }          
 }

Upvotes: 1

Views: 24632

Answers (5)

epascarello
epascarello

Reputation: 207547

What is style? You have not defined it anywhere in your code above:

function ChangeBgColor(obj, evt) 
{ 
    if(evt.type=="focus") 
        style.background ="lightgrey";  //<--what is style?
    else if(evt.type=="blur") 
    {
        style.background="white";
    }          
}

I am guessing that you wanted something like

obj.style.background ="lightgrey";

And in the code above, simplified

function ChangeBgColor(obj, evt) 
{ 
    obj.style.background = (evt.type=="focus") ? "lightgrey" : "white";
}

The best answer is to use pure CSS.

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123417

JavaScript is not necessary for this task, just use css (:focus is supported since IE8)

https://developer.mozilla.org/en-US/docs/CSS/:focus

input { background: lightgray; }
input:focus { background: white; }

Only if this effect is absolutely needed also on < IE8 then JS (properly wrapped in a conditional comment) can be used, but even in this scenario it is recommended to keep off style from logic: e.g.

function ChangeBgColor(obj, evt) { 
    obj.className = (evt.type === "focus") ? "focus" : "";
}

and use this style

 input { background: lightgray; }

 input:focus, 
 input.focus { background: white; }

Upvotes: 4

Tung Nguyen
Tung Nguyen

Reputation: 11

Yep, you should try this javascript code to change the background color for this element:

  var obj = document.getElementById("yourId");
  obj.onfocus = function() {
    obj.style.backgroundColor = 'red';
  }

Now you can change whatever color you want

Upvotes: 1

Mooseman
Mooseman

Reputation: 18891

obj.style.background = "#C8C8C8";

Upvotes: 2

Ivo Pereira
Ivo Pereira

Reputation: 3500

Try doing it with jQuery.

$('#div').on('focus', function() {
    $(this).css({background:'blue'});
});

Upvotes: 0

Related Questions