JavaScript - Settimeout And Elemid Compatibility Problem
Hello all.
I am doing an experiment with setTimeout for a much larger project and cant seem to get this bit of code working. What is "supposed" to happen is on hover the div goes black, and on removing the mouse it turns red after 1 second. however, it doesnt work. ive tried a bunch of variations but nothing gets it to work. i want to line up a bunch of divs and not need to write a seperate function for each one. any ideas? here is the HTML: Code: <div id="0" onMouseOver="blackit('0')" onMouseOut="fadeit('0')"></div> <div id="1" onMouseOver="blackit('1')" onMouseOut="fadeit('1')"></div> <div id="2" onMouseOver="blackit('2')" onMouseOut="fadeit('2')"></div> <div id="3" onMouseOver="blackit('3')" onMouseOut="fadeit('3')"></div> here is the JavaScript: Code: function blackit(elemID) { document.getElementById(elemID).style.backgroundColor="#000"; } function fadeit(elemID) { setTimeout("document.getElementById(elemID).style.backgroundColor='red'", 1000); } there is some CSS but nothing crazy. it should work but it doesnt. the black on hover works but then it either stays black or goes red immediately, not waiting the 1 second. thanks Similar Tutorialshi, i'm making a page with an image on it. when that image is clicked i want it to make one div visible, and also run the javascript function to make a second div visible after 2 seconds. Everything seems to work correctly except that the javascript runs on page load instead of waiting for when the image is clicked. any help much appreciated. thanks! Here's the javascript: <code <script type="text/javascript"> function showIt() { document.getElementById("show_1").style.visibility = "visible"; } setTimeout("showIt()", 2000); </script> </head> </code> Here's the html: <code> <div id="flyer1">content <div id="show_1" style="visibility:hidden">content </div> </div> <div id="image"> <a href="javascript:void(0)" onclick="MM_showHideLayers('flyer1', '','show')"; "showIt()">image</a> </div> </code> I'm working on a disjointed rollover, with several links changing an image in another location. There is a default image that appears when the page opens and whenever you roll off any of the links. Initially, the problem was that mousing from one link to the next caused a quick flash of the default image because there is a little space between these links. To address that, I added a time out to keep the default image from appearing immediately on onmouseout. Now, when I mouse from one link to the next I get a smooth transition, but then the delayed onmouseout function kicks in while still hovering over a link. How can I make hovering over a new link override this delayed onmouseout? Here's the script: Code: <script type="text/javascript"> window.onload = preloader() function preloader(){ var pic1 = new Image(); pic1.src = "images/cover1.jpg"; var pic2 = new Image(); pic1.src = "images/cover2.jpg"; var pic3 = new Image(); pic1.src = "images/cover3.jpg"; var pic4 = new Image(); pic1.src = "images/cover4.jpg"; } function bookInfoSwap(imgSrc,ID,bInfo) { document.getElementById("covers").src = imgSrc; document.getElementById("courseID").innerHTML = ID; document.getElementById("bookInfo").innerHTML = bInfo; } function swapDelay() { setTimeout("bookInfoRevert()",3000); } function bookInfoRevert() { document.getElementById("covers").src = "images/covers.gif"; document.getElementById("courseID").innerHTML = " "; document.getElementById("bookInfo").innerHTML = " "; } </script> ...and a couple of the links: Code: <a href="http://www.mymathlab.com/" target="_blank" onmouseover="bookInfoSwap('images/cover6.jpg','Self Study Course ID: <br />cos68804','Billstein, <em>A Problem Solving approach to Mathematics for Elementary School Teachers, 9/e and Custom Edition</em>');" onmouseout="swapDelay();" class="courseTab">Math 10/11</a> <a href="http://www.mymathlab.com/" target="_blank" onmouseover="bookInfoSwap('images/cover4.jpg','Self Study Course ID: <br />cos59796','Sullivan, <em>Statistics: Informed Decisions Using Data, 3/e</em>');" onmouseout="swapDelay();" class="courseTab">Math 21</a> Thanks. I have 2 news tickers that I want to show one after the other. They are both widgets (javascript) that I grabbed from the stated website. However to get one to run after the other I felt like I needed a setTimeout(). So I made one of them delayed (ticker8) but instead of JUST appearing after 5000 ms, it appears and EVERYTHING ELSE DISAPPEARS. I know that it's something silly I just can't figure out what it is. The HTML code is below. [CODE] <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script LANGUAGE='JavaScript' type='text/javascript' SRC='http://www.theFinancials.com/syndicated/Free/EXk_EconomicStats_US.js'></script> </head> <body> <div id="ticker6"> <script LANGUAGE='JavaScript' type='text/javascript' SRC='http://www.theFinancials.com/syndicated/Free/EXk_Interest_TBills.js'></script> <script LANGUAGE='JavaScript' type='text/javascript'> document.writeln(EXk_Interest_TBills('0050201336','100%','C9C9C9','yes','6B6B6B','Arial',11,1,'37373 7')); </script> </div> <div id="ticker8"> <script type="text/javascript"> setTimeout("ticker8()", 5000); function ticker8() { <!--START theFinancials.com Content--> <!--copyright theFinancials.com - All Rights Reserved--> document.writeln(EXk_EconomicStats_US('0199604514','100%','C9C9C9','yes','6B6B6B','Arial',11,1,'3737 37')); <!--END theFinancials.com Content--> } </script> </div> </body> </html> [CODE] Would really appreciate some help with this one. Many thanks in advance Hello, I have two frames, one to the left, one to the right. The left one contains a form, which I'm using to take in user input, and at the same time to refresh the frame on the right. The left frame's code is: Code: <html> <head> <script type="text/javascript"> function reload_right_frame() { parent.right_frame.location.reload(); } </script> </head> <form method="post"> <input type="submit" value="Enter" onClick="reload_right_frame();"> <input type='text' name='userinput'> </form> <?php echo "You entered: " . $_POST['userinput']; ?> </html> This succeeds in spewing out what the user entered, and simultaneously refreshing the right-hand frame. However, I want there to be a delay in refreshing the right-hand frame, so I changed the left-frame coding as follows: Code: <html> <head> <script type="text/javascript"> function delayed_reload() { var t=setTimeout("reloadframe()",3000); } function reload_right_frame() { parent.right_frame.location.reload(); } </script> </head> <form method="post"> <input type="submit" value="Enter" onClick="delayed_reload();"> <input type='text' name='userinput'> </form> <?php echo "You entered: " . $_POST['userinput']; ?> </html> This is where it stops working. The right-hand frame is not reloaded at all. I want it to reload after 3 seconds. The user input text is spewed out, though. If I change the input type from "submit" to "button", however, the delayed reload of the right-hand frame works fine, but then the user input text fails to show. How can I make both form and delayed reload both work? I'm probably missing something obvious. Thanks in advance for any help! Hello everybody I need your help in this problem At first, this is the code used HTML Code PHP 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> JavaScript Code PHP 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); } 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 Hello, so i got one question. I have this Java Script of old facebook chat which works great at chrome and firefox with greasemonkey but when i tried to put this at IE9 with IEPro plugin , facebook just went crazy. Cant open chat at all, also all site is broken. What is problem with this script at IE,Safari or Opera? Maybe you can help me thx. You can find that script here : www.fu.sk/107159.user.js I adapted (well, attempted to, at least) a quote/testimonial rotation script to fit into my website. The script works PERFECTLY on Firefox but after making my modifications, I killed it in IE...and being a total n00b to JavaScripting.....I'm totally stumped. In Firefox, the script shows at the proper height. In Internet Explorer, the script is only shown at ~40 pixels and doesn't seem to be rotating through the different quotes (it still fades but it fades the same quote back and forth). The obvious question: HOW DO I FIX IT?!!? Original script was found at: http://www.caodesigns.com/blog/tutor....php?postID=33 My script is at: http://www.digitalctrl.org/help.html (right sidebar, in the "Testimonials" box). But something I want to know for future reference.......what is it that causes things to be formatted differently across browsers? This cross browser INcompatability is giving me grey hairs. I've been lurking around your community for a while now.....I hope you gents don't mind my first post being a question. If I need to reformat my post or do anything else to get assistance, please let me know so I can take care of it. I am trying to dynamically add rows to a table when the user clicks a button. here my function Code: function addFocusArea() { if(addTlFocusAreaCount <= 5) { //Create new Title row var titleRow = document.createElement("tr"); var titleCol = document.createElement("th"); var titleText = document.createTextNode("Additional Focus Area " + addTlFocusAreaCount); titleCol.appendChild(titleText); titleRow.appendChild(titleCol); document.getElementById("focusTable").appendChild(titleRow); //Create new category row var categoryRow = document.createElement("tr"); var categoryCol = document.createElement("td"); var categorySelect = document.createElement("select"); var categories = document.getElementById("<%=DecisionToolKeys.PRIMARY_FOCUS%>"); //copy a dropdown menu that is already existing on the page for(var i=0; i<categories.length; i++) { var option = document.createElement("option"); option.value = categories[i].value; option.text = categories[i].text; categorySelect.options.add(option); } categoryCol.appendChild(categorySelect); categoryRow.appendChild(categoryCol); document.getElementById("focusTable").appendChild(categoryRow); addTlFocusAreaCount++; } else { alert("You cannot add more than five additional practice areas."); } } And here is my button Code: <input type="button" value="Add Focus Area" onclick="JavaScript:addFocusArea()"/> This is working in Firefox and Chrome, but not IE 8. Any clue as to why? Thanks, Nick Okay, for some reason the setTimeout isn't working for me, and I have no idea why. I've tried everything and Googled even more. If anyone has any ideas, I'll be grateful Code: function display(min,sec) { if (sec <= 0) { sec=60; min-=1; } if (min <= -1) { sec=0; min=0; tEnd(); } else { sec = sec-1; } if (sec<=9) { sec = "0" +sec; } document.form.time.value=min+":"+sec; SM = window.setTimeout("display("+min+","+sec+")",1000); } function tEnd() { window.clearTimeout(SM); alert('Your time is up!'); } Thanks in advance. Hello - I've got this lovely little animation that slides some div fields to the right a short distance. Everything works except the setTimeout (located in the SlideIn function). It simply 'jumps' without taking any time at all. I've tried a bunch of stuff: changed the amount of time from 100 to 10000 changed it from var t = setTimeout("SlideIn()", 1000) SlideIn with/without the brackets, with/without the quotation marks. SlideIn() SlideIn(i) SlideIn(label_id_fixed) SlideIn(label_id_no) Just about at the end of my rope, and so many different combinations I'm forgetting which ones I've tried and which I haven't. I know it is looping through because it gets to the end position and allows the other JavaScript functions to work ok. So it is not getting 'stuck' or anything like that. Here is the complete code (there is a style sheet located separately). Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="class.css" /> </head> <script type="text/javascript"> //<![CDATA[ window.onload=starter; function starter(){ collapseMenu(); SetUpAnimation(); } function SetUpAnimation(){ if (document.querySelectorAll) { labels = document.querySelectorAll('div.label'); } else if (document.getElementsByClassName) { labels = document.getElementsByClassName('label'); } //loops through the labels if (labels){ for (var i=1; i <= labels.length; i++) {SlideIn(i); } } } function SlideIn(label_id_no){ var label_id_fixed = label_id_no; var endPos = 150; var currentPos = 0; for (currentPos = 1; currentPos < 60; currentPos++){ var label_id_name = "label" + label_id_fixed; document.getElementById(label_id_name).style.left = currentPos + "px"; setTimeout("SlideIn", 1000); } } function collapseMenu(){ var elems = null; var labels = null; if (document.querySelectorAll) { elems = document.querySelectorAll('div.elements'); labels = document.querySelectorAll('div.label'); } else if (document.getElementsByClassName) { elems = document.getElementsByClassName('elements'); labels = document.getElementsByClassName('label'); } if (elems){ for (var i=0; i < elems.length; i++) { elems[i].style.display="none"; } for (var i=0; i < labels.length; i++) { labels[i].onclick=showBlock; } } } function showBlock(evnt){ var theEvent = evnt ? evnt : window.event; var theSrc = theEvent.target ? theEvent.target: theEvent.srcElement; var itemId = "elements" + theSrc.id.substr(5,1); var item = document.getElementById(itemId); if (item.style.display=='none'){ item.style.display='block'; }else{ item.style.display='none'; } } //]]> </script> </head> <body> <div class="label" id="label1">this is a label</div> <div class="elements" id="elements1"> <p>painting</p><br /> <p>photography</p><br /> </div> <div class="label" id="label2">this is another label</div> <div class="elements" id="elements2"> <p>sculpture</p><br /> <p>ceramics</p><br /> </div> </body> </html> Is there another JS function that I can use to force a time delay without having the code continue to run? I'm using the setTimeout() function but the call to this function doesn't stop the code flow. I need to stop the code flow while waiting. I guess I need a Sleep() type of JS function. What I'm trying to do is display some blank text on the screen using a for loop (I'm using <BR> to give the appearance of "opening up" a vertical window section in the browser) and I need this 'text' to complete before allowing the following code in the function to execute. The following code will display a Table with rows of data. I'm trying to use a timing function to give a visual impression of a window opening up just before the data displays. Thanks... Hello guys I need to get something fun! with setTimeout function! I am n00b! so be patent please. I need when <body onload="Myfunc();"> fires, that function should show "Please wait...!" or "Loading...". for , say 5 seconds!. then it disappear. I used setTimeout with that but it didn't do what I wanted! here is my code: PHP Code: function Myfunc(){ document.getElementById("ss2").innerHTML = "Loading..."; setTimeout("Myfunc();", 5000); } // where id="ss2" is the place to display the string "loading..." ! and a one more question ! can I do something like a while loop! where it holds *i* value as seconds! and for every second it passes it should print out a string I make it up ! let say loop for 3 seconds ! So, when seconds = 0 then display "string of second 0" and stick it in there, then go to the next second when it is exactly = 1 then display "new line with string of second 1" and stick it in there, then do to the last second when it is exactly = 2 then display " new line with string of second 2" and stick it in there, exit the loop! is there anyway to do that? please note that I am a n00bie ! help is much appreciated ! Hi trying to load a random swf files using setTimeout please help Code: </head><script type="text/javascript"> var numberOfSongs = 3 var sound = new Array(numberOfSongs+1) sound[1]= "number/1.mp3" sound[2]= "number/2.mp3" sound[3]= "number/3.mp3" function randomNumber(){ var randomLooper = -1 while (randomLooper < 0 || randomLooper > numberOfSongs || isNaN(randomLooper)){ randomLooper = parseInt(Math.random()*(numberOfSongs+1)) } return randomLooper } var randomsub = randomNumber() var soundFile = sound[randomsub] document.write ('<EMBED src= "' + soundFile + '" hidden=true autostart=true loop=false>') setTimeout(randomNumber,4000); </script> <body onload="randomNumber()"> Hi all, I've noticed that setTimeout seems to return a simple integer as it's "id" which can be used to clear the timeout ahead of time. So, in order to have multiple setTimeouts called (which requires the previous one to be cleared before the next one is called), I simply did this: Code: clearTimeout(setTimeout(function() { /* some code */ }, 1000) -1); Note the "-1"... each time this code is called, it starts a new setTimeout and clears "instance-1" which is supposed to be the previous instance. The idea is that this block can be called hundreds of times, and when the calling finally stops, the inner code is executed 1 second later. This SEEMS to be working (yes, even in MSIE!). Question is, am I fooling myself? Is this wrong? If so, what's the right way to do it? Thanks... -- Roger (btw, the actual use of this is dynamic resizing of a DIV by dragging the corner with the mouse.... I want the actual PX size to display live while resizing, then after resizing stops, the size display goes away 1 second later... in case you were wondering). Here is my code: Quote: <script> var confirmationPageURL = "http://google.com"; // Add handler for Ecwid's OnPageLoad event if ( typeof(Ecwid) == 'object' && typeof(Ecwid.OnPageLoad) == 'object' ) { Ecwid.OnPageLoad.add(function(page) { // Redirect user if needed if ( typeof(page) == 'object' && 'ORDER_CONFIRMATION' == page.type ) { window.location = confirmationPageURL; window.setTimeout(confirmationPageURL, 8000, true); } }); } </script> I'm just doing a simple redirect after a purchase is made from a shopping cart I use on my site. However, I can't get the window.setTimeout working. The page is instantly redirected and not 8 seconds. I'm sure I have wrong syntax or placement. Who knows. I know nothing about JS. Any help is appreciated. Thank you Hi there The JavaScript below behaves erratically - sometimes the timing is perfect, at other times it show 20 mins has passed when only 6 has in reallity - quite some gain - I'm baffled! Code: Public Function SessionTime(ByVal DivName As Panel) As String Dim vTime As String = "var sessionTimeout = 19; " & vbCr vTime += "function ReadCookie(cookieName) " & vbCr vTime += "{ " & vbCr vTime += "var theCookie=""""+document.cookie; var ind=theCookie.indexOf(cookieName); " & vbCr vTime += "if (ind==-1 || cookieName=="""") return """";" & vbCr vTime += "var ind1=theCookie.indexOf(';',ind); " & vbCr vTime += "if (ind1==-1) ind1=theCookie.length; " & vbCr vTime += "return unescape(theCookie.substring(ind+cookieName.length+1,ind1));" & vbCr vTime += "} " & vbCr vTime += "function DisplaySessionTimeout()" & vbCr vTime += "{ " & vbCr 'assigning minutes left to session timeout to Label vTime += "if (sessionTimeout > 1) " & vbCr vTime += "{ " & vbCr vTime += "document.getElementById('" & DivName.ClientID & "').innerText = sessionTimeout + "" Minutes remaining until session timeout!""; " & vbCr vTime += "} " & vbCr vTime += "else " & vbCr vTime += "{ " & vbCr vTime += "document.getElementById('" & DivName.ClientID & "').innerText = ""ONLY ONE MINUTE REMAINS UNTIL SESSION TIMEOUT!""; " & vbCr vTime += "}" & vbCr vTime += "sessionTimeout = sessionTimeout - 1; " & vbCr vTime += "var Posted = ReadCookie('PostedValue'); " & vbCr vTime += "if (Posted == 0)" & vbCr vTime += "{ " & vbCr vTime += "sessionTimeout = 19; " & vbCr vTime += "var expires = new Date(); " & vbCr vTime += "expires.setUTCFullYear(expires.getUTCFullYear() + 1); " & vbCr vTime += "document.cookie = 'PostedValue=1; expires=' + expires.toUTCString() + '; path=/'; " & vbCr vTime += "}" & vbCr 'if session is under preset warning vTime += "if (sessionTimeout > 5) " & vbCr '<--------------- 4 vTime += "{ " & vbCr vTime += "document.getElementById('" & DivName.ClientID & "').style.visibility=""hidden""; " & vbCr vTime += "}" & vbCr vTime += "else " & vbCr vTime += "{" & vbCr vTime += "document.getElementById('" & DivName.ClientID & "').style.visibility=""visible""; " & vbCr vTime += "}" & vbCr 'if session is not less than 0 vTime += "if (sessionTimeout >= 1) " & vbCr 'call the function again after 1 minute delay vTime += "{ " & vbCr vTime += "setTimeout('DisplaySessionTimeout()', 60000); " & vbCr '<------60000 vTime += "} " & vbCr vTime += "else " & vbCr vTime += "{ " & vbCr 'show message box vTime += "alert(""Your current Session will expire in approx one minute""); " & vbCr vTime += "} " & vbCr 'vTime += "alert(""Set to "" + ReadCookie('PostedValue')); " & vbCr vTime += "} " & vbCr vTime += "DisplaySessionTimeout();" & vbCr Return vTime End Function Code: function funt() { var link = document.getElementsByClassName("class")[0]; if(link != null) { var i = 0; if(check != link.childNodes[i]) { link.childNodes[i].click(); check = link.childNodes[i]; } else { window.location = "website" } } else { if(document.getElementById('enbut').value != "some value") { document.getElementById('id').click(); } window.location = "website" } t=setTimeout("funt()",3000); } with this i'm trying to get it to loop every 3 seconds using the settimeout function at the end of the loop. each time i run this it just runs once and exits. anyone know what i'm doing wrong? I wrote the code below to animate a roll of dice. It does iterate 10 times, as the code intends, but for some reason it doesn't pause in between. Also, how can I get it to return the final dice value to the calling function? Code: DiceValue=RollDiceAnimated(1) function RollDiceAnimated(RollIteration) { var Die1;var Die2 var RollSpeed=100 Die1=0;while(Die1<1 || Die1>6){Die1=Math.floor(Math.random()*7)} Die2=0;while(Die2<1 || Die2>6){Die2=Math.floor(Math.random()*7)} document.getElementById("Dice1").src="Images_Dice/Dice" + Die1 + ".jpg" document.getElementById("Dice2").src="Images_Dice/Dice" + Die2 + ".jpg" if(RollIteration<10){ var tempval=setTimeout(RollDiceAnimated(RollIteration+1),RollIteration*RollSpeed) } else{return Die1+Die2} } I'm trying to set a timer when someone moves off of an image. When I try my event without the timer there are no problems but it throws syntax or object expected errors (if I play with the quotes some) when I add in the timer. This is inline code on the image. onMouseout="newsTimer = setTimeout("Effect.toggle('news', 'slide')", 500)"; It is likely something simple I am overlooking but I cannot find any answers after a long search. Thank you for any and all help. I'm trying to delay this line by 1 second, but can't seem to figure out the syntax. Code: window.location.href="index.php?vid_id="+<?php echo $vid_id +1 ?>; this is the entire function Code: $('#cancel').click(function() { $.ajax({ type: "POST", url: "scripts/greenlight.php?vid_id="+<?php echo $vid_id ?>, data: "vote=2", success: function(){ }}); document.getElementById("greenlight").src="img/greenlight_btns/greenlight_btn.png"; document.getElementById("cancel").src="img/greenlight_btns/cancel_btnOver.png"; //window.location.href="index.php?vid_id="+<?php echo $vid_id +1 ?> window.setTimeout(function() { window.location.href="index.php?vid_id="+<?php echo $vid_id +1 ?>; }, 500); }); // end click |