Change color using querySelector
Asked Answered
S

4

8

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!

Slippy answered 23/6, 2016 at 22:44 Comment(0)
B
8

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';
}
Beals answered 23/6, 2016 at 22:56 Comment(2)
Got it! Thanks, dude :DSlippy
I'm trying to vote but there is some bug there D: When I vote it returns to zero lolSlippy
I
1

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 ...

Illimani answered 23/6, 2016 at 22:48 Comment(0)
H
0

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() { ... }
Herringbone answered 23/6, 2016 at 22:49 Comment(0)
M
0

Try the following code:

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

This will make the color of h1 red.

Mullock answered 27/11, 2018 at 20:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.