7

An good example of what im trying to do is, think of instragram. When you are click on a photo, it opens a window with that photo plus the grey background. If you click anywhere in the grey background the picture is closed, however if you click on the picture the picture remains in the window.

This is what I am trying to achieve with this:

<div class="overlay_display_production_list_background" id="overlay_display_production_list_background_id" onclick="this.style.display = 'none'">
    <table class="table_production_availability" id="table_production_availability_id" onclick="this.parentElement.style.display = 'block'">
    </table>

</div>

However this doesnt work. how do I get this working, I only want Purely java-script.

Thanks

  • 1
    can u prepare a codepen / jsfiddle with more code to help you on these? – user2906608 Apr 06 '18 at 09:23
  • display:none on the div will make the table also no more visible ... the end .. – Temani Afif Apr 06 '18 at 09:24
  • Yes I know Temani, and its meant to make the table no more visible unless you click only in the table –  Apr 06 '18 at 09:24
  • This might help
    https://stackoverflow.com/questions/1369035/how-do-i-prevent-a-parents-onclick-event-from-firing-when-a-child-anchor-is-cli
    – Dominik Apr 06 '18 at 09:25

2 Answers2

6

Avoid intrinsic event attributes (like onclick). Bind your event handlers with JavaScript. Take advantage of the event object to prevent further propagation of the event up the DOM (so it never reaches the parent and thus doesn't trigger the event handler bound to it).

document.querySelector("div").addEventListener("click", parent);
document.querySelector("div div").addEventListener("click", child);

function parent(event) {
  console.log("Parent clicked");
}

function child(event) {
  event.stopPropagation();
  console.log("Child clicked");
}
div {
  padding: 2em;
  background: red;
}

div div {
  background: blue;
}
<div>
  <div>
  </div>
</div>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You perhaps can take an inner div which is absolute that has the background and certain height and width which is equal to main parent div and that has all the style, so on click of that div you may close parent div and on image you need not to do anything.

<div Parent><div Childdiv>
</div>
<img>
</div>

So childdiv should have display none functionality. With JavaScript, you should be able to close parent div on a click of child div.

Pang
  • 9,564
  • 146
  • 81
  • 122
user2906608
  • 123
  • 10