JavaScript - Stop Multiple Onmouseover Firing Continuously
Hello all,
I have a question regarding onmouseover on "a" tag. I currently have a list of "img" thumbnails which have onMouseOver attached to the "a" tag which wraps the "img". When the mouse is over the image, a "preview" of the image will load in another div via a javascript function, this javascript function has a jquery fadeto effect so the preview will fade into view. The problem now is if a user hover over multiple thumbnails quickly, the onMouseOver event is registered multiple times, so when the user finally stop hovering over multiple thumbnails quickly, the last thumbnail will receive the event multiple times and fades in not only once. Below is my code: function previewimage(loadimg){ jloadimg='<img src="../images/'+loadimg+'.png" />'; //stimulate a fade in effect by making the image has 0.7 opacity first $(#largeimage).fadeTo('fast', 0.7, function() { }); $(#largeimage).fadeTo('slow', 1, function() { }); document.getElementById('largeimage').innerHTML=jloadimg; } for the list of thumbnail images, I have: <a onMouseOver="previewimage('imagefile1');"><img src="path/to/thumbnail/image1.png" /></a> <a onMouseOver="previewimage('imagefile2');"><img src="path/to/thumbnail/image2.png" /></a> <a onMouseOver="previewimage('imagefile3');"><img src="path/to/thumbnail/image3.png" /></a> How do I cancel multiple event from running continuosly if the previous one is still in queue? Similar TutorialsI'm writing a GUI css/html editor in JavaScript which is a litte ambitious considering I just started with js like a month ago. Here's my first hurdle: Users can add divs simply by clicking on the div or element in which they want the new div to reside. The creation of a new div is in the onclick event. However, when I click on a div, I'm getting an onclick events from it and all the divs positions below it, so it's creating multiple new divs and all I want is one! Is there any way to make the onclick even fire for just the top layer div? Maybe using the z-index or something? Please help if you can - I couldn't find anything related to this at all. Thanks Hi. I've been working on a project for some time now, and just recently I installed Firefox. Now, part of the site (which works perfectly in IE6/7) doesn't work in Firefox. Here is part of the code: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Meniu de navigare</title> </head> <body bgcolor="#000437"> <table width="119" style="position:relative; top:35%"> <a href="pag_start.html" rel="nofollow" target="continut"><tr><td class="nav_bar" height="24" background="p1.png" valign="center" onmouseover="background='p2.png'" onmouseout="background='p1.png'" onmousedown="background='p3.png'" onmouseup="background='p2.png'">Home</td></tr></a> blah blah blah </table> </body> </html> (I didn't copy all of the code because it's basically the same all the way down) The main problem is with the link (Firefox apparently doesn't recognize table rows as links). The second problem is with the onmouseover/onmouseout etc handlers (absolutely nothing happens). Any ideas how to solve this? Thanks. Bye. PS: just in case you need to know, the code is for a nav bar. for example i have: a picture of a man sitting down a gif of him going from the sitting position to the standing position and picture of him standing i want the man to sit when the page is loaded, go to the standing animation onMouseOver, and when the animation is complete, stop the animation by going to the standing picture i have heard of two ways to do this but i dont know the best way, or if there is a third alternative with PHP or another language i could make a timer of the same period of time it takes for the standing gif to complete. i havent done any testing but i would suspect that there would be a bug with this method. some older computers load slower, and the gif may finish its animation before the timer is complete, or the timer may complete before the gif has finished its animation. this might cause gif to start a new cycle before the browser changes pictures, or the browser might change pictures before the man is finished standing. if you know for a fact that this will not happen, or if its occurrence is extremely rare, please alleviate my fears the second option is to break the gif down with some piece of software into jpegs and make many timers to reassemble the animation. this method was not suggested to me, i came up with it myself, so i dont trust that this is the best way to do things properly anyone who has ever done this sort of rollover animation in any language, your input would be greatly appreciated JavaScript Code: window.addEvent('domready',function(){ //SAMPLE 8 var handles8_more = $$('#handles8_more span'); var nS8 = new noobSlide({ box: $('box8'), interval: 5000, autoPlay: true, items: $$('#box8 h3'), size: 900, handles: $$('#handles8 span'), handle_event: 'mouseenter', addButtons: { previous: $('prev8'), play: $('play8'), stop: $('stop8'), playback: $('playback8'), next: $('next8') }, onWalk: function(currentItem,currentHandle){ //style for handles $$(this.handles,handles8_more).removeClass('active'); $$(currentHandle,handles8_more[this.currentIndex]).addClass('active'); //text for "previous" and "next" default buttons $('prev8').set('html','<< '+this.items[this.previousIndex].innerHTML); $('next8').set('html',this.items[this.nextIndex].innerHTML+' >>'); } }); //walk to item 0 witouth fx nS8.walk(0,false,true); }); html Code: <div class="slider sample8"> <p class="buttons" id="handles8"> <span>Item 1</span><span>Item 2</span><span>Item 3</span><span>Item 4</span><span>Item 5</span> </p> <div class="mask1"> <div id="box8"> <div onMouseOver="nS8.Stop();" onMouseOut="nS8.Play();"> </div> </div> </div> <p class="buttons"> <span id="prev8"><< Previous</span> | <span id="next8">Next >></span> </p> <p class="buttons"> <span id="playback8">< Playback</span> <span id="stop8">Stop</span> <span id="play8">Play ></span> </p> </div> All I need to do is when they hover ocer the div statement stop the program from looping. and then when they stop hovering over it let it start looping again. Hey all, First off, just wanted to send a big thanks out to everyone on this board that has helped me along my path, you all have been a really big help! Ok, now on to today's question. I have a nice little script that changes a company's logo (displayed in a side bar) when the user mouses over a part of an image map. Here is the basic code: Code: <head> <?php //assign array of links to string $row_limit = $num_rows - 1; for ($otmm_loop=0;$otmm_loop<$num_rows;$otmm_loop=$otmm_loop+1) { if ($otmm_loop == 0) { $otmm_image_string = "$pic_adr_array[$otmm_loop]".","; } elseif ($otmm_loop == $row_limit) { $otmm_image_string = "$otmm_image_string"."$pic_adr_array[$otmm_loop]"; } else { $otmm_image_string = "$otmm_image_string"."$pic_adr_array[$otmm_loop]".","; } } $s1 = "$otmm_image_string"; $qs1 = "\"".implode("\",\"",explode(",",$s1))."\""; <script type="text/javascript"> function doChanges(y){ var z= y; var imagevar = myimages[z]; var imagethis = this.href; changeimage(imagevar,imagethis); } </script> <script type="text/javascript"> function changeimage(towhat,url){ if (document.images){ document.images.targetimage.src=towhat.src gotolink=url } } function warp(){ window.location=gotolink } </script> <script type="text/javascript"> var myimages=new Array() var gotolink="#" function preloadimages(){ for (i=0;i<preloadimages.arguments.length;i++){ myimages[i]=new Image() myimages[i].src=preloadimages.arguments[i] } } preloadimages(<?echo("$qs1");?>); </script> </head> <body> <a href="javascript:warp()"><img src="/images/OnTheMiningMap/rilogo.png" name="targetimage" border="2"></a> <img src="http://www.the-rational-investor.com/images/OnTheMiningMap/<?echo("$map_version");?>" BORDER="2" usemap="#mymap"> <MAP NAME="mymap"> <area shape="rect" coords="<?echo("$rilogo_x_start");?>,<?echo("$rilogo_y_start");?>,<?echo("$rilogo_x_end");?>,<?echo("$rilogo_y_end");?>" onMouseover="doChanges(0)" href="http://www.therationalinvestor.ca/" rel="nofollow" target="_blank" Title="The Rational Investor" alt="The Rational Investor"> <area shape="rect" coords="<?echo("$autism_x_start");?>,<?echo("$autism_y_start");?>,<?echo("$autism_x_end");?>,<?echo("$autism_y_end");?>" onMouseover="doChanges(1)" href="http://www.autismbc.ca/" rel="nofollow" target="_blank" Title="Autism Society of BC" alt="Autism Society of British Columbia"> <area shape="rect" coords="<?echo("$britania_x_start");?>,<?echo("$britania_y_start");?>,<?echo("$britania_x_end");?>,<?echo("$britania_y_end");?>" onMouseover="doChanges(2)" href="http://www.britaniaminingmuseum.ca/" rel="nofollow" target="_blank" Title="Britannia Mining Museum" alt="Britannia Mining Museum"> <area shape="rect" coords="<?echo("$sable_x_start");?>,<?echo("$sable_y_start");?>,<?echo("$sable_x_end");?>,<?echo("$sable_y_end");?>" onMouseover="doChanges(3)" href="http://sableresources.com/" rel="nofollow" target="_blank" Title="Sable Resources - Shasta" alt="Sable Resources - Shasta"> <area shape="rect" coords="<?echo("$northgate_x_start");?>,<?echo("$northgate_y_start");?>,<?echo("$northgate_x_end");?>,<?echo("$northgate_y_end");?>" onMouseover="doChanges(4)" href="http://northgateexploration.com/Home/default.aspx" rel="nofollow" target="_blank" Title="Northgate Resources - Kemess South" alt="Northgate Resources - Kemess South"> <area shape="rect" coords="<?echo("$thompson_x_start");?>,<?echo("$thompson_y_start");?>,<?echo("$thompson_x_end");?>,<?echo("$thompson_y_end");?>" onMouseover="doChanges(5)" href="http://www.thompsoncreekmetals.com/s/Home.asp" rel="nofollow" target="_blank" Title="Thompson Creek Metals - Endako" alt="Thompson Creek Metals - Endako"> <area shape="rect" coords="<?echo("$imperial_x_start");?>,<?echo("$imperial_y_start");?>,<?echo("$imperial_x_end");?>,<?echo("$imperial_y_end");?>" onMouseover="doChanges(6)" href="http://www.imperialmetals.com/s/Home.asp" rel="nofollow" target="_blank" Title="Imperial Metals - Huckleberry" alt="Imperial Metals - Huckleberry"> <area shape="rect" coords="<?echo("$westerncoal_x_start");?>,<?echo("$westerncoal_y_start");?>,<?echo("$westerncoal_x_end");?>,<?echo("$westerncoal_y_end");?>" onMouseover="doChanges(7)" href="http://www.westerncoal.com/" rel="nofollow" target="_blank" Title="Western Coal - Brule, Dillon, Perry Creek" alt="Western Coal - Brule, Dillon, Perry Creek"> <area shape="rect" coords="<?echo("$peaceriver_x_start");?>,<?echo("$peaceriver_y_start");?>,<?echo("$peaceriver_x_end");?>,<?echo("$peaceriver_y_end");?>" onMouseover="doChanges(8)" href="http://www.peacerivercoal.com/" rel="nofollow" target="_blank" Title="Peace River Coal" alt="Peace River Coal"> <area shape="rect" coords="<?echo("$teckcoal1_x_start");?>,<?echo("$teckcoal1_y_start");?>,<?echo("$teckcoal1_x_end");?>,<?echo("$teckcoal1_y_end");?>" onMouseover="doChanges(9)" href="http://www.teck.com/Generic.aspx?portalName=tc" rel="nofollow" target="_blank" Title="Teck Coal Fording River" alt="Teck Coal Fording River"> <area shape="rect" coords="<?echo("$teckcoal2_x_start");?>,<?echo("$teckcoal2_y_start");?>,<?echo("$teckcoal2_x_end");?>,<?echo("$teckcoal2_y_end");?>" onMouseover="doChanges(9)" href="http://www.teck.com/Generic.aspx?portalName=tc" rel="nofollow" target="_blank" Title="Teck Coal Greenhills" alt="Teck Coal Greenhills"> <area shape="rect" coords="<?echo("$teckcoal3_x_start");?>,<?echo("$teckcoal3_y_start");?>,<?echo("$teckcoal3_x_end");?>,<?echo("$teckcoal3_y_end");?>" onMouseover="doChanges(9)" href="http://www.teck.com/Generic.aspx?portalName=tc" rel="nofollow" target="_blank" Title="Teck Coal Line Creek" alt="Teck Coal Line Creek"> <area shape="rect" coords="<?echo("$teckcoal4_x_start");?>,<?echo("$teckcoal4_y_start");?>,<?echo("$teckcoal4_x_end");?>,<?echo("$teckcoal4_y_end");?>" onMouseover="doChanges(9)" href="http://www.teck.com/Generic.aspx?portalName=tc" rel="nofollow" target="_blank" Title="Teck Coal Elkview" alt="Teck Coal Elkview"> <area shape="rect" coords="<?echo("$teckcoal5_x_start");?>,<?echo("$teckcoal5_y_start");?>,<?echo("$teckcoal5_x_end");?>,<?echo("$teckcoal5_y_end");?>" onMouseover="doChanges(9)" href="http://www.teck.com/Generic.aspx?portalName=tc" rel="nofollow" target="_blank" Title="Teck Coal Coal Mountain" alt="Teck Coal Coal Mountian"> <area shape="rect" coords="<?echo("$imperial2_x_start");?>,<?echo("$imperial2_y_start");?>,<?echo("$imperial2_x_end");?>,<?echo("$imperial2_y_end");?>" onMouseover="doChanges(10)" href="http://www.imperialmetals.com/s/Home.asp" rel="nofollow" target="_blank" Title="Imperial Metals - Mount Polley" alt="Imperial Metals - Mount Polley"> <area shape="rect" coords="<?echo("$teck_x_start");?>,<?echo("$teck_y_start");?>,<?echo("$teck_x_end");?>,<?echo("$teck_y_end");?>" onMouseover="doChanges(11)" href="http://www.teck.com/Generic.aspx?portalName=tc" rel="nofollow" target="_blank" Title="Teck - Huckleberry" alt="Teck - Huckleberry"> <area shape="rect" coords="<?echo("$taseko_x_start");?>,<?echo("$taseko_y_start");?>,<?echo("$taseko_x_end");?>,<?echo("$taseko_y_end");?>" onMouseover="doChanges(12)" href="http://www.tasekomines.com/tko/Home.asp" rel="nofollow" target="_blank" Title="Taseko - Gibralar" alt="Taseko - Gibralar"> <area shape="rect" coords="<?echo("$roca_x_start");?>,<?echo("$roca_y_start");?>,<?echo("$roca_x_end");?>,<?echo("$roca_y_end");?>" onMouseover="doChanges(13)" href="http://www.rocamines.com/s/Home.asp" rel="nofollow" target="_blank" Title="Roca - Max" alt="Roca - Max"> <area shape="rect" coords="<?echo("$breakwater_x_start");?>,<?echo("$breakwater_y_start");?>,<?echo("$breakwater_x_end");?>,<?echo("$breakwater_y_end");?>" onMouseover="doChanges(14)" href="http://www.breakwater.ca/" rel="nofollow" target="_blank" Title="Breakwater - Myra Falls" alt="Breakwater - Myra Falls"> <area shape="rect" coords="<?echo("$hillsborough_x_start");?>,<?echo("$hillsborough_y_start");?>,<?echo("$hillsborough_x_end");?>,<?echo("$hillsborough_y_end");?>" onMouseover="doChanges(15)" href="http://www.hillsboroughresources.com/" rel="nofollow" target="_blank" Title="Hillsborough - Quinsam" alt="Hillsborough - Quinsam"> </MAP> </body> My question is, how can I get three different images (company logo, weekly price chart and monthly price chart - all of which are in an image folder on my server) to change on this one mouseover event. I tried replicating the function three times and altering each function's name but that ended up screwing the whole thing up. Any thoughts/suggestions would be greatly appreciated, Brian hi, please ignore this thread..it is a duplicate of one already active. MODS please delete. apologies for my mistake. Hi, Im a complete newbie to javascript and I've basically copied and pasted the javascript I found here to use on my site. Its an onMouseOver slideshow: http://www.javascriptkit.com/script/...ifferent.shtml to use on my site. Basically, my problem is how do I add a second, separate image in a different location on the web page, associated with this script? If I post <a href="javascript:warp()"><img src="myimage" name="targetimage" border=0></a> in two different locations, which is the script for the image, the script stops working, but having it once makes it work. So how do I add two different image locations? Can someone please help me here? I just want to add more images in a different location. ie have image location 1, and image location 2. Thanks in advance Script Below: Code: <script> function changeimage(towhat,url){ if (document.images){ document.images.targetimage.src=towhat.src gotolink=url } } function warp(){ window.location=gotolink1 } </script> <script language="JavaScript1.1"> var myimages=new Array() var gotolink="#" function preloadimages(){ for (i=0;i<preloadimages.arguments.length;i++){ myimages[i]=new Image() myimages[i].src=preloadimages.arguments[i] } } preloadimages(my images here) </script> For the Links: <a href="creativewriting.html" onMouseover="changeimage(myimages[1],this.href)">Creative Writing</a><br> For the Image: <a href="javascript:warp()"><img src="myimage" name="targetimage" border=0></a> I am very new to javascript and cannot find any info anywhere regarding the following problem: On my website I have around 100 pages containing an action form. Occasionally it is necessary to cancel the action throughout the 100 pages which is very time-consuming. Then the action has to be reinstated once again for all the 100+ pages. I thought the solution would be to use javascript to change the action from a .js file which would mean only one page, the .js file, would require alteration: The action that appears on all 100+ pages several times that I am trying to change or stop happening by overwriting the "form action": <form action="http://www.changenamecart.com/" method="post"> <input type="hidden" name="userid" value="1234567"> <input type="hidden" name="return" value="http://www.thehomepage.co.uk/index.htm"> <input type="image" src="http://www.changenamecart.com/images/pic.gif"> </form> My efforts to date a The change .js file: function change() { var myChange = form action; if(myChange == form action){ document.write("form xction"); } } The html file in the header: <script src="change.js" type="text/javascript"></script> I am afraid that my knowledge of programming is very small and I would welcome any help to solve this problem. How can I write a JavaScript for the following requirement. I have to go to a link say
Quote: www.google.com and refresh it for every 5 seconds continuously. Thanks I have a slideshow on a test page at this link. I want to change it so that the slides loop rather than getting to the end and rewinding back to slide one. Can I alter the code (below) or would it be better to just find another code? Code: <script type="text/javascript"> $(document).ready(function() { var currentPosition = 0; var slideWidth = 1024; var slides = $('.slide'); var numberOfSlides = slides.length; var speed = 3000; slideShowInterval = setInterval(changePosition, speed); slides.wrapAll('<div id="slidesHolder"></div>') slides.css({ 'float' : 'left' }); $('#slidesHolder').css('width', slideWidth * numberOfSlides); function changePosition() { if(currentPosition == numberOfSlides - 1) { currentPosition = 0; } else { currentPosition++; } moveSlide(); } function moveSlide() { $('#slidesHolder') .animate({'marginLeft' : slideWidth*(-currentPosition)}); } });</script> I'm having some problem with this DHTML app. The problem is that when i click on an image button, nothing happens. I have verified that the DOM event handlers are loaded. However, when i click on the images (buttons), nothing happens Code: var PenSize = "3"; var PenColor = "Black"; var LoadFile = ""; var UIstatus = "visible"; var CurrentNote = 0; var BGcolor = "#C7C1A3"; var DataPath = "\Data\\"; var ImageExtension = ".img"; var FileList = []; var SystemPath; var UIstatusLandscape = "visible"; var UIstatusPortrate = "hidden"; var Server = "localhost"; var UserName = "guest"; var Password = "guest"; var NxtNote = new Image(); var Mode = "Landscape"; var DataLibrary = "notes.txt"; document.onkeyup = ToggleUI; // Startup Script if (document.addEventListener) { document.addEventListener("DOMContentLoaded", LoadEventListeners, false); alert("loaded"); } function LoadEventListeners() { // Event Listeners for UI Buttons var eventUp = document.getElementById("UpNote"); var eventPlus = document.getElementById("AddNote"); var eventSave = document.getElementById("SaveNote"); var eventClear = document.getElementById("ClearNote"); var eventDelete = document.getElementById("DeleteNote"); var eventOptions = document.getElementById("Options"); var eventDown = document.getElementById("DownNote"); eventUp.addEventListener("click", NoteUp, false); eventPlus.addEventListener("click", AddNote, false); eventSave.addEventListener("click", SaveNote, false); eventClear.addEventListener("click", ClearSketch, false); eventDelete.addEventListener("click", DeleteNote, false); eventOptions.addEventListener("click", ConfigOptions, false); eventDown.addEventListener("click", NoteDown, false); // Event Listeners for the Options Dialogue var eventDown = document.getElementById("OptionsClose"); eventDown.addEventListener("click", ConfigOptions, false); // Finish the Startup Process Init(); } function Init() { // Get the System Path GetSystemPath("SketchBook.html"); // Load All Filenames of the DataPath directory into an array var TmpLoad = LoadFromDisk(SystemPath + DataPath + DataLibrary); // Check to see if the Notebook is blank if(TmpLoad == null) { // The botebook is Blank alert("Notebook is Blank"); return; } // Parse the CSV file data into an Array FileList = TmpLoad.split(","); //Load the first Note onto the canvas // if there are no notes in the directory, don't try to load anything if(FileList.length < 0) { var Source = LoadFromDisk(FileList[CurrentNote]); NxtNote.src = Source; // Load the NoteBookCounter data into the innerHTML of it's DIV // document.getElementById("NoteBookCounter").innerHTML = "<center><font size='2'>" + CurrentNote + " / " + FileList.length + "</font></center>"; // Load the image data onto the canvas var canvas = document.getElementById('SketchPage').getContext('2d'); canvas.drawImage(NxtNote , 0, 0); return; } } function ConfigOptions() { if (document.getElementById("Options").style.visibility == "hidden") { document.getElementById("Options").style.visibility = "visible"; } else { document.getElementById("Options").style.visibility = "hidden"; } // Modify the variables of any selections that were made PenSize = document.getElementById('GetPenSize').value; PenColor = document.getElementById('GetPenColor').value; } function ToggleUI(e) { var KeyID = (window.event) ? event.keyCode : e.keyCode; // KeyValue 18 is the ALT key var KeyValue = 18; // Use a key to hide the toolbars so that most of the screen is used for the UI // ********** If the device is in Landscape Mode, toggle the Portrate-Style UI Toolbar if(Mode == "Landscape") { if(KeyID == KeyValue) { if(UIstatusLandscape == "visible") { UIstatusLandscape = "hidden"; document.getElementById("UI_Landscape").style.visibility = "hidden"; return; } if(UIstatusLandscape == "hidden") { UIstatusLandscape = "visible"; document.getElementById("UI_Landscape").style.visibility = "visible"; } } } // ********** If the device is in Portrate Mode, toggle the Portrate-Style UI Toolbar if(Mode == "Portrate") { if(KeyID == KeyValue) { if(UIstatusPortrate == "visible") { UIstatusPortrate = "hidden"; document.getElementById("UI_Portrate").style.visibility = "hidden"; return; } if(UIstatusPortrate == "hidden") { UIstatusPortrate = "visible"; document.getElementById("UI_Portrate").style.visibility = "visible"; } } } } function Draw(element, event) { document.addEventListener("mousemove", PenHandler, true); document.addEventListener("mouseup", upHandler, true); event.stopPropagation(); event.preventDefault(); function PenHandler(event) { var x = event.clientX; var y = event.clientY; // mouse event goes here var canvas = document.getElementById("SketchPage"); var ctx = canvas.getContext("2d"); if (PenShape ="Circle") { // This draws a circle ctx.fillStyle = PenColor; ctx.beginPath(); ctx.arc(x, y, PenSize, 0, Math.PI*2, true); ctx.closePath(); ctx.fill(); } event.stopPropagation(); } function upHandler(event) { document.removeEventListener("mouseup", upHandler, true); document.removeEventListener("mousemove", PenHandler, true); event.stopPropagation(); } } function SaveNote() { alert("triggered"); return; // Get the current file name var FileName = SystemPath + DataPath + CurrentNote + ImageExtension; // Convert the Canvas Data into a Base64 encoded PNG image var Note = document.getElementById("SketchPage").toDataURL(); // Write the PNG file to the disk SaveToDisk(FileName, Note); // Update the Note Library file // Read in the current DataLibrary File's Data var Tmp = LoadFromDisk(SystemPath + DataPath + DataLibrary); var NewData = Tmp + CurrentNote + ImageExtension + ","; // Finally Save the updated DataLibrary file SaveToDisk(Tmp, NewData); alert("saved"); } function NoteUp() { // Display the previoius note CurrentNote--; // Make sure you don't incrimnet to a non-existant note if(CurrentNote == -1) { CurrentNote = FileList.length; } var Source = LoadFromDisk(FileList[CurrentNote]); NxtNote.src = Source; // Load the image data onto the canvas // Clear the Pre-existing Canvas Data First ClearSketch(); var canvas = document.getElementById('SketchPage').getContext('2d'); canvas.drawImage(NxtNote, 0, 0); } function NoteDown() { //Display the Next note CurrentNote++; // Make sure you don't incrimnet to a non-existant note if(CurrentNote > FileList.length) { CurrentNote = 0; } var Source = LoadFromDisk(FileList[CurrentNote]); NxtNote.src = Source; // Load the image data onto the canvas // Clear the Pre-existing Canvas Data First ClearSketch(); var canvas = document.getElementById('SketchPage').getContext('2d'); canvas.drawImage(NxtNote, 0, 0); // Update the NoteBookCounter data into the innerHTML of it's DIV //document.getElementById("NoteBookCounter").innerHTML = "<center><font size='2'>" + CurrentNote + " / " + FileList.length + "</font></center>"; return; } function DeleteNote() { // Delete The current note alert("Deleting Page - " + FileList[CurrentNote]); // Remove the file from the File System DeleteFile(FileList[CurrentNote]); // Remove the Element containing the FileName to be deleted from the array for (var x = 0; x < FileList.length; x++) { if(FileList[x] == CurrentNote + ImageExtension) { FileList.splice[x]; return; } } // Rewrite the Library File var TmpData = ""; for (var x = 0; x < FileList.length; x++) { TmpData = TmpData + FileList[x] + ","; } // Write the new Library File SaveToDisk(SystemPath + DataPath + DataLibrary, TmpData); // Load The Previous Note // Display the previoius note CurrentNote--; // Make sure you don't incrimnet to a non-existant note if(CurrentNote == -1) { CurrentNote = FileList.length; } // If the DataLibrary is zero length - just clear the Canvas and Return var TmpLoad = LoadFromDisk(SystemPath + DataPath + DataLibrary); if(TmpLoad == null) { CurrentNote = 0; ClearSketch(); return; } // Your about to place a new image on the Canvas // Clear the Current Canvas Data First ClearSketch(); var Source = LoadFromDisk(FileList[CurrentNote]); NxtNote.src = Source; // Load the image data onto the canvas var canvas = document.getElementById("SketchPage"); var context = canvas.getContext("2d"); canvas.drawImage(NxtNote, 0, 0); } function AddNote() { // Add a note to the notebook and at the end of the File List // **** Later this function should be modified to be an INSERT function rather than just an add // Just incase the user needs to go back an edit and add more things to their notebook var NumberOfNotes = FileList.length; CurrentNote = NumberOfNotes + 1; // Clear the Canvas ClearSketch(); // Write a blank image file to the Data directory so that we have the actual file there var FileName = SystemPath + DataPath + CurrentNote + ImageExtension; // Write it to the disk SaveToDisk(FileName, "Null Content"); // Add the new Note Data to the end of the array FileList.length++; FileList[FileList.length] = CurrentNote + ImageExtension; // Rewrite the Data Library File TmpData = ""; for (var x = 0; x < FileList.length; x++) { TmpData = TmpData + FileList[x] + ","; } // Write the new Data Library to the Disk SaveToDisk(SystemPath + DataPath + DataLibrary, TmpData); // Refresh the Directory List FileList = []; // Load All Filenames of the DataPath directory into an array var TmpLoad = LoadFromDisk(SystemPath + DataPath + DataLibrary); // Parse the CSV file data into an Array FileList = TmpLoad.split(","); } function ClearSketch() { // Clear the contents of the Canvas //Draw a rectangle that covers the canvas var canvas = document.getElementById("SketchPage"); var ctx = canvas.getContext("2d"); ctx.fillStyle = BGcolor; ctx.fillRect (0, 0, canvas.width, canvas.height); } function Crypt(method) { // This function will Encrypt or Decrypt All the NoteData if(method == "encrypt") { return; } if(method == "decrypt") { return; } } function Archive(method) { // This function will Restore or Backup all NoteData to a network resource if(method == "restore") { return; } if(method == "backup") { for(var x = 0; x > FileList.legth; x++) { // Read the data of each note var NoteData = LoadFromDisk(FileList[x]); // Upload the Note to the Server var Url = Server + "/Backup.php?" + x + "?" + NoteData; ajaxRequest(Url); } return; } } // These are the Ajax Functions for Sending and Recieving Files function callback(serverData, serverStatus) { alert(serverData); // Called automatically when we get data back from server } // Display an alert box with the recieved data var url='http://somedomain.com/getdata.php?doc=sometext.txt'; // This is the URL we will call. function ajaxRequest(url) { var AJAX = null; // Initialize the AJAX variable. if (window.XMLHttpRequest) { // Does this browser have an XMLHttpRequest object? AJAX = new XMLHttpRequest(); // Yes -- initialize it. } AJAX.onreadystatechange = function() { // When the browser has the request info.. if (AJAX.readyState == 4 || AJAX.readyState == "complete") { // see if the complete flag is set. callback(AJAX.responseText, AJAX.status); // Pass the response to our processing function } // End Ajax readystate check. } AJAX.open("GET", url, true, UserName, Password); // Open the url this object was set-up with. AJAX.send(null); // Send the request. } // ******************** These are the XPCOM Functions ************************ function GetSystemPath(ApplicationName) { // This function should Detect the system directory of the app // and return that string as the SystemPath variable // You must supply the filename of the HTML file that it is being called from // I suppose later i could add the code to detect the HTML's actual file name // It's on the ToDo List... var GetSysPath = self.location; GetSysPath = GetSysPath + ""; Get = GetSysPath.replace("file:///" , ""); Get = Get.replace(/\//g , "\\"); Get = Get.replace(ApplicationName, ""); SystemPath = Get; return SystemPath; } function DeleteFile(FileName) { // Delete a local file netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var aFile = Components.classes["@mozilla.org/file/local;1"].createInstance(); if (aFile instanceof Components.interfaces.nsILocalFile) { aFile.initWithPath(FileName); aFile.remove(false); } } function SaveToDisk(filepath, content) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("Permission to save file was denied."); } var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath( filepath ); if ( file.exists() == false ) { file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 ); } var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"] .createInstance( Components.interfaces.nsIFileOutputStream ); outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 ); var output = content; var result = outputStream.write( output, output.length ); outputStream.close(); } function LoadFromDisk(filePath) { if(window.Components) try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); file.initWithPath(filePath); if (!file.exists()) return(null); var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream); inputStream.init(file, 0x01, 00004, null); var sInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream); sInputStream.init(inputStream); return(sInputStream.read(sInputStream.available())); } catch(e) { //alert("Exception while attempting to load\n\n" + e); return(false); } return(null); } I am trying to do a page redirect upon timer completes counting down to 0 from 5 seconds. I used a script from the internet, but so far I cant get to work. I have also in the file some php and html. the php is just to echo out some text and the html is doing the redirect via a meta tag that someone suggested. Code: <html> <head> </head> <body> <?php include_once('config.php'); echo $_SESSION['flash']['notice'].'<br/><br/>'; echo 'you will be automatically redirected in a few seconds.'; ?> <script language="javascript" type="text/javascript"> // var milisec=0 var seconds=5 document.counter.d2.value='5' function display(){ if (milisec<=0){ milisec=9 seconds-=1 } if (seconds==0){ document.write(<meta http-equiv="refresh" content="5;url=page.php">) } display() </script> <form name="counter"> <input type="text" size="8" name="d2"> </form> </body> </html> My firefox web developer is telling it has a javascript error of: unexpected end of xml source. the funny thing is I dont have any xml in it. I appreciate any help in the matter. This is my class doucmnet :: PHP Code: XMLXHttpRequest = function(name){ this._handle = new XMLHttpRequest(); this._method = ''; this._url = ''; this.readyState = 0; this.responseBody = ''; this.responseText = ''; this.responseXML = ''; this.status = 0; this.statusText = ''; this.className = name; this.onreadystatechange = function(){} this.ontimeout = function(){} this.abort = function(){ this._handle.abort(); } this.getAllResponceHeaders = function(){ return this._handle.getAllResponceHaders; } this.getResponceHeader = function(bstrHeader){ return this._handle.getResponceHeader(bstrHeader); } this._readyStateUpdate = function(){ if(typeof(name) !== "undefined"){ name = this.className; } eval(""+name+".onreadystatechange();"); eval(""+name+".readyState = "+name+"._handle.readyState;"); eval(""+name+".status = "+name+"._handle.status;"); eval(""+name+".statusText = "+name+"._handle.statusText;"); eval(""+name+".responseText = "+name+"._handle.responseText;"); eval(""+name+".responseBody = "+name+"._handle.responseBody;"); eval(""+name+".responseXML = "+name+"._handle.responseXML;"); } this.open = function(sMethod, sUrl){ this._readyStateUpdate(); this._handle.onreadystatechange = this._readyStateUpdate; this._handle.ontimeout = this.ontimeout(); this._url = sUrl; this._method = sMethod; } this.send = function(data){ this._handle.open("GET", "xml.php?url="+ this._url + "&method=" + this._method + "&data=" + urlencode(data)); this._handle.send(null); } this.setRequstHeader = function(sName, sValue){ return this._handle.setRequestHeader(sName, sValue); } } What this is supposed to do :: This is a class that is supposed to allow CrossDomain AJAX(XMLXHttpRequest) in the exact same way the XMLHttpRequest dose all the same handlers other then it uses a php file to get all the data now the PHP File works perfectly post and GET - Without cURL. Now most of the class works it can send the data("POST" or "GET") cross domain the only problem seems to be firing the onreadystatechange PHP Code: this.open = function(sMethod, sUrl){ this._readyStateUpdate(); this._handle.onreadystatechange = this._readyStateUpdate; this._handle.ontimeout = this.ontimeout(); this._url = sUrl; this._method = sMethod; } As you can see i have its set to fire the _readyStateUpdate on the onreadystatechange so why is it not fireing, This is tested in FireFox 3.5, ComitBird(Firefox 3.2 Core), Google Chrome and IE and it dose not work in all of them as i know there is a bug with FireFox 3.5 and Firebug wich im a developer i have got it but thats why im testing in GG and IE Any help would be greatly appreciated I have an input text with an onchange event that calls a function in which an alert box displays. I also have a button whose onclick calls a different function. If the user makes a change in the input text and immediately clicks the button, the onchange event fires, displaying the alert box, but the code in the function for the onclick of the button doesn't execute. I've read that this has something to do with event bubbling, but I haven't seen any solutions. Is there a solution? Is it even possible?
hi, i have aded window unload event handler to my code. my page calls some function that takes few secs and page then loads in 5-6 secs. while ths page is loading, if user clicks 'x' on browser window, then code inside unload event handler doesnt get executed. if user waits for page to be loaded fully and hten clicks 'x', then unload event handler gets executed. but i want if during loading user decides to click 'x' button, then also unload handler shold get exucted. i am pasting a sample code that simulates my situation: <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Untitled Page</title> <script type="text/javascript"> function unloadPage() { alert('unloaded page'); } function pauseJS(timeInMilliS) { var date = new Date(); var curDate = null; do { curDate = new Date(); }while(curDate-date < timeInMilliS); } </script> </head> <body onload="pauseJS(6000)" onunload="unloadPage()"> <p>Test Page</p> </body> </html> I am using 2 ajax functions in the program. One for login and one for logout. The login one is showUser which is working correctly by using the form onsubmit method, however the logout button (IN BOLD) onclick method is not working. Pls help. Code: <form onsubmit="showUser(document.getElementById('uid').value,document.getElementById('pass').value);return false;" > <div id="txt"><b>Enter your username </b> <input type="text" name= "username" id="uid"> <br> <b>Enter your password</b> <input type="password" name="pass" id="pass"> <br></div> <div id="txt1" style="display : none">help</div> <input type="submit" value="Login" /> <input type="button" onclick="logout(document.getElementById('uid').value); return false; " name="logout" value="Logout" /> <input type="button" value="Register" class="register"/> </form> I have a Google Maps JScript that does two things - first it figures out the user's geolocation and then provides directions between two points. The problem occurs in that the geolocation takes a second to run, so the second function has initialLocation as an undefined variable. I need this variable to reflect the value used in the earlier geolocation (which works) in the instance 'var start = initialLocation'. Any suggestions? A way to make the second function wait until the first has completed? Code: <script type="text/javascript"> var initialLocation; var siberia = new google.maps.LatLng(60, 105); var newyork = new google.maps.LatLng(32.77, -79.92); var browserSupportFlag = new Boolean(); var map; var infowindow = new google.maps.InfoWindow(); function handleNoGeolocation(errorFlag) { if (errorFlag == true) { initialLocation = newyork; contentString = "Error: The Geolocation service failed."; } else { initialLocation = siberia; contentString = "Error: Your browser doesn't support geolocation. Are you in Siberia?"; } map.setCenter(initialLocation); infowindow.setContent(contentString); infowindow.setPosition(initialLocation); infowindow.open(map); } var directionDisplay; var directionsService = new google.maps.DirectionsService(); var map; function initialize() { // Try W3C Geolocation method (Preferred) if(navigator.geolocation) { browserSupportFlag = true; navigator.geolocation.getCurrentPosition(function(position) { initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); contentString = "You are here! (w3c)"; map.setCenter(initialLocation); infowindow.setContent(contentString); infowindow.setPosition(initialLocation); infowindow.open(map); }, function() { handleNoGeolocation(browserSupportFlag); }); } else if (google.gears) { // Try Google Gears Geolocation browserSupportFlag = true; var geo = google.gears.factory.create('beta.geolocation'); geo.getCurrentPosition(function(position) { initialLocation = new google.maps.LatLng(position.latitude,position.longitude); contentString = "You are here! (gears)"; map.setCenter(initialLocation); infowindow.setContent(contentString); infowindow.setPosition(initialLocation); infowindow.open(map); }, function() { handleNoGeolocation(browserSupportFlag); }); } else { // Browser doesn't support Geolocation browserSupportFlag = false; handleNoGeolocation(browserSupportFlag); } directionsDisplay = new google.maps.DirectionsRenderer(); var myOptions = { zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); directionsDisplay.setMap(map); alert(initialLocation); var start = initialLocation; var end = '<?php echo $address;?>'; var request = { origin:start, destination:end, travelMode: google.maps.DirectionsTravelMode.DRIVING }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } }); } </script> On my site we have image galleries that pop up over top of the page in a higher z-index and position:fixed, and another div between the gallery and background with opacity set to about 85%. The image gallery div has a close button, and I was asked to make the gallery also close by pressing ESC, so I added this: igevt=function(evt){checkclosegal(evt)} window.addEventListener('keypress',igevt, false) and checkclosegal: function checkclosegal(evt) { if(evt.keyCode==27) { closebgeagal() window.removeEventListener('keypress',igevt, false) } } This works perfectly in Firefox and Opera, but Chrome and Safari don't fire the event (not worried about ie right now - I know it uses attachEvent). Could it have something to do with the gallery being in a higher z-index? Please help, thanks! Hi All, I have a script that is called by the onchange event on my text field (it compares the date entered into the field and issues an alert if the date is earlier than the current date). This worked great on my data entry form but I also want to use the same script in my update form. In the update form the text field is already receiving a value via php: Code: <input name="DateNeeded" type="text" class="formField" id="DateNeeded" onchange="checkDate(this)" value="<?php echo $row_rstRequestDetails['DateNeeded']; ?>" /> and this is causing my onchange event to fire when the page is loaded. Is there a way to suppress the onchange event for the initial page load? Thanks, Ken So I am adding a little simple clean up function when users paste into an iframe with design mode on. I have no problems with firing this function with Firefox Code: getElementById('add_article').contentWindow.document.addEventListener('paste', iFrameClean, true); but for the life of me I cant get it to fire in Ie I have tried attachEvent in IE only Code: getElementById('add_article').attachEvent('onpaste', iFrameClean); //iframe onpaste add an onpaste to the body of the iframe Code: onpaste="setTimeout(function(){iFrameClean();},100);" even the onPaste in the iframes body doesnt fire in IE!!! I have had a good look around but no one seems to have an answer on this. Also please note I have successfully attached the onblur and onfocus events to this iframe in IE and firefox It would be really handy as people are copying html into the iframes. I have a html cleaner firing when they submit but I want the text to be cleaned when/if they paste in. |