Dan Gravell Dan Gravell - 2 months ago 7
HTML Question

CSS3 switch inside clickable element

I have the following html:

<li class="list-group-item li-tab-1">
<div class="list-group-item-desc" data-target="#tab-1" data-toggle="tab">
<strong>1</strong>
<div class="small m-t-xs">
<p>Description</p>
</div>
<div class="onoffswitch">
<input type="checkbox" checked="checked" class="onoffswitch-checkbox" id="tab-1-enabled" /> <label class="onoffswitch-label" for="tab-1-enabled"> <span
class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span>
</label>
</div>
</div>
</li>


This is a Bootstrap tab.
.onoffswitch
is a CSS3 switch.

I'm trying to make the entire
<li>
clickable to show
#tab-1
as the tab content.
I can do this by defining a
<div>
with the
data-target
and
data-toggle
attributes. This works - when I click the div the tab shows.

However, embedded inside the
<li>
is a CSS3 switch. I want that to work independently of the clickable div.

This is similar to Links inside of larger clickable areas (CSS Only), except the nested clickable elements are CSS3 switches instead of anchors.

Using the CSS3 switch outside the anchor works fine.

I tried making the actual hidden checkbox visible, removing the CSS3 styling, and clicking that. That does work, so is this related to CSS3?

I wondered if this is related to propogation - the trouble is that if I set an event listener for
control.select
or
change
I get no events - just the div click event.

Answer

Turned out it was propogation that was the problem (thanks @TW80000).

$(".list-group-item-desc").click(function(ev) {
    var isSwitchClick = $('.onoffswitch').has($(ev.target)).length > 0;
    if(isSwitchClick) {
        ev.stopPropagation();
    }
});

That checks whether the click was inside the switch, and if so stops propogation.

In reality I have since moved the Bootstrap tab attrributes into the <li> but I think either approach should work to avoid swallowing the event.