PDA

View Full Version : Multiple Div Ids in getElementById Help



dassurai
07-22-2008, 12:05 PM
Hey i am new to javascript and trying to modify this
<script type="text/javascript">
document.onclick=check;
function check(e){
var target = (e && e.target) || (event && event.srcElement);
var obj = document.getElementById('content');
checkParent(target)?obj.style.display='none':null;
}
function checkParent(t){
while(t.parentNode){
if(t==document.getElementById('content')){
return false
}
t=t.parentNode
}
return true
}
</script>

basically i have two divs with different ids i need to have this functionality on both the divs. when i am putting the script for a single div its works fine. my question is how can i have the functionality with two different divs having two different ids.
please help
thanks in advance

Nile
07-22-2008, 12:43 PM
Try this:


<script type="text/javascript">
document.onclick=check;
var obj = new Array();
var target = new Array();
var allDivs = ['div1','div2'];
function check(e){
for(indicate=0;indicate<allDivs.length;indicate++){
target[indicate] = (e && e.target) || (event && event.srcElement);
obj[indicate] = document.getElementById(allDivs[indicate]);
checkParent(target[indicate])?obj[indicate].style.display='none':null;
}
}
function checkParent(t){
while(t.parentNode){
for(indicate=0;indicate<allDivs.length;indicate++){
if(t==document.getElementById(allDivs[indicate])){
return false;
}
t=t.parentNode;
}
return true;
}
}
</script>

I really don't think this will work, but its no effort giving it a try. :)

jscheuer1
07-22-2008, 04:11 PM
Why not use the parent element's class name instead of id? That way you can have two or more parents with the same class name. For the purpose of the code below, I'm assuming that the parent(s) are division tags with the class name of 'content':


<script type="text/javascript">
document.onclick=check;
function check(e){
var target = (e && e.target) || (event && event.srcElement);
for (var c = document.getElementsByTagName('div'), i = c.length - 1; i > -1; --i)
if(c[i].className == 'content')
c[i].style.display = '';
if(checkParent(target))
checkParent(target).style.display = 'none';
};
function checkParent(t){
while(t.parentNode){
if(t.className == 'content')
return t;
t=t.parentNode;
};
return false;
};
</script>

However, I'm a little confused by the original code, here:


checkParent(target)?obj.style.display='none':null;

Which looks like to me, if I've clicked on a child of the parent, it (the parent and the child) disappears. If I've clicked anywhere else, parent and child appear. If I have that right, I think my code is setup to do that as well.

And I don't like the looks of:


var target = (e && e.target) || (event && event.srcElement);

But if it works, I'm not going to argue about it.