hugolcouto
hugolcouto

Reputation: 87

Change color using querySelector

I'm following a Javascript tutorial using a book. The exercise is change the background color in a <input type="search"> using document.querySelector. When I try to search something with no text in the search box, the background from <input> changes to red. I did it using onsubmit and some conditional. But in the next part, it must returns to white bckground using onfocus and I'm not getting.

The code that I tried is

document.querySelector('#form-busca').onsubmit = function() {
    if (document.querySelector('#q').value == '') {
        document.querySelector('#q').style.background = 'red';
        return false;
    }
}

document.querySelector('#form-busca').onfocus = function() {
    document.querySelector('#q').style.background = 'white';
}

Can someone help me? Thanks a lot!

Upvotes: 8

Views: 39732

Answers (4)

shamlan khaled
shamlan khaled

Reputation: 201

Try the following code:

// select
var h1 = document.querySelector("h1");
// manipulate
h1.style.color = "red";

This will make the color of h1 red.

Upvotes: 0

Francis
Francis

Reputation: 692

almost got it dude.

change:

document.querySelector('#form-busca').onfocus

to:

document.querySelector('#q').onfocus

revised code:

correct sample:

document.querySelector('#form-busca').onsubmit = function() {
    if (document.querySelector('#q').value == '') {
        document.querySelector('#q').style.background = 'red';
        return false;
    }
}

document.querySelector('#q').onfocus = function() {
    document.querySelector('#q').style.background = 'white';
}

Upvotes: 8

ShadowRanger
ShadowRanger

Reputation: 155383

You want the onfocus handler to be on the #q element, not on #form-busca; the form's focus doesn't matter, you want to clear the background when the input element gains focus:

document.querySelector('#q').onfocus = function() { ... }

Upvotes: 0

Matthew
Matthew

Reputation: 123

It sounds like you want the input's background color to change to white when the input element is focused.

Try changing your onfocus selector to:
document.querySelector('#q').onfocus ...

Upvotes: 1

Related Questions