Forum Moderators: open

Message Too Old, No Replies

passing variable from For loop to function

         

manning2

10:24 pm on Jan 16, 2008 (gmt 0)

10+ Year Member



I'm trying to pass a variable, getDetailsClass[i] to a function but I get "undefined" in the first example.

The goal is to get use an elements container to toggle the display property
<div> <!-- the div is the trigger -->
<img src=../.jpg" />
<p class="details">this should toggle show/hide</p>
</div>

EXAMPLE 1:
function getDetails() {

var getDetailsClass = getElementsByClass(document, "*", "details");

for (var i=0; i<getDetailsClass.length; i++) {
var detail = getDetailsClass[i];

getDetailsClass[i].parentNode.onclick = function() {
detail.style.display = "block";
}
}
}

The second example works but it seems like it could be simplified.
EXAMPLE 2:
function getDetails() {

// find all elements with class="details"
var getDetailsClass = getElementsByClass(document, "*", "details");

for (var i=0; i<getDetailsClass.length; i++) {
// set Parent (wrapper Div) as trigger

getDetailsClass[i].parentNode.onclick = function() {
var getChild = getElementsByClass(this, "*", "details");

for (var j=0; j<getChild.length; j++) {
getChild[j].style.display="block";
}
}
}
}

thanks

gergoe

1:10 am on Jan 17, 2008 (gmt 0)

10+ Year Member



I got some lecture just about similar problems, see this thread [webmasterworld.com]. You will need to make a new function, which creates a function to replace the div (the second one you have already). So in your loop, you not just create an anonymous function (and assign it to onclick), but you call a function (with the details variable in parameter), and this function returns your oneliner, which hides the paragraph. To make the long story short:

function createOnClick(obj) { 
return function() {
obj.style.display = "block";
}
}
//
function getDetails() {
var getDetailsClass = getElementsByClass(document, "*", "details");
for (var i=0; i<getDetailsClass.length; i++) {
getDetailsClass[i].parentNode.onclick = createOnClick(getDetailsClass[i]);
}
}

Simple it become, isn't it? If you read in the thread I mentioned above, then you will get a nice explanation about this (javascript closures) - and I don't need to write it down here :-)

manning2

3:14 pm on Jan 17, 2008 (gmt 0)

10+ Year Member



very helpful, thanks