jquery change background color of td when clicked on empty portion

Viewed 49

I am working on event management project. I created an event in 1 day. I want to change the background color of the td only when the user clicks on an empty portion. If they click on the event div there should be no change in background color.

$(document).on("click", "td", function() { 
  $(this).css("background-color", "lightblue");
});

If I click on the event the background color changes. I want that it only changes when I click on an empty portion.

1 Answers

To achieve this you can check that the event.target matches the element the event is bound to. Try this:

$(document).on("click", "td", function(e) {
  if (e.target == this)
    $(this).css("background-color", "lightblue");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      Click me and the BG will change
      <div>Click me and it won't</div>
    </td>
  </tr>
</table>

Related