steve Kim steve Kim -4 years ago 190
Javascript Question

js click event on empty div class

I have three divs as below:

Here is a JSFiddle.

$(document).on('click', '.top', function (e) {
console.log("Empty space clicked");

width: 208px;
text-transform: uppercase;
text-align: left;
height: 34px;
background-color: #F44336;
border-bottom: 1px solid #ea1c0d;
color: #ffffff;
box-shadow: 0px 3px 3px 0px rgba(50, 50, 50, 0.1);
padding: 3px 8px;
cursor: auto;
font-size: 12px;
font-size: 11px;
text-transform: none;
line-height: 12px;
margin-top: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;

.inner_1:hover, .inner_2:hover {
cursor: pointer;
text-decoration: underline;

<script src=""></script>
<div class="top">
<div class="inner_1">Top content: This is full width</div>
<div class="inner_2">Bottom</div>

As you can see from the jsfiddle, when the
is clicked, it shows a log.

However, I want to make it so that it shows the log ONLY when the empty space is clicked and not when
div class is clicked (as it shows the log when these two classes are clicked as of now).

What is the best way to achieve this?


Answer Source

Use stopPropagation from jquery. This will stop all child divs from triggering parent onClick

$(document).on('click', '.top > div', function (e) {                    

Edit: Code above was building on what OP knows but this way is more efficient for the browser.

$('.top > div').on('click', function (e) {                    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download