Scott White
Scott White

Reputation: 141

Clickable Container with inner links

My apologies if this already exists but I was unable to find anything like it. My stupid question is:

I have a clickable container with links inside that looks kinda like:

<div onclick="someFunction()">
    <...>
    <...>
    <button onclick="otherFunction()">
</div>

I want to be able to click anywhere in the container and open up something but I also want to be able to have the button inside work. My appreciation for all assistance in advance and apologies for the dumb question.

Upvotes: 0

Views: 64

Answers (2)

mastermind
mastermind

Reputation: 1057

It will work like ur thinking, when u click on button, click will fire on both on ur button as well as on div check codepen

event.stopPropagation()

var someFunction = function(event){
  alert('<someFunction>');
  
}

var otherFunction = function(event){
  alert("otherFunction ->");
}

var otherFunctionStopPropagation = function(event){
  alert("|otherFunction|");
  event.stopPropagation();
}
.Some{
  height:200px;
  background-color:yellow;
  z-index:1;
  
}

.other{
  z-index:2;
}
<div onclick="someFunction()" class="Some">
  <button onclick="otherFunction(event)"  class='other' id='other'>otherFunction</button>
  <button onclick="otherFunctionStopPropagation(event)"  class='other' id='other'>otherFunctionStopPropagation</button>

  <a onclick="otherFunctionStopPropagation(event)" href='' class='other' id='other'>a_otherFunctionStopPropagation</a>
</div>

https://codepen.io/mastersmind/pen/EbLEBb

Upvotes: 1

Jayabalaji J
Jayabalaji J

Reputation: 1066

You should use event.stopPropogation() function. This will prevent event getting bubbled to the parent element,

otherFunction() {
  event.stopPropagation()
  // your code here
}

Upvotes: 0

Related Questions