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

Time:01-20

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

CodePudding user response:

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.

CodePudding user response:

you should use the CSS selector :focus on your input style like that:

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 {
   border: 2px solid #6415ff;
}

So it basically checks when you clicked on the input and that you're ready to write on it, which means your focus on the input. So the CSS detect that and changes the style.

Hope it helped, if you want more information see this documentation

  • Related