Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate checkbox hover effect with jQuery

How would I simulate the effect that happens to a checkbox when you hover over it using jQuery? When you do this in Chrome and Firefox, the checkbox input is highlighted blue.

To give a bit more context, I have a grid like so:

<table>
    <tbody>
        <tr>
            <td><input type="checkbox" /></td>
            <td>this is a checkbox</td>
        </tr>
    </tbody>
</table

I want to make it that the checkbox is highlighted the default blue colour when a user hovers over the <tr>

I realise I could put a label around this is a checkbox and reference the checkbox with the for attribute, however I would rather trigger this effect on hover over the <tr>.

I'm a bit suspicious about using CSS to style the checkbox input itself as it seems a bit hacky.

like image 895
ajbeaven Avatar asked Jul 16 '26 09:07

ajbeaven


2 Answers

/edit after your edit: Some browsers (like Opera) seem to allow you to do things like padding-right:100px so that hovering the mouse near the checkbox would highlight the checkbox as well. You can try waste some time with that, but I'd highly recommend you do it with libraries.

That blueish hover sort of thing is from the operating system. Only imaginable way would've been to focus it but obviously it doesn't work.

You can do what we've all been doing for the past decade, turn checkboxes into hidden inputs and use images. Plenty of libraries out there.

Here's one.

like image 148
Silviu-Marian Avatar answered Jul 18 '26 21:07

Silviu-Marian


I'd say your best bet for looks consistency is to replace the checkbox with your own crafted checkbox. I extracted and edited this from a plugin I made a while ago.

Demo: http://jsfiddle.net/elclanrs/jTteE/

html:

<label><input type="checkbox">Hey</label>

css:

input[type="checkbox"] {
    position: absolute;
    margin-left: -9999px;
}
.check {
    position: relative;
    display: inline-block;
    vertical-align: top;
    margin-right: .5em;
    width: 1.1em;
    height: 1.1em;
    background: #ddd;
}
.check:hover {
    background: pink;
}
.check.checked {
    background: red;
}
.check.checked:after {
    content: "\2713";
    position: absolute;
    font-size: 22px;
    font-weight: bold;
    line-height: 16px;
    top: 0;
    z-index: 999;
    color: white;
}

js:

// Check
$('input:checkbox').each(function() {
    $(this).before('<span class="check"></span>');
    if ($(this).is(':checked')) {
        $(this).prev('span').addClass('checked');
    }
}).change(function() {
    $(this).prev('span').toggleClass('checked');
});
like image 42
elclanrs Avatar answered Jul 18 '26 23:07

elclanrs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!