Thakur Saksham Chauhan
Thakur Saksham Chauhan

Reputation: 186

How to change style of an input with javascript?

I want to give a

-webkit-box-shadow:inset 0 0 5px black;

property to a text box as one focuses on it.

For example, here the background-color is being changed, but I want box-shadow instead.

<script>
function myFunction(x)
{
x.style.background="yellow";
}
</script>

and the HTML

<input type="text" onfocus="myFunction(this)">

Upvotes: 0

Views: 439

Answers (3)

Dan Davies Brackett
Dan Davies Brackett

Reputation: 10071

Instead of using JS for this, use the CSS pseudo-class :focus:

input[type="text"]:focus
{
    -webkit-box-shadow:inset 0 0 5px black;
    box-shadow:inset 0 0 5px black;
}

That way, the textbox will get the shadow when the user tabs into it, or clicks it, or whatever - and the styles will properly go away when they leave, and so on.

Remember to use the unprefixed version of the box-shadow style as well.

Upvotes: 0

hop
hop

Reputation: 2558

Define css classes, and you can easily switch them as needed.

<script>
function myFunction(x)
{
x.style.className="yourcssclass";
}
</script>

Upvotes: 0

Michael
Michael

Reputation: 7092

Why not use :focus in CSS?

http://jsfiddle.net/VjLKV/

input {
    border: 1px solid black;
}

input:focus {
    outline: none;
    border: 1px solid black;
    -webkit-box-shadow:inset 0 0 5px black;
}

Upvotes: 3

Related Questions