Issue with custom checkbox styling not responding to label hover and click functionality

I recently found a creative way to design custom styled checkboxes using pure CSS. The only downside is that you have to click on the box (actually, the label) itself to check it. If you're familiar with placing the input inside the label, then you know that allows for clicking on the text or the box to check it. However, this method doesn't allow for styling the checkbox itself due to limitations in CSS. To overcome this, I attempted to use JavaScript to trigger hover and click states. Despite applying the classes, the CSS isn't being rendered as expected, leaving me puzzled. I'm still working on implementing the click events, but first, I want to achieve the desired hover effect by hovering over the box.

http://codepen.io/sinrise/pen/gPZmRm

HTML

<div class="container">
  <ul class="subcategories">
    <li id="subcat-test">
      <div class="tmi-checkbox">
        <input type="checkbox" id="subcat-check-test" value="none" />
        <label for="subcat-check-test"></label><span>Subcategory</span>
      </div>
    </li>
  </ul>
</div>

CSS (SCSS)

.container { padding: 50px; }
ul.subcategories {
    list-style: none;
    padding: 0;
    li {
        &:hover { cursor: pointer; }
        position: relative;
        .tmi-checkbox {
            position: relative;
            display: block;
            margin: 0 0 15px 0;
            input[type="checkbox"] {
                visibility: hidden;
                &:checked + label:after {
                    opacity: 1;
                    border-color: #fff;
                }
                &:checked + label {
                    background: orange;
                    border-color: orange;
                }
            }
            label {
                position: absolute;
                top: 0;
                width: 18px;
                height: 18px;
                border-radius: 3px;
                border: 1px solid #ccc;
                &:hover { cursor: pointer; }
                &:after {
                  opacity: 0;
                  content: '';
                  position: absolute;
                  width: 11px;
                  height: 7px;
                  background: transparent;
                  top: 3px;
                  left: 3px;
                  border: 3px solid #333;
                  border-top: none;
                  border-right: none;
                  -webkit-transform: rotate(-45deg);
                  -moz-transform: rotate(-45deg);
                  -o-transform: rotate(-45deg);
                  -ms-transform: rotate(-45deg);
                  transform: rotate(-45deg);
                }
                &:hover::after {
                    opacity: 0.3;
                    cursor: pointer;
                }
            }
            span {
                display: block;
                position: absolute;
                margin-left: 30px;
                top: 0;
                max-width: 230px;
                color: #4a4a4a;
                left: 10px;
            }
        }
    }
}

JS

$(".subcategories li").hover(function() {
  $(this).find("label").addClass("tmi-checkbox-label-hover");
  $(this).find("input").addClass("tmi-checkbox-hover");
}, function() {
  $(this).find("label").removeClass("tmi-checkbox-label-hover");
  $(this).find("input").removeClass("tmi-checkbox-hover");
});

Answer №1

Make sure to place the

<span>Subcategory</span>
within the label element

<label for="subcat-check-test"></label><span>Subcategory</span>

Your code has been revised for better functionality. Take a look at it here: http://example.com

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Flex bug in safari causing issues with inline form display

I have created a simple inline form using flexbox. However, I encountered an issue in Safari where the button loses its width. Here is a screenshot for reference: https://i.stack.imgur.com/3s5AR.jpg Interestingly, the form looks fine in all other browsers ...

Is there a way to utilize solely Javascript in order to crop an image?

Is there a way to crop an image using plain JavaScript? I need a function that can take an image with specific width, height, offsetX, and offsetY and create a new image of the specified portion. I'm not very knowledgeable about HTML5 canvas and simi ...

Troubleshooting: How to resolve the issue of "Error [ERR_HTTP_HEADERS_SENT]: Unable to set headers after they have been sent to the client"

