I am not sure if I understood exactly what the problem is, but it sounds like you need to pass an argument to the function you want to call with setTimeout
?
var retTimer = setTimeout(function() {
divRetract(elem2)
}, 20);
سؤال
I have a div
that expands and retracts to show/hide content. I'm using button
s with addEventListner
to show/hide the div
. I have more then one div
I want to show/hide and more than one set of show/hide button
s. I'm therefore trying to reuse the same two functions that show/hide the content but with different event handlers.
The problem I'm having is passing the relevant div id
to the function so the function knows whichdiv
element to show/hide for each function call. The function
recognizes the div id
on the first interation however when recalled by setTimeout
the div id
is no longer recognized. I have tried adding the variable used for div id
to setTimeout
without any joy.
I'm aware I can use inline javascript for this but am trying to avoid that.
Any ideas how I can solve this using external javascript as I'm trying here ?
HTML:
<button id='expand'>expand</button><button id='retract'>retract</button>
<div id="latinText">
<p>...some content here</p>
</div>
<button id='expandToo'>expandToo</button><button id='retractToo'>retractToo</button>
<div id='latinText2'>
<p>...some more content here</p>
</div>
Javascript:
function divExp(elem) {
var element = document.getElementById(elem);
var h = element.offsetHeight;
var scrollHeight = element.scrollHeight;
var divTimer = setTimeout(divExp, 20);
if(h < scrollHeight) {
h += 5;
} else {
clearTimeout(divTimer);
}
element.style.height = h+'px' ;
}
function divRetract(elem2) {
var element = document.getElementById(elem2);
var h = element.offsetHeight;
var retTimer = setTimeout(divRetract, 20);
if(h > 0) {
h -= 5;
} else {
clearTimeout(retTimer);
}
element.style.height = h+'px' ;
}
document.getElementById('expand').addEventListener('click', function(){ divExp('latinText'); }, false);
document.getElementById('retract').addEventListener('click',function (){ divRetract('latinText') }, false);
document.getElementById('expandToo').addEventListener('click', function(){ divExp('latinText2'); }, false);
document.getElementById('retractToo').addEventListener('click',function(){ divRetract('latinText2'); }, false);
المحلول
I am not sure if I understood exactly what the problem is, but it sounds like you need to pass an argument to the function you want to call with setTimeout
?
var retTimer = setTimeout(function() {
divRetract(elem2)
}, 20);
نصائح أخرى
You should write
var divTimer = setTimeout(function(){divExp(elem)}, 20);
instead of
var divTimer = setTimeout(divExp, 20);
than You'll pass the same element to a function, called by timeout. Otherwise You call divExp() function without parameters