8

I am trying to create a custom designed checkbox using the label associated to a checkbox element and hiding (display:none) the checkbox.

This works fine in all browsers except IE, which requires the checkbox to be visible for the label to be clickable.

Here's my code...

HTML

<input type="checkbox" id="myCheck" />​

CSS

label.checkbox {
    border:1px solid #666;
    width:25px;
    height:23px;
    display:block; 
}​

jquery

$("input[type=checkbox]").each(function() {
    $(this).hide().before('<label for="' + $(this).attr("id") + '" class="checkbox"></label>');
});

$("input[type=checkbox]").live('change', function() {
    if ($(this).prop('checked') == true) {
        $('label[for=' + $(this).attr("id") + ']').html("X")
    } else {
        $('label[for=' + $(this).attr("id") + ']').html("")
    }
});​

Or jsfiddle

Tom
  • 12,776
  • 48
  • 145
  • 240

2 Answers2

9

I don't know whether there is a more efective way to do this, but you can do this by setting checkbox element position out of the page,

.hiddenEl {
   position:absolute;
   top: -3000px;
}


$("input[type=checkbox]").each(function() {
    $(this).addClass("hiddenEl").before('<label for="' + $(this).attr("id") + '" class="checkbox"></label>');
});

DEMO


UPDATE

And also you can set checbox opacity to zero, that will hide it without "dispayl:none",

$(this).css("opacity", 0)

or

$(this).fadeTo(0, 0)
Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129
  • 7
    Note: It's generally better to use `left: -3000px` instead of `top:-3000px` (or 9999px). When you click the label using `top`, the focus will be set to the radiobutton and IE8 will attempt to bring it into view - having the unfortunate side effect of scrolling to the top of the page. So provided your content fits horizontally with no horizontal scroll bar it is better to use `left` than `top` – Simon_Weaver Jul 15 '13 at 03:20
  • The `opacity` property is not supported in Internet Explorer until version IE9, therefore I had to use `filter:Alpha(opacity=0)`. [mozilla-css-opacity](https://developer.mozilla.org/en-US/docs/Web/CSS/opacity) – ityler22 Oct 25 '16 at 18:25
  • @ityler22, I think you don't have to worry about that beacuse it's handled by jquery. – Okan Kocyigit Oct 26 '16 at 06:40
  • @ocanal That's interesting, I'll have to try that out! Admittedly I used your solution from a pure CSS approach so that would explain why it could work by adding the opacity with jquery. – ityler22 Oct 26 '16 at 12:55
2

try this:

#myCheck{
  position:absolute;
  left:-9999px;
  }

And leave the check box "visible"

Carsen
  • 269
  • 3
  • 10