* **> const PORT=8000 const express = require('express') const {v4:uuidv4}=require('uuid') const bcrypt =require('bcrypt') const jwt =require('jsonwebtoken') const cors=require('cors') const {MongoClie ...

How to modify this to return a function and eliminate the need for declaring a function

Greetings! I understand that this may seem simple to some of you, but I am feeling quite lost. I've been tasked with removing the function declaration and converting it into a return function. Any assistance would be greatly appreciated. const canView ...

What methods can a server use to identify if JQuery Ajax's "withCredentials: true" option was utilized for CORS requests?

Currently, I am working on integrating CORS (Cross-origin resource sharing) into a framework. I understand that when an XMLHttpRequest request is made using Jquery's ajax(...) with the withCredentials property set to true, the server must specificall ...

Angular 4 provides the capability to reset a radio group that has been dynamically generated within a table

I am facing an issue with a dynamically created radio group inside a table in my component. I am using ngFor to generate the radio buttons, and there is a clear button outside the ngFor that should reset the radio group when clicked. However, my current im ...

Transmit a PDF byte array from JavaScript to PHP using Ajax, then utilize the PHP file to send an email

I am facing a particular issue. Currently, I am utilizing the pdf-lib library for JavaScript to generate a PDF. The last step involves creating a uint8array: const pdfBytes = await pdfDoc.save() My goal is to transmit these pdfbytes via AJAX to a PHP fi ...

"Troubleshooting: Issues with Bootstrap Popover Functionality Triggered by Ajax

I am facing an issue where the Bootstrap popover content loaded with ajax is not being displayed. Below is the code snippet in Javascript: var id = 1; $.post("load.php?pageid", { pageid:id; }, function(data,status){ ...

Using the Strikethrough Feature in React

Is it possible to apply a strikethrough effect to a checkbox's label text when toggled on and off? In my system development process, I've utilized various methods. What modifications should be made in the fComplete method for this feature to wor ...

Bringing a .json Model into Three.js

Exploring Three.js for the first time and struggling with importing a .json model obtained from Clara.io For instance, I have downloaded this model: However, I can't seem to understand how to embed it into an HTML file. :( I attempted the following ...

The attempt to connect with react-native-fetch-blob has not been successful

How do I resolve the issue of displaying a PDF from my assets folder in an Expo, React Native project using react-native-pdf? While scanning folders for symlinks, encountered an error with RNFetchBlob library in my project directory. The automatic linki ...

What methods are available to gradually increase a counter until it reaches a specific number by a designated date?

I have a unique idea for my website - I want to create a special counter that gradually increases to a specific number, but does so over the course of an entire year. Imagine starting at 0 and aiming to reach 35340340 after exactly one year has passed. It ...

Guide to retrieving objects in React.js

Struggling to extract a country from an online JSON file that I am currently fetching. I am attempting to streamline the process by creating a function to retrieve the country from the dataset and avoid repeating code. However, I am encountering difficulti ...

ReactJS allows the display of placeholder text for input fields only when they are actively selected

After modifying the BootstrapInput code snippet to the following: <BootstrapInput id="age-customized-input" placeholder="Search Title" /> I noticed that the placeholder text only appears when the input field is activated. Does anyone kno ...

What is the most efficient way to dynamically alter the position of a div element within an HTML document using

In a scenario where a parent div contains multiple child divs, it is required that one particular child div named .div_object_last always stays at the end. Below is an example setup : HTML <div class="div_parent"> <div class="div_object"> ...

Utilizing Custom Script Tag Types in Visual Studio for Enhanced HTML Template Functionality and Improved Syntax Highlighting

Currently, I am utilizing Visual Studio 2012 for editing HTML and JavaScript. My approach involves inserting templates using partial views in inline script tags (view code below). The use of AngularJS, a Javascript framework, dictates that the type must be ...

A guide on how to identify the return type of a callback function in TypeScript

Looking at this function I've created function computedLastOf<T>(cb: () => T[]) : Readonly<Ref<T | undefined>> { return computed(() => { const collection = cb(); return collection[collection.length - 1]; }); } Thi ...

Problem with integration of Bootstrap datetime picker in AngularJS directives

I am currently utilizing the Bootstrap Datetime picker to display data from a JSON file in calendar format. The data is first converted into the correct date format before being shown on the calendar, with both a To date and From date available. scope.onH ...

Approach to Using Bootstrap 4 with Intl-Tel-Input

I've been attempting to integrate intl-tel-input with bootstrap 4, but I'm facing an issue where the placeholder for the input is not showing up. I've tried various solutions found online, but none of them seem to work. Here's my HTML ...

What is the best way to conceal a button before printing and have it reappear once the printing process is finished?

I have a button on my webpage with the id "print_req" that is used to trigger a JavaScript function for printing the page. I want this button to be hidden during the printing process and then reappear afterwards, so it does not show up in the printed docum ...