2

I'm trying to make the text field change its color but it doesn't seem to work Here is the code:

<html>
<head>
  <title>   
  This is a title
  </title>

<script type="text/javascript">
    function changeColor()
    {
    alert("bla")
    document.getElemenyById("text1").style.background-color:red;
    }
</script>
</head>

<body>

<form>
<input id="text1" type="text" onkeypress="changeColor()">
</form>


</body>

</html>
  • thank you
1
  • Use backgroundColor instead Commented Sep 7, 2013 at 12:54

4 Answers 4

4

That's a syntax error. You can't use CSS syntax (background-color: red) inside JavaScript.

You want to actually assign a value (the string "red") to a member of the style object called backgroundColor:

...style.backgroundColor = "red";
Sign up to request clarification or add additional context in comments.

Comments

3

Try this:

document.getElementById("text1").style.backgroundColor = "red";

Demo: http://jsfiddle.net/jG95a/

There were four problems in your code:

  • A typo in getElementById() (you had a "y" instead of a "t")
  • background-color is not valid in JS dot notation, you need backgroundColor
  • You need = not :
  • red needs to be a string, "red"

Or to put those last three points another way, the way you had background-color:red is appropriate in a stylesheet, but not in JavaScript.

Comments

2

If using Jquery use CSS() . If Plain Javascript

document.getElementById("text1").style.backgroundColor = "red";

or

document.getElementById("text1").style("backgroundColor":"red"); 

One error is in "getElementById" typo

3 Comments

Did you test that second option?
yeah using jquery we write $("#text1").style("backgroundColor":"red");
No we don't. What I was hinting at is that that is a syntax error. Try it and see. (For it to work with a colon you need to pass an object.)
2

1) most of CSS attributes accessed from JavaScript need to replace all "-" and use rpn style, ie.

background-color becomes backgroundColor,

border-collapse becomes borderCollapse and so on.

2) When manipulating styles in JavaScript one may often need to update multiple attributes at once. A good and elegant method is to use the JavaScript "with" statement :

with(document.getElementById("text1").style) {
    backgroundColor = 'red' ;
    fontWeight = 'bold' ;
    // etc... 
} 

3) the jQuery way is also simple :

$('#text1').css({
    "background-color": "red", 
    "font-weight": "bold"
}) ;

http://api.jquery.com/css/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.