2

In my html I have div that needs to be respond to user clicks. I have a new requirement to add some input controls within that div, however clicking on them causes the click event of the div to be fired.

Is it possible to prevent this from happening without interfering with the functionality of the input?

$('.click-me').click(function(){
   $(this).css("background-color", "#F00");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="click-me">
    I can be clicked
    
    <select>
        <option>Option One</option>
        <option>Option Two</option>
        <option>Option Three</option>
    </select>
</div>

This is different to the suggested duplicate because I'm not attaching an event to the select list, the browser does that by itself. I want to allow the normal event on the select list to play out but not call the event on the div that is behind it

CurlyPaul
  • 1,138
  • 1
  • 10
  • 29

2 Answers2

3

How about this:

<div class="click-me" id='myDiv'>
    I can be clicked

    <select>
        <option>Option One</option>
        <option>Option Two</option>
        <option>Option Three</option>
    </select>
</div>

$('.click-me').click(function(event){
    if(event.target.id == 'myDiv') {
       $(this).css("background-color", "#F00");
    }
});
renakre
  • 8,001
  • 5
  • 46
  • 99
3

Option 1: Event target filtering

You can do this without too much additional code, without preventing event bubbling which may have unanticipated effects at a later time, or indeed by adding any additional event bindings..

Simply establish the original target for the event, then only run the relevant code if it is not an input etc:

$('.click-me').click(function(e) {
  if (['select', 'input', 'textarea'].indexOf(e.target.tagName.toLowerCase()) === -1) {
    $(this).css("background-color", "#F00");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="click-me">
  I can be clicked

  <select>
    <option>Option One</option>
    <option>Option Two</option>
    <option>Option Three</option>
  </select>
</div>

Option 1: Event target matching

Alternatively, check if the event target is the actual div itself, below checks whether the event target has the class click-me, it may be best to compare on a more unique attribute (e.g. id as noted elsewhere) or you could match the actual node itself.

$('.click-me').click(function(e) {
  if ($(e.target).hasClass('click-me')) {
    $(this).css("background-color", "#F00");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="click-me">
  I can be clicked

  <select>
    <option>Option One</option>
    <option>Option Two</option>
    <option>Option Three</option>
  </select>
</div>
SW4
  • 69,876
  • 20
  • 132
  • 137