Change color using querySelector

hugolcouto picture hugolcouto · Jun 24, 2016 · Viewed 13.4k times · Source

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!

Answer

Francis picture Francis · Jun 24, 2016

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';
}