This seems something I shouldnt have to waste a question on, but I can’t get it to work!
I’m trying to make a pretty checkbox using a <span> with a background icon and a hidden checkbox.
My HTML is
<span class="checkedBox" id="mailing_Check"></span>
<input type="checkbox" id="mailing" /> <!--(currently not hidden for testing)-->
CSS is simple:
.checkedBox { background: url('../images/iconLine.png'); background-position: -550px, 0px; display: inline-block; width: 25px; height: 25px }
.unCheckedBox { background: url('../images/iconLine.png'); background-position: -575px, 0px; display: inline-block; width: 25px; height: 25px }
I need to bind an onClick handler to the checkedBox item, toggle/flip the class to unCheckedBox and set the checkbox to checked.
Now, I have various long winded ways of doing this, but am trying to do it using jQuery toggle, or toggleClass and I can’t get it to work properly.
Just working with flipping the CSS class for now…
$('.checkedBox, unCheckedBox').live('click', function () {
$(this).toggleClass('checkedBox').toggleClass('checkedBox');
});
That will flip it once, but is not binding properly, when I click the second time, it has no effect.
I’ve tried using this example; jQuery toggle class
But that doesn’t seem to want to work, also various other Googled results, but for some reason I am struggling.
I want to keep the code to a minimum using the minimum requirement of variables, like I say, I have some long winded method using if/else logic, but I figured jQuery should make it easier! 🙂
Since you’re modifying the exact same CSS style properties on your two CSS rules (
.checkedBoxand.unCheckedBox), I imagine that you don’t have to toggle the.checkedboxclass, because the other just overrides it.Even better, you can just have a class that marks all your “pretty” checkboxes, and then another that modifies the style from the default.
Maybe something like:
CSS
Then you can just worry about toggling the
.checkedclass.