Skip to content
Advertisement

In JavaScript e.target is not working as I expected

I have written some JavaScript that opens an element when an element is clicked. However I can’t get the:

JavaScript

This is not working to how I want it because:

  1. You can open more than one of the showed elements when I only want one open at a time.

  2. When I click inside the element it closes, I only want it to close if they have clicked outside the box.

    JavaScript

http://jsfiddle.net/jamcoupe/9CEGw/

Edit: After @Felix Kling post I changed the code to:

JavaScript

This has solve the first problem but I am still stuck on how to make it so that only one box is ever open at one giving time. So when a user has signIn box open and clicks on currencyChanger I want the signIn box to be off.

http://jsfiddle.net/jamcoupe/kcF9Z/7/

Advertisement

Answer

When I click inside the element it closes, I only want it to close if they have clicked outside the box.

As I already said in my comment, if the box contains other elements, then e.target does not refer to the box itself but to the element within the box.

So in order to test whether the click was outside or not, you have to test whether e.target is an element within the box or the box itself. For that, you have to traverse the DOM tree.

Example:

JavaScript

You can open more than one of the showed elements when I only want one open at a time.

If you want to make the three dialogs dependent on each other, you have to maintain some shared state. I’d suggest, instead of having three dialogs, you can have one dialog manager which takes care of opening and closing the boxes.

Example:

JavaScript

DEMO

I hope this gives you some idea. There is still a lot which can be improved, for example, now the manager listens to every click event, no matter whether a dialog is open or not.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement