user7461846
user7461846

Reputation:

how to avoid click on parent by clicking on child?

<div class='titlewrap'>
<div class='title'>lorem ipsum</div>
<div class='title'>lorem ipsum</div>
<div class='title'>lorem ipsum</div>
<br><br>
</title>

I want to separate right click on titlewrap vs title.

js

$(document).on('contextmenu', '.titlewrap', function(e) {
    e.preventDefault();
    console.log('titlewrap');
});

$(document).on('contextmenu', '.title', function(e) {
    e.preventDefault();
    console.log('title');
});

Click on title gives double console result:
titlewrap
title

How to get only title by clicking on title and keep titlewrap clicking on titlewrap (empty space below title)

Upvotes: 1

Views: 49

Answers (2)

Patrick Evans
Patrick Evans

Reputation: 42736

Use event.stopPropagation() to stop the event from bubbling up to the parent and triggering its event. You will still be able to trigger titlewrap's event by right clicking on an area not covered by the title elements

$(document).on('contextmenu', '.titlewrap', function(e) {
    e.preventDefault();
    console.log('titlewrap');
});

$(document).on('contextmenu', '.title', function(e) {
    e.preventDefault();
    e.stopPropagation();
    console.log('title');
});
.titlewrap {
  padding:10px;
  border:black solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='titlewrap'>
  <div class='title'>lorem ipsum</div>
  <div class='title'>lorem ipsum</div>
  <div class='title'>lorem ipsum</div>
</div>

Upvotes: 1

leelum1
leelum1

Reputation: 1254

Try adding stopPropagation to the .title function like so

$(document).on('contextmenu', '.titlewrap', function(e) {
    e.preventDefault();
    console.log('titlewrap');
});

$(document).on('contextmenu', '.title', function(e) {
    e.preventDefault();
    e.stopPropagation();
    console.log('title');
});

Upvotes: 1

Related Questions