Skip to content
Advertisement

JS onClick how to remove it when I click anywhere on the webpage

I am making a form and input where, when I click on the input the border of the form changes it’s color and what I want to happen is that when I click anywhere else it goes back to it’s original color.

-HTML

<form action="">
    <input onclick="onClick()" type="email" placeholder="Your E-mail Address">
    <button>Get Started</button>
</form>

-CSS

form {
   display: flex;
   flex-direction: row;
   border: 2px solid rgb(226, 226, 226);
   border-radius: 30px;
   padding: 8px 8px;
   width: 78%;
   transition: all 300ms ease;
}

.on-click form {
   border: 2px solid #6415ff;
}

-JS

function onClick() {
    document.body.classList += " on-click"
}

I tried making this one but I can’t put it on the whole document

function offClick() {
    document.body.classList.remove('on-click')
}

When I click on the input the form changes it’s color but I can’t wrap my head on how to get it off. Any advice or solutions please

Advertisement

Answer

You actually don’t need JavaScript to solve this at all, you could use :focus-within pseudo-class, like this:

form {
   display: flex;
   flex-direction: row;
   border: 2px solid rgb(226, 226, 226);
   border-radius: 30px;
   padding: 8px 8px;
   width: 78%;
   transition: all 300ms ease;
}

form:focus-within {
   border: 2px solid #6415ff;
}

More about :focus-within here.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement