Use Images Like Checkboxes
I Would Like to Have an Alternative to a Standard Checkbox - Basically I'd Like to Use Images and When the User Clicks the Image, Fade It out and Overlay a...
I would like to have an alternative to a standard checkbox - basically I'd like to use images and when the user clicks the image, fade it out and overlay a tick box.
In essence, I want to do something like Recaptcha 2 does when it gets you to click images that meet a certain criteria. You can see a Recaptcha demo here but it might sometimes get you to solve text questions, as opposed to the image selection. So here's a screenshot:
When you click one of the images (in this case, containing a picture of steak), the image you click shrinks in size and the blue tick appears, indicating that you've ticked it.
Let's say I want to reproduce this exact example.
I realise I can have 9 hidden checkboxes, and attach some jQuery so that when I click the image, it selects/deselects the hidden checkbox. But what about the shrinking of the image/overlaying the tick?
8 Answers
Pure semantic HTML/CSS solution
This is easy to implement on your own, no pre-made solution necessary. Also it will teach you a lot as you don't seem too easy with CSS.
Must Read
This is what you need to do:
Your checkboxes need to have distinct id attributes. This allows you to connect a <label> to it, using the label's for-attribute.
Example:
<input type="checkbox" id="myCheckbox1" />
<label for="myCheckbox1"><img src="" /></label>
Attaching the label to the checkbox will trigger a browser behaviour: Whenever someone clicks the label (or the image inside it), the checkbox will be toggled.
Next, you hide the checkbox by applying for example display: none; to it.
Now all that is left to do is set the style you want for your label::before pseudo element (which will be used as the visual checkbox replacement elements):
label::before {
background-image: url(../path/to/unchecked.png);
}
In a last tricky step, you make use of CSS' :checked pseudo selector to change the image when the checkbox is checked:
:checked + label::before {
background-image: url(../path/to/checked.png);
}
The + (adjacent sibling selector) makes sure you only change labels that directly follow the hidden checkbox in the markup.
You can optimize that by putting both images in a spritemap and only applying a change in background-position instead of swapping the image.
Of course you need to position the label correctly and apply display: block; and set correct width and height.