0

I have some list items and each contains a small box next to it. Upon clicking on the box, some info is shown. I want to hide the box if a click is outside the box. But i do not know exactly how to do it. There are already some posts similar to this question but all of them are using jQuery but I have to get this done using pure JavaScript

I tried to do following way: http://jsfiddle.net/kn8hw4tf/1/

6
  • You have to listen click event on entire document Commented Oct 21, 2014 at 8:03
  • The quickest solution is to add an even listener to body and hide the box on click. Commented Oct 21, 2014 at 8:04
  • fiddle link is not working Commented Oct 21, 2014 at 8:08
  • 1
    @ManjunathSiddappa: It is not supposed to. The OP has received a warning by the editor that jsfiddle links are not allowed unless accompanied by some code in the question, and he's trying to wriggle around the requirement. Commented Oct 21, 2014 at 8:11
  • 2
    @user596502: And instead of pasting some code into your question as the rules say you should, you instead mark a random piece of text as code to avoid the warning? Please do not do so in the future; as a new user you can be forgiven not to know the rules, but this is obviously a case of being told the rules and then going out of your way to disobey them. Commented Oct 21, 2014 at 8:57

1 Answer 1

2

Listen for clicks anywhere on document, and react to them. Listen for clicks on the box, and invoke event.stopPropagation() so they don't hit the listener on document.

document.getElementById('test_id').addEventListener('click', function getDetails(evt) {
    var id = this.getAttribute('id');
    alert("Clicked on " + id);
    evt.stopPropagation();
});

document.addEventListener("click", function (e) {
    alert("Clicked outside");
});
Sign up to request clarification or add additional context in comments.

2 Comments

is there any example that i can look forward to or can you please elaborate a bit more. Thank you
Sorry, but your fiddle has so many errors and irrelevant bits that I couldn't understand what you were trying to do exactly. A minimal example demonstrating the concept is here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.