Steve Kim
Steve Kim

Reputation: 5601

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");	
});		
.top{    
    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;
  }
 .inner_1{
    font-size: 12px;
 }
  .inner_2{
   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="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="top">
  <div class="inner_1">Top content: This is full width</div>
  <div class="inner_2">Bottom</div>
</div>

As you can see from the jsfiddle, when the .top 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 inner_1 or inner_2 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?

Thanks.

Upvotes: 0

Views: 2080

Answers (1)

Steven Johnston
Steven Johnston

Reputation: 1849

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

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

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

$('.top > div').on('click', function (e) {                    
  e.stopPropagation();
});     

Upvotes: 2

Related Questions