JavaScript - Onclick Not Firing After Onchange
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?
Similar TutorialsHi 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 Hello, I'm working on a quote generator and I'm running into an issue with onChange events not firing when a text field is dynamically populated via a child window. Here's my setup: I have 3 text boxes (quantity, price, markup) that are multiplied together in order to give the total of that product. Each text box has an onChange event [called calculator()] that calls an external javascript file, which handles the multiplication and instantly updates the total of that product. Up to this point, everything works fine - - when I manually edit any of the 3 inputs, the total updates correctly. However, my problem is that I now have the "price" text box being dynamically populated, and when it updates it is not firing the onChange event attached to it. The text box is being filled by way of launching a child window and running the following code within it: Code: function call_submit() { opener.document.quote_form.item_price_1.value=document.child.prods.options[document.child.prods.selectedIndex].id self.close(); } I've also tried to call the calculator function from within the child window, with no luck: Code: function call_submit() { opener.document.estimator_form.item_price_1.value=document.child.prods.options[document.child.prods.selectedIndex].id calculator () self.close(); } So, as of right now, the following is happening - - I launch the child window, I select the product to add to the quote, the child window closes and the price is correctly populates within the "price" text box, BUT the total stays at zero. If I manually edit any of the fields, it then catches back up and properly updates the total. Is their any way to fire the onChange event at the time when the text field is populated from the child window? Any help would be appreciated. Thanks in advance. 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> Hi, I have what I assume started as a simple error and then trying to fix it I think I have made things so complicated I've become confused. I have two fields, a drop down list and a text field, when someone clicks on a value in a drop down list (I will show the results eventually but at the moment) I just want the result to echo in my getCategory.php and the same for the text field. Both php pages are currently being called. And at the moment contain $_REQUEST['category'] and $_REQUEST['ProductName'] respectively. Nothing is being echoed. I know the below code is wrong, but the more I try to correct it the worse it gets so I thought I would just leave it as is before I made it worse. Code: <script type="text/javascript"> function loadXMLDoc1(File,ID,Msg){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { try{ xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; } } var params=Msg; xmlhttp.open("POST",File,true); xmlhttp.setRequestHeader("Pragma", "Cache-Control:no-cache"); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.setRequestHeader("Content-length", params.length); xmlhttp.setRequestHeader("Connection", "close"); xmlhttp.send(params); } </script> </head> <body> <label>Search by Category: </label> <select name="category" id="category" onchange='loadXMLDoc1("getCategory.php","txtHint","category")' class="input"> <option value="please select" selected"selected">Please Select</option> <option value="Clothes" name="Clothes" id="Clothes">Clothes</option> <option value="Bags" name="Bags" id="Bags">Bags</option> <option value="Hats" name="Hats" id="Hats">Hats</option> </select> <br /> <br /> <label>Search by name: </label> <input type="text" class="input" name="ProductName" id="ProductName" value="Search" size="30"/> <input type="button" value="Search" onclick="loadXMLDoc1('getProductName.php','txtHint', ProductName='(this.value)')" /> <br /> <br /> <div id="txtHint"></div> 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. 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. 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); } 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 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 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> 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? 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. 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! ok so here is the problem in more detail i have a dropdown menu wrapped in a div attached to this div is the onmouseout event which hides the div this is working the problem however is when moving from 1 link to the next in the dropdown the onmouseout event of the wrapper div is firing and hiding the div prematurely see it live relevant code: Code: <div id="roster_drop" class="drop_menu" style="left: 128px;" onmouseout="this.style.display = 'none';"> <a href="roster.php">Superstars</a> <a href="champions.php">Champions</a> <a href="titlehistory.php">Title History</a> </div> how do i make the event only trigger when your mouse leaves the div itself and not crossing onto a link I'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 I'm currently working on a project and I am doing a bunch of image switching. I'm having a problem with the following... I have seven medium image objects and one small one. One is at the top and the other 7 are below. When one of the 7 is clicked, it then becomes the one up top and the one up top then takes the place of the image clicked. This needs to be able to happen no matter which of the seven i click. Also when you click one of the seven it runs a script to change 9 other images in the center of the page. this isnt too important because i have it working already. What i have is, each of the seven images run their function that changes the 9 center images and then it runs another function. What i need is for that function to determine which company for example(shaws, lowes, target) the top image belongs to and replace the image that was clicked with the top one. But i also need to replace the NAME="" and ONCLICK="function()" with the proper ones for the original company up top. Please if you can understand what im trying to do let me know, if you need further clarification i can do so. i can draw a picture of what im trying to do or the layout if needed but i cant necessarily show anyone the project due to a non-disclosure. I have a onChange value
Code: var people = [ ["Timothy Conner", "1999-Present", "Age: 12", "Male", ""], ["Andrew Conner", "1992-Present", "Age: 19", "Male", ""] ]; var how = "Brothers"; function find() { if(document.getElementById("name").value == people [0] [0]) { document.getElementById("desc").value = people [0] [1] + " " + people [0] [2] + " " + people [0] [3]; } if(document.getElementById("name").value == people [1] [0]) { document.getElementById("desc").value = people [1] [1] + " " + people [1] [2] + " " + people [1] [3]; } document.getElementById("relateb").value = document.getElementById("name").value; } Code: Name: <input type="text" id="name" value="" onChange="find()"/> So for it to proses a name you must click out of a box is ther a way to make it instead of when you click out of it, it would immidiatly change? Code: <input type = "text" style ='display:none;' onchange="display_data_from_server(this.value)"/> Value inside that input is cahanged from js. Is there any reason that onchange would not happen ? i mean, it does not. Hi folks. I'm working on a calculator and need to use the 'onchange' function. Basically, the user selects the year (id=taxYear) and once the year is select (default is 2008) this year will appear in 2 different lines of the page under 2 seperate ID's(ageYear & totalYear). I've looked at a few example of the function but I'm still not sure how to approach it. At the moment the year changes once I hit the 'calculate' button but the onChange would obviously offer a better alternative with the date changing once 'taxYear' is changed. here is the script; Code: //check the year var taxYear = document.getElementById('taxYear').options[document.getElementById('taxYear').selectedIndex].value; document.getElementById('ageYear').innerHTML = taxYear; document.getElementById('totalYear').innerHTML = taxYear; Here is the jsp; Code: <tr> <td align="left" width="203" colspan=""><p> Your Tax Year: </p></td> <td align="left" > <s:select name="taxYear" id="taxYear" list="#{'2008':'2008', '2009':'2009'}" theme="simple" />* </td> </tr> <tr> <td align="left" width="203"><p> Age at December 31st <span id="ageYear"></span></p></td> <td align="left" colspan="1"> <s:textfield name="age" id="age" theme="simple" cssClass="text" value="30" /> * <div id="errorage" class="warningmessage" style="display:none"> Please enter your Age to proceed. </div> </td> </tr> <tr> <td colspan="2" class="basicboldtext"> <br/> The total pension contribution you can make for year <span id="totalYear"></span> is €<span id="totalTax2"></span> <br/> </td> </tr> Appreciate any help on this! Is it possible disable an onclick after clicking it and then enable it from another onclick by id Code: <img id="one" href="images/homepage/sliders/bonus_button.jpg" style="position:relative; top:30px; left:50px; height:30px; width:70px; float:left;"> This code runs when it is clicked: Code: $("#one").click(function() { runEffectB(); return false; }); What I would like to happen is for either runEffectB() to not run if it was just run or to disable the #one.click once it has run. I am assuming I will be able to re-enable it from another onclick running a similar function. This is jquery and jquery ui if that helps. Any ideas much appreciated. |