Change background color of input field using JS

I'm trying to change background color of an input field when focusing in JS, when its not in focus it should just be a white background color.

I've tried this code, but get an error on it, so I'm not sure what i'm doing wrong.

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

            <fieldset>
                <legend>Personlige oplysninger</legend>

                <div>
                    <label for="navn">Udfyld dit fornavn:</label>
                    <input type="text" name="navn" class="navn" id="navn" value="" onclick="navn()" placeholder="Dit fornavn" />*
                    <span id="obsnavn" class="alert"></span>
                </div>

                <input type="button" value="Send" id="send" />

            </fieldset>

        </form>

Upvotes: 2

Views: 8991

Answers (2)

Guillaume Georges
Guillaume Georges

Reputation: 4020

There are a few issues in your code :

  • your handler function declares an obj parameter as the first parameter. When an event is fired, the first element declared in the handler function is a reference to the event object.
  • you're trying to react to blur or focus, but you're using onclick on your HTML tag.
  • to change your element's background color, you need to modify its style object and, in this style object, the backgroundColor property (the JavaScript equivalent of the background-color CSS property).

Here's a solution involving addEventListener function. It allows you to attach the same listener to both events : blur and focus.

var element = document.getElementById("navn");
element.addEventListener("focus", handler);
element.addEventListener("blur", handler);

function handler(evt) {
    if (evt.type == "focus")
        evt.target.style.backgroundColor = "yellow"; //<--what is style?
    else if (evt.type == "blur") {
        evt.target.style.backgroundColor = "white";
    }
}
<form>
   <fieldset>
      <legend>Personlige oplysninger</legend>
      <div>
         <label for="navn">Udfyld dit fornavn:</label>
         <input type="text" name="navn" class="navn" id="navn" value="" placeholder="Dit fornavn" />*
         <span id="obsnavn" class="alert"></span>
      </div>
      <input type="button" value="Send" id="send" />
   </fieldset>
</form>

Upvotes: 4

Evan DELEUSE
Evan DELEUSE

Reputation: 1

Because your function as parameter so when you call onclick="navn()" without params it can't work

call it like this :

  onblur="blur(this)"  onfocus="focus(this)"

  function blur(obj) {
                obj.style.backgroundColor == "white";
        }
  function focus(obj) {
                obj.style.backgroundColor = "yellow";
        }

Upvotes: 0

Related Questions