loreley
loreley

Reputation: 59

Prototype.js event.target.id for child elements

I want to hide a div when clicking somewhere else in the page. For this, I have:

$(document.body).observe('click', function(e){
    if(e.target.id != 'myDiv') {
        $('myDiv').hide();
    }
});

Works fine, the only problem is that inside this div I have other elements, and clicking them also closes #myDiv. I want it so that clicking anything inside this div won't trigger the hiding. After searching around, I found the answer here on how to do this with jQuery: https://stackoverflow.com/a/12222263/548524. However, I can't seem to get this working in Prototype, and obviously has() is not valid here.

Any help is much appreciated!

Upvotes: 2

Views: 2762

Answers (2)

Victor
Victor

Reputation: 3828

document.observe('click', function(event) {
  if (!event.findElement('#myDiv')) {
    $('myDiv').hide();
  }
});
  1. You don't need $(document.body) - there is already document-wide observe
  2. There is a method to find element from event

Upvotes: 2

Dirk McQuickly
Dirk McQuickly

Reputation: 2139

Use the 'up' function:

$(document.body).observe('click', function(e){
    if(e.target.id != 'myDiv' && !$(e.target.id).up('#myDiv')) {
        $('myDiv').hide();
    }
});

Upvotes: 1

Related Questions