Hello everybody I need your help in this problem At first, this is the code used HTML Code <input type="text" onfocus="fadeIn(this)" /><div class="box" style="opacity: 0.0"></div><br /> <input type="text" onfocus="fadeIn(this)" /><div class="box" style="opacity: 0.0"></div> HTML: JavaScript Code function fadeIn(elem){ element = elem.nextSibling; elemOpacity = element.style.opacity; element.innerHTML = elemOpacity; if (elemOpacity < 1.0) element.style.opacity = parseFloat(elemOpacity) + 0.1; timeIn = setTimeout(fadeIn, 100); } Code (markup): I have used the opacity property to make fading element like fadeIn() function in jquery , and i have used onfocus event to execute the code . Problem exists in setTimeout function, this function Does not work But the code works without this function What is the cause of the problem , Please help me
I don't why your code doesn't work with setTimeout function, but maybe you can do what you want by using this code: <input id="input1" type="text" onfocus="fadeIn(this.id)" /><div class="box" style="opacity: 0.0"></div><br /> <input id="input2" type="text" onfocus="fadeIn(this.id)" /><div class="box" style="opacity: 0.0"></div> HTML: function fadeIn(elem_id){ elem = document.getElementById(elem_id); element = elem.nextSibling; elemOpacity = element.style.opacity; element.innerHTML = elemOpacity; if (elemOpacity < 1.0) element.style.opacity = parseFloat(elemOpacity) + 0.1; timeIn = setTimeout("fadeIn('"+elem_id+"')", 100); } Code (JavaScript):
Hi. Probably because fadeIn() was called several times: 1st time from input element which was OK, but the next times from setTimeout which could not pass parameter? Either use a global for storing elem, or use s_ruben's example (using element id) shall solve the problem. But... don't you think non-recursive fadeIn() is better: ... var timeIn = null; el = null; function fadeIn(elem){ el = elem; timeIn = setInterval( function(){ var element = el.nextSibling; var elemOpacity = element.style.opacity; element.innerHTML = elemOpacity; if (elemOpacity < 1.0){ element.style.opacity = parseFloat(elemOpacity) + 0.1; } else{ clearInterval(timeIn); } },100); } ... Code (markup):
The problem is the this keyword in fadeIn(this). When you first onfocus the text box, this is the textbox. When the code runs to setTimeout, ie., timeIn = setTimeout(fadeIn, 100); this becomes global object because the running scope is changed to global scope after running setTimeout. Here is another example of fadeIn and fadeOut using setTimeout. http://www.pagecolumn.com/javascript/fade.htm