caner taşdemir
caner taşdemir

Reputation: 203

jQuery - div inside div, how to run only 1 click event when inside has been clicked

I have a div inside div. If the inside div has been clicked (closeme div), I dont want to run the other div's (container div) click event. How can I do that ?

html

<div id="container">
content
<div id="closeme"></div>
</div>

js

$(document).on('click', '[id="container"]' ,function(){
alert("I am clicked");
}

$(document).on('click', '[id="closeme"]' ,function(){
alert("I am clicked");
}

Upvotes: 1

Views: 360

Answers (3)

madalinivascu
madalinivascu

Reputation: 32354

Do a if to test if the target is #closeme

 $(document).on('click', '[id="closeme"]', function(event) {
     if ($(event.target).is('[id="closeme"]')) {
        alert("coloseme clicked");
     }
    });

Upvotes: 2

rushi
rushi

Reputation: 276

Like others have just mentioned. You have to stop the event propagation. Here is a full working example.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
  <div id="container">
    content
    <div id="closeme">Inner Div</div>
  </div>
</body>
  <script>
    $(document).on('click', '[id="container"]', function(event) {
      alert("container clicked");
    });

    $(document).on('click', '[id="closeme"]', function(event) {
      event.stopPropagation();
      alert("coloseme clicked");
    });
  </script>
</html>

Upvotes: 1

guradio
guradio

Reputation: 15555

$(document).on('click', '[id="container"]', function(e) {
  e.stopPropagation();
  alert("I am container");
})

$(document).on('click', '[id="closeme"]', function(e) {
  e.stopPropagation();
  alert("I am closeme");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  content
  <div id="closeme">qwe</div>
</div>

Use event.stopPropagation()

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Upvotes: 2

Related Questions