1

Here's my function:

document.querySelector('body').addEventListener('click',e=>{getRandomImagePair()});

When I click anywhere on the body something happens. I have two divs .more and .wd and if I click on them the function getRandomImagePair() executes. How can I make so that if I click the links the function doesn't fire?

I tried this below, it works but then the .more div won't trigger another needed different function.

$('.more, .wd').on('click', function(event) {
  event.stopPropagation();
});
Tom O.
  • 5,730
  • 2
  • 21
  • 35
Federico
  • 1,392
  • 1
  • 17
  • 40

2 Answers2

1

Using event delegation, just check the className of the event.target element. Use an if statement in your event handler callback to prevent getRandomImagePair from being called a link was clicked on:

function getRandomImagePair() {
  console.log('getRandomImagePair called');
}

//using event delegation
document.querySelector('body').addEventListener('click', e => {
  if (e.target.className !== 'wd' && e.target.className !== 'more') {
    getRandomImagePair();
  }
});
.wd,
.more {
  color: blue;
  text-decoration: underline;
}
<body>
  <div class="more">.more</div>
  <div class="wd">.wd</div>

  <p>Here is some other stuff</p>
  <p>that when clicked on should still fire event handler</p>
</body>
Tom O.
  • 5,730
  • 2
  • 21
  • 35
  • This has a flaw if there are children inside of the element `
    click here.more
    ` So if OP has nested elements inside, than this answer will fail.
    – epascarello Jul 03 '18 at 13:39
  • @epascarello Nothing about nested `` elements was detailed in the question. – Tom O. Jul 03 '18 at 13:42
  • I agree this answer will work if there is no nesting. Just stating it in case the OP has it since it is vary rare the OP shows the actual HTML. Using [contains()](https://developer.mozilla.org/en-US/docs/Web/API/Node/contains) would be safer IMO. – epascarello Jul 03 '18 at 13:44
0

Try excluding the items you don't want to be affected by the click :

const getRandomImagePair = () => {
 alert("clicked")
}

$('body :not(".more, .wd")').on('click', getRandomImagePair);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Yep</button>
<button class="more">Nope</button>
<button class="wd">Nope</button>
<button>Yep</button>
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63