Click event only on parent, not children
Making the click event fire only when clicking on a parent HTML element, not on its children. In JavaScript:
child 1
child 2
child 3
HTML code:
<div class="example">
<div class="parent">
<div class="child">child 1</div>
<div class="child">child 2</div>
<div class="child">child 3</div>
</div>
</div>
JavaScript code:
<script>
document.querySelector('.parent').addEventListener('click', function () {
var selection = window.getSelection();
if ( event.target == event.currentTarget && selection.type != 'Range' ) {
document.querySelector('.parent').classList.toggle('red');
}
});
</script>
CSS code:
/* Styling the look */
.parent{padding: 62px 40px 40px 40px; cursor: pointer; background: #ded;}
.parent:before{content: "parent"; position: absolute; left: 0; top: 0; padding: 17px 0 0 40px;}
.child{padding: 0 25px 9px 25px; cursor: text; border-left: 1px #ccc solid; border-right: 1px #ccc solid; background: #ddd;}
.child:first-of-type{padding-top: 19px; border-top: 1px #ccc solid;}
.child:last-of-type{padding-bottom: 19px; border-bottom: 1px #ccc solid;}
.red{font-weight: bold; color: #c00;}
Links
- Event: currentTarget property: developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
- Window: getSelection() method: developer.mozilla.org/en-US/docs/Web/API/Window/getSelection
- Selection: type property: developer.mozilla.org/en-US/docs/Web/API/Selection/type
- How to have click event ONLY fire on parent DIV, not children? stackoverflow.com/questions/9183381/how-to-have-click-event-only-fire-on-parent-div-not-children
- Prevent onClick event when selecting text: stackoverflow.com/questions/31982407/prevent-onclick-event-when-selecting-text
Browser support
- Windows
- Edge 12.0+
- Firefox 3.5+
- Google Chrome 1.0+
- Opera 10.0+
- Safari 3.1+
- Linux
- Firefox 3.5+
- Google Chrome 1.0+
- Opera 10.0+
- iOS
- Safari 2.0+
- Android
- Samsung Internet 1.0+
- Chrome Android 18.0+
- Firefox for Android 4.0+
- Opera Android 10.1+