How to remove a value when you click outside of a button?
When I click a button I select the ratings value but when i click outside of the buttons I want to remove that value from the variable.
I tried if .hasFocus() and .activeElement is false (probably did it wrong too) then change the variable to undefined but it didn't work for now.
https://stackblitz.com/edit/web-platform-gffhc4?file=script.js
Lena
StackBlitz
Pure HTML / CSS / JS (forked) - StackBlitz
A polymer project based on @polymer/lit-element.
5 Replies
Really this sort of thing should be done with radio inputs rather than buttons.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio
You can do the following;
And style the input to be visually hidden but still on the DOM, and the div to look like your buttons.
You can then add a rule
input:checked + div
which will select the div belonging to the selected radio button.
You could also implement your "click away > reset value", but this isn't a common pattern in UI and it's likely that users will be confused by this behavior.
That being said, if you want to do it to teach yourself more about this, that's okay.
You can iterate over the radio inputs and call radio.checked = false
on each of them, as well as myBoundValueVar = undefined
if you're setting up binding (although I'd advise in this case you don't, and instead grab the radio group value as and when you need it)@willsterjohnson Thanks for your reply. Yes I was trying to understand more JavaScript that's why I wanted to try it but if you say that this is actually not good practice then I think I won't bother too much and try doing it with the radio buttons as you said 🙂
np! it's not that it's a bad thing to do, there's no accessibility or usability issue with doing what you had planned.
The only real reason not to is because nobody else is doing it. There are some things where being unique is extremely valuable, but for more functional UI such as inputs, dropdowns, buttons, links, etc, it's generally best to do something similar to everyone else, that way your users will be able to use their previous experience on the web to correctly guess how your website works.
It's easy to forget, but most people who use the internet aren't all that computer literate, even if they've been on it for years. My grandfather was the first guy in a pretty large area to get a home PC back when 32KB of RAM was huge, and his computer skills are... not great 😅 I try to imagine him using the site when I'm testing something out, helps a lot to remind myself that as a developer I'm much more computer literate than most of my users will be.
@willsterjohnson Yes I see hehe. And I changed it to radio buttons now. It still works fine 😁
in that case you should use labels to preserve semantic and it automatically wires the click/focus from the label to the corresponding input