JavaScript - Js Error Firefox Using Localstorage
Howdy
So i am working on a piece that using local storage and saves them to an un ordered list. I have been using Chrome for the console and inspector abilities and it has been going well. I've tested it before in Safari and Opera and I know it works. However, in Firefox (and IE but I don't care about that) I am getting a console error. Here is the code being executed: Code: var i=0; while (localStorage.key(i) != null) { var values = localStorage.getItem(localStorage.key(i)); values = values.split(";"); $("#logscreen").append("<li class='arrow logname'><a href='#' class='direct' onclick='...'>" + values[0] + "</a></li>"); i++; } There is some jQuery thrown in there but basically it says, test for a localStorage key of i, if it is not null create the list item, add one to i and repeat. I am getting the following error in firefox only: Index or size is negative or greater than the allowed amount" code: "1 [Break on this error] while (localStorage.key(i) != null) Any ideas folks? Similar TutorialsHello all, I need some help here. I'm new to HTML 5 and I'm not sure how to convert my cookie script over to HTML 5 LocalStorage. If anyone could help, I would appreciate it greatly. Here's my cookie script: Code: var currentRotation=null; function checkOrientAndLocation(){ if(currentRotation != window.orientation){ setOrientation(); } } function setOrientation(){ switch(window.orientation){ case 0: orient = 'portrait'; break; case 90: orient = 'landscape'; break; case -90: orient = 'landscape'; break; } currentRotation = window.orientation; document.body.setAttribute("orient",orient); setTimeout(scrollTo,0,0,1); } $(window).unload(function() { // On page unload $('.remember').each(function() { // Save each value to expire in a year $.cookie(this.id, this.value, {expires: 365}); }); $('.draggable').each(function() { // Save draggable positions var draggable = $(this); $.cookie(this.id, draggable.css('top') + '_' + draggable.css('left'), {expires: 365}); $.cookie('disp' + this.id, draggable.css('display'), {expires: 365}); }); }); $(function() { var val, pos, disp; setInterval(checkOrientAndLocation,1000); $('.remember').each(function() { var val = $.cookie(this.id); // Retrieve value for this element if (val) { this.value = val; } } ); $('.draggable').each(function() { var pos = $.cookie(this.id); // Retrieve values for this element if (pos) { pos = pos.split('_'); $(this).css({position: 'absolute', top: pos[0], left: pos[1]}); } var disp = $.cookie('disp' + this.id); if (disp) { this.style.display = disp; } } ).touch({animate: false, sticky: false, dragx: true, dragy: true, rotate: false, resort: false, scale: false }); }); Hello, I apologize if this is not in the right forum as part of my question may not be reated to javascript but I have the following problem(s). I am attempting to make a website that has three pages: index.html customize.html home.html The index page needs to have an onLoad script that does several things: 1. Checks whether the browser supports localStorage and branches to either LSYes() or LSNo() accordingly 2. LSYes has to check whether a value of NY=True or NY=False has been set in local storage. If neither has been set it redirects to customize.html, otherwise it redirects to home.html. 3. LSNo has to perform a similar check and redirect as LSYes by checking for a cookie containing the appropriate value. The customize page has to have an onLoad script that detects whether localStorage is supported and somehow be able to pass that value to another script that is called later on from a form on the page. It also has to have another script that is called from rhe form that can handle any/all of the following conditions: 1. Checking a zipcode entered in the form against a list of NY zipcodes to determine whether the person lives in NY. 2. Save the value of NY=True if it finds a match or NY=False if it doesn't in either localStorage or a cookie based on the results of the onLoad script. 3. Allow the user to clear any values that may be saved and save new values if the user moves in or out of NY. The home page needs to likewise detect whether localStorage is supported. If localStorage is not detected it has to: 1. Check for either NY=True or NY=False in the cookie 2. Change the expiration date on the cookie to one year from the current date even if the cookie has not expired. 3. Completely hide certain sections of the page if it detects a value of NY=false or if a person navigates to the page without NY value being set but show them if NY is set to true. If localStorage is detected it has to perform similar functions using localStorage. In each case, if the browser supports localStorage that is to be used instead of a cookie. There are several things this site needs to do that are beyond my current skill levels. 1. localStorage detection 2. Comparing a zipcode entered on the form to a list of NY zipcodes without making the script huge and slowing down page loading. 3. Automatically changing from index to either home or customize based on whether localStorage has been set for the site. 4. Hiding or showing sections of a page based on a value in localStorage. I have an idea how to do some of this with a cookie but when I try it it acts like no cookie is present even though I know it is so I am not sure what I am doing wrong there. I have been trying to teach myself by putting parts of various scripts that each perform part of what I need together but this approach isn't working right. Thanks for your help Anello I am working on a Phonegap app that sends emails that consist of form data that is filled out within the app. I need my app to send the emails which I have sorted out. The second part of the app needs to store the email subject of all the mails that are sent in local storage and then in a separate function needs to output all the saved data and send it. I will post my full code below and comment the important bits. Code: function sendMail(imageURI, click){ var d = new Date(); var dat = d.getDate(); var mon = d.getMonth(); var year = d.getFullYear(); var hours = d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); var todayDate = dat+'-'+mon+'-'+year+' | '+hours+':'+minutes+':'+seconds; var agent = $('#agent').val(); var depot = $('#selection').val(); var date = $('#free').val(); var newURI = imageURI.replace("file:///storage/emulated/0/DCIM/Camera/",""); /* -----> the variable that needs to be stored */ var newFileName = 'N' + result + '_' + agent + '_' + todayDate + '_' + newURI + '_' + depot + '_' + date; /* -----> storing the variable */ var temp = localStorage.getItem('newFileName'); var somearray=temp.split(','); somearray_length=somearray.length; somearray[somearray_length]=newFileName; var somestring=somearray.join(','); localStorage.setItem('newFileName',somestring); /* <----- storing the variable */ var largeImage = document.getElementById('largeImage'); largeImage.style.display = 'block'; largeImage.src = imageURI; cordova.plugins.email.addAlias('gmail', 'com.google.android.gm'); cordova.plugins.email.open({ app: 'gmail', to: 'blah@gmail.com', subject: newFileName, body: '<ul><li style="font-weight:bold;text-decoration: underline;"><b><u>File: </b></u></li><li>'+newURI+'</li><br><li style="font-weight:bold;text-decoration: underline;"><b><u>Agent Name: </b></u></li><li>'+agent+'</li><br><li style="font-weight:bold;text-decoration: underline;"><b><u>Next Scheduled Date: </b></u></li><li>'+date+'</li><br><li style="font-weight:bold;text-decoration: underline;"><b><u>Scanned: </b></u></li><li>'+todayDate+'</li><br><li style="text-decoration: underline;font-weight:bold;"><b><u>Depot: </b></u></li><li>'+depot+'</li></ul>', attachments: [imageURI], isHtml: true }); }; /* -----> The second function */ function endOfDay(data){ var d = new Date(); var dat = d.getDate(); var mon = d.getMonth(); var year = d.getFullYear(); var hours = d.getHours(); var minutes = d.getMinutes(); var seconds = d.getSeconds(); var todayDate = dat+'-'+mon+'-'+year+' | '+hours+':'+minutes+':'+seconds; ending=localStorage.getItem('newFileName'); var salesman = $('#agent').val(); var newsFileName = 'End of Day Report for Agent: ' + salesman + '|' + todayDate; cordova.plugins.email.addAlias('gmail', 'com.google.android.gm'); cordova.plugins.email.open({ app: 'gmail', to: 'seth.v.staden@gmail.com', subject: newsFileName, body: 'end of day report: <br>' + ending, isHtml: true }); localStorage.setItem('newFileName',''); }; my problem is that instead of outputting all the sent subjects that have been stored like so: "subject 1, subject 2, subject 3, etc..." it is outputting it as the latest mail that was sent, i.e. "subject 3, subject 3". I have no clue why this is going wrong or how to fix it... any help would be greatly appreciated. Reply With Quote 01-15-2015, 11:13 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts Instead of doing all this tortu Code: var temp = localStorage.getItem('newFileName'); var somearray=temp.split(','); somearray_length=somearray.length; somearray[somearray_length]=newFileName; var somestring=somearray.join(','); localStorage.setItem('newFileName',somestring); Why not simply do Code: localStorage.setItem('newFileName', localStorage.getItem('newFileName') + "," + newFilename ); Though I admit I don't see why your code won't work. It just causes a bunch of unneeded overhead. ********** COMMENTARY: I think your dates will be unreadable by humans. var mon = d.getMonth(); That will get a ZERO for January, 1 for February, etc. For human readable, you should do var mon = d.getMonth() + 1; Hi all, I've been experimenting with Local Storage. I can do things like this just fine: localStorage.setItem('variable_name', variable_value); // write a value var variable_value = localStorage.getItem('variable_name'); // read a value localStorage.removeItem('variable_name'); // delete a value But if I do this: var object = { width : w, height : h }; ...then place it in local storage, reading it back gives me a TEXT STRING that says "[Object object]" and not the actual object. I would like to be able to store multiple values in one object, but it doesn't seem to work. I also tried to store a variable obtained with "document.getElementById" and when read back it just says [HTMLDivElement] (something like that) instead of the actual element. Am I doing something wrong, or does local storage not support objects? (btw, tested on FF 3.6). Thanks! -- Roger I'm trying my hand at localstorage (which is HTML5), but I'm combining it with javascript (which is... erm, well, javascript ) so I decided to put this in the javascript forum. If I'm wrong, I apologize. Anyway, though I'm not a complete newbie when it comes to coding, this is new for me and frankly, I'm stuck. What I'm trying to do (nothing special, just messing around a bit) is show the current time and the time the visitor last visited. I made this: Code: var tijd = new Date(); var oudetijd = tijd.getTime(); localStorage.setItem('laatste bezoek', oudetijd); var laatstebezoek = localStorage.getItem('laatste bezoek'); document.write(laatstebezoek + "<br>"); document.write(oudetijd); Should work, right? Well, it does... partly. It shows the current time (woohoo!!! ) but the "old time" (oudetijd) is exactely the same! Now, I know I'm doing something wrong here, most likely something stupid like a missing comma, but whatever it is, I don't see it. Can someone shed some light on this? P.S. As you can probably see from the code, I'm Dutch. I dont know if it helps or not, but here's a translation: tijd= time oude tijd = old time laatste bezoek = last visit Thanks in advance! So. When I save a boolean to localStorage It converts it to string. PHP Code: localStorage["fixedBackground"] = document.getElementById("fBackground").checked; And that saves a 'true' or 'false' string. So to convert it to a boolean value, in the 'restore options' I use the function 'toBool' PHP Code: function toBool(str) { if ("false" === str) return false; else return str; } PHP Code: var value = localStorage["fixedBackground"]; if (null != value) document.getElementById("fBackground").checked = toBool(value); And that works just fine. However, I want to recall this saved data in a javascript. I want an PHP Code: if (value = true){ document.getElementsByTagName('body')[0].style.backgroundAttachment="fixed"; } But I can't get a 'toBool' type of function into that statement This is my method of retrieving the data: PHP Code: var port = chrome.extension.connect({name: "knockknock"}); port.postMessage({get: "fixedBackground"}); port.onMessage.addListener(function(msg) { //Set bgimage attachment javascript:value=msg.value; which makes the full if statement: PHP Code: var port = chrome.extension.connect({name: "knockknock"}); port.postMessage({get: "fixedBackground"}); port.onMessage.addListener(function(msg) { //Set bgimage attachment javascript:value=msg.value; if(value = true) { document.getElementsByTagName('body')[0].style.backgroundAttachment="fixed"; } }); any ideas? Hey there. I've recently written a small javascript library that creates a unified interface for localStorage and sessionStorage. The code is here http://github.com/AndrewLowther/StorageItem I'm looking for people to give me feedback and to help me work on it should you so wish. Feedback is most welcome! I'm having some issues with firefox, chrome seems to work ok. Firebug is giving me an error stating country is not defined. The line it's saying it's on is where the function for an ajax call to populate a select input on page load. Here's the script that sets up the functions to call and fill the state and city values: Code: <script src="/components/com_helloworld/js/request.js"> /**************************************************** * Ajax call to fill city values ****************************************************/ </script> <script> function handleOnChange(dd1) { var idx = dd1.selectedIndex; var val = dd1[idx].text; var par = document.forms["cbcheckedadminForm", "adminForm"]; var parelmts = par.elements; var cb_statesel = parelmts["cb_state"]; var country = val; var directory = ""+document.location; directory = directory.substr(0, directory.lastIndexOf('/')); Http.get({ url: "./components/com_helloworld/js/regvalues/states/" + country + ".php", callback: fillcb_state, cache: Http.Cache.Get }, [cb_statesel]); } function fillcb_state(xmlreply, cb_stateelmt) { if (xmlreply.status == Http.Status.OK) { var cb_stateresponse = xmlreply.responseText; var cb_statear = cb_stateresponse.split("|"); cb_stateelmt.length = 1; cb_stateelmt.length = cb_statear.length; for (o=1; o < cb_statear.length; o++) { cb_stateelmt[o].text = cb_statear[o]; } } else { alert("Cannot handle the Ajax call."); } } function handleOnChange2(dd1) { var idx = dd1.selectedIndex; var val = dd1[idx].text; var par = document.forms["cbcheckedadminForm", "adminForm"]; var parelmts = par.elements; var cb_citysel = parelmts["cb_city"]; var state = val; var directory = ""+document.location; directory = directory.substr(0, directory.lastIndexOf('/')); Http.get({ url: "./components/com_helloworld/js/regvalues/" + state + ".php", callback: fillcb_city, cache: Http.Cache.Get }, [cb_citysel]); } function fillcb_city(xmlreply, cb_cityelmt) { if (xmlreply.status == Http.Status.OK) { var cb_cityresponse = xmlreply.responseText; var cb_cityar = cb_cityresponse.split("|"); cb_cityelmt.length = 1; cb_cityelmt.length = cb_cityar.length; for (o=1; o < cb_cityar.length; o++) { cb_cityelmt[o].text = cb_cityar[o]; } } else { alert("Cannot handle the Ajax call."); } } </script> And here's how it's being triggered on page load: Code: <script> function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } addLoadEvent(function() { ajaxFunction(document.getElementById('country').value); handleOnChange(country); setupDependencies('cbcheckedadminForm', ''); handleOnChange2(cb_state); }); </script> I'm not sure why it says it's not defined as it clearly is. This error is causing the dependent drop down script to not work in firefox causing the child dropdowns to not hide. I did notice something odd though, if I remove the doctype line it works ok. I did this as firebug was throwing an error on another page claiming it had a syntax error so obviously something somewhere is messed up. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>"> When the doctype lines are removed firebug throws this error: window.document.forms[arguments[i]] is undefined [Break On This Error] for(var j = 0, e = window.document...ts[i]].elements; j < e.length; ++j) { in formmanager.js. Hi Coders, I have a javascript function which lets a user to choose one of the 7 option buttons on a "mainsub.asp" page and the page will then be forwarded to one of the 7 process pages depending on what has been chosen. The problem is that firefox is angry with the first line ("if" statement) and tells the following in its error console: Error: document.forms[0].C1 is not a function Source File: [localhost...] Line: 117 Here is the code: function fSubmit(){ if (document.forms[0].C1(0).checked) document.forms[0].action="process.asp"; else if (document.forms[0].C1(1).checked) document.forms[0].action="process1.asp"; else if (document.forms[0].C1(2).checked) document.forms[0].action="process2.asp"; else if (document.forms[0].C1(3).checked) document.forms[0].action="process3.asp"; else if (document.forms[0].C1(4).checked) document.forms[0].action="process4.asp"; else if (document.forms[0].C1(5).checked) document.forms[0].action="process5.asp"; else if (document.forms[0].C1(6).checked) document.forms[0].action="process6.asp"; else document.forms[0].action="process.asp"; return; } Internet explorer does not complain about anything and does its job great. But I could not figure out how to change the code to be also compliant with Firefox? Thanks for all the comments. Please help, I'm getting this error, Object expected, Code: 0 in Internet Explorer (not in Firefox, though). Here is the link to the page: http://www.uatparts.com/miva/merchan...Category_Code= I'm worried that my customers might shy away and not buy from me when they see this error. What do I need to do in order to stop this error from appearing? Note: I tried including the code in this thread but it was too long, the forum wouldn't let me. FireFox is throwing a DOM security error. And i don't really know why. i've used toDataURL() before, and it's never done this. Hopefully i can get this little app fixed, so that i can use it on my TabletPC for taking notes in class. The line of code that is throwing this error is: Code: var Note = document.getElementById("SketchPage").toDataURL(); here's the full error from the Error Console: Error: uncaught exception: [Exception... "Security error" code: "1000" nsresult: "0x805303e8 (NS_ERROR_DOM_SECURITY_ERR)" location: "file:///C:/SketchBook-Dev/SketchBook.js Line: 236"] here is the JS file: Code: var PenSize = "3"; var PenShape = "Circle"; 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 UIstatus = "visible"; var Server = "localhost"; var NxtNote = new Image(); document.onkeyup = ToggleUI; function Init() { // Get the System Path GetSystemPath("SketchBook.html"); // Load All Filenames of the DataPath directory into an array GetFileList(SystemPath + DataPath, FileList); //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 image data onto the canvas var canvas = document.getElementById('SketchPage').getContext('2d'); canvas.drawImage(NxtNote , 0, 0); } } function HideOptions() { document.getElementById("Options").style.visibility = "hidden"; } function ToggleUI(e) { var KeyID = (window.event) ? event.keyCode : e.keyCode; var KeyValue = 18; // Use a key to hide the toolbars so that most of the screen is used for the UI if(KeyID == KeyValue) { if(UIstatus == "visible") { UIstatus = "hidden"; document.getElementById("UI").style.visibility = "hidden"; return; } if(UIstatus == "hidden") { UIstatus = "visible"; document.getElementById("UI").style.visibility = "visible"; } } } function ShowOptions() { document.getElementById("Options").style.visibility = "visible"; } function UpdatePenSize() { PenSize = document.getElementById('GetPenSize').value; } function UpdatePenShape() { PenShape = document.getElementById('GetPenShape').value; } function UpdatePenColor() { PenColor = document.getElementById('GetPenColor').value; } 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() { // 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); } function NextNote(Direction) { if(Direction == "up") { // Display the previoius note CurrentNote--; // Make sure you don't incrimnet to a non-existant note if(CurrentNote <= 0) { 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); return; } if(Direction == "down") { //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); return; } } function DeleteNote() { // Delete The current note DeleteFile(SystemPath + DataPath + FileList[CurrentNote]); // Reload the Directory List // Clear the FileList Array FileList = []; GetFileList(SystemPath + DataPath, FileList); // Load The Previous Note // Display the previoius note CurrentNote--; // Make sure you don't incrimnet to a non-existant note if(CurrentNote <= 0) { CurrentNote = FileList.length; } 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); return; } 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 CurrentNote++; // Add the new Note File name to the end of the FileList Array FileList.push(CurrentNote + ImageExtension); // 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; var Note = document.getElementById("SketchPage").toDataURL(); } 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") { return; } } // ******************** 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 GetFileList(Directory, FileList) { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var _nsILocalFile = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); // initialize path to work with _nsILocalFile.initWithPath(Directory); // get file interface implemenation // this means that an XPCOM Class can implement multiple interface var lv_oFile = _nsILocalFile.QueryInterface(Components.interfaces.nsIFile); var lv_oEntries = lv_oFile.directoryEntries; while(lv_oEntries.hasMoreElements()) { var lv_cFile = lv_oEntries.getNext() .QueryInterface(Components.interfaces.nsIFile).path; FileList.push(lv_cFile); } } 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); } and the HTML UI code: Code: <html><head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <title>Sketch Book v1.0</title> <script src="SketchBook.js" type="text/javascript"></script> <script src="JSxpcom.js" language="text/javascript"></script> </head> <body onLoad="Init();"> <div id="SketchPageView"> <canvas id="SketchPage" width="480" height="640" style="background: #C7C1A3; position: absolute; top: 0px; left: 0px;" onmousedown="Draw(this, event);"></canvas> </div> <div id="Options" style="position: absolute; visibility: hidden; top: 100px; left: 50px;"> <table cellwidth="100" border="0" cellpadding="0" cellspacing="0" height="50"> <tbody><tr><td><img src="./Image/TL-black.PNG" height="19" width="19"></td><td bgcolor="#bce0f8"><center><b>Options</b></center><img src="./Image/delete.png" style="position:absolute; top: 2px; left: 150px; height: 18; width: 18;" onClick="HideOptions();"></td><td><img src="./Image/TR-black.PNG" height="19" width="19"></td></tr> <tr><td bgcolor="#bce0f8"></td> <td bgcolor="#bce0f8"> <div style="border: 1px solid black;"> <table> <tbody><tr> <td><center>Pen Size</center></td><td><center>Color</center></td> </tr> <tr> <td> <select id="GetPenSize" onchange="UpdatePenSize();"> <option value="1">1 px</option> <option value="2">2 px</option> <option value="3">3 px</option> <option value="4">4 px</option> <option value="5">5 px</option> </select> </td> <td> <select id="GetPenColor" onchange="UpdatePenColor();"> <option value="Black">Black</option> <option value="White">White</option> <option value="Red">Red</option> <option value="Blue">Blue</option> <option value="Green">Green</option> <option value="Brown">Brown</option> </select> </td> </tr> <tr> <td><input value="Restore" onclick="RestoreData();" type="button"></td><td><input value="Backup" onclick="BackupData();" type="button"></td> </tr> <tr> <td><input value="Encrypt" onclick="EncryptData();" type="button"></td><td><input value="DeCrypt" onclick="DecryptData();" type="button"></td> </tr> </tbody></table> </div> </td> <td bgcolor="#bce0f8"></td></tr> <tr><td><img src="./Image/BL-black.PNG" height="19" width="19"></td> <td bgcolor="#bce0f8"></td><td align="right"><img src="./Image/BR-black.PNG" height="19" width="19"></td></tr> </tbody></table> </div> <table id="UI" style="position: absolute; top: 0px; left: 412px; visibility: visible;" border="0" cellpadding="0" cellspacing="0" width="40"> <tbody><tr><td><img src="./Image/TL-black.PNG" height="19" width="19"></td><td bgcolor="#bce0f8"></td><td><img src="./Image/TR-black.PNG" height="19" width="19"></td></tr> <tr><td bgcolor="#bce0f8"></td> <td bgcolor="#bce0f8" height="600"> <img src="./Image/up.png" style="width: 30px; height: 30px;" alt="up" onclick="NextNote('up');"><br><br><br><br> <img src="./Image/plus.png" style="width: 30px; height: 30px;" alt="add" onclick="AddNote();"><br><br><br><br> <img src="./Image/save.png" style="width: 30px; height: 30px;" alt="save" onclick="SaveNote();"><br><br><br><br> <img src="./Image/clear.png" style="width: 30px; height: 30px;" alt="clear" onclick="ClearSketch();"><br><br><br><br> <img src="./Image/delete.png" style="width: 30px; height: 30px;" alt="delete" onclick="DeleteNote();"><br><br><br><br> <img src="./Image/gear.png" style="width: 30px; height: 30px;" alt="options" onclick="ShowOptions();"><br><br> <img src="./Image/down.png" style="width: 30px; height: 30px;" alt="down" onclick="NextNote('down');"> </td> <td bgcolor="#bce0f8"></td> </tr> <tr><td><img src="./Image/BL-black.PNG" height="19" width="19"></td> <td bgcolor="#bce0f8"></td> <td align="right"><img src="./Image/BR-black.PNG" height="19" width="19"></td></tr> </tbody></table> </body></html> Hi, I've written a small script for a website, and strangely enough (or maybe not) it works in Firefox and Chrome but not IE. I'd read about block level inside inline causing this but i'm still not entirely sure. Here is the offending script: Code: function changeImage(image) { if (image == 6) { var vid = document.createElement('object'); vid.width = "700"; vid.height = "370"; vid.id = "photo"; vid.innerHTML = '<param name="movie" value="http://www.youtube-nocookie.com/v/g4cpDgGlFng&hl=en_US&fs=1&rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/g4cpDgGlFng&hl=en_US&fs=1&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="700" height="370"></embed>'; document.getElementById("body").replaceChild(vid, document.getElementById("photo")); } else { var img = document.createElement('img'); var old = document.getElementById("photo") img.width = "700"; img.height = "370"; img.id = "photo"; img.alt = "Photo of Gippsland Lakehous"; img.src = "images/photos/" + image + ".jpg"; document.getElementById("body").replaceChild(img, old); } The offending line is the long innerHTML one. I'm sure this must be a very hacky way of doing things (incidentally the thing is replacing an image with another image or video depending on what is clicked), but I rarely code at all, so don't know any better Thanks! I have the following piece of script to write a line in HTML which is variable; the variable 'bunting' is the path and filename (which varies depending on site where page resides): <CODE> <script language="JavaScript" type="text/javascript"> <!-- document.write('<div id="ic1" style="background-image:url(' + bunting + ');">'); //--> </script> </CODE> This works in most browsers, but in Firefox 3.0.4, it fails to render, and instead generates a piece of literal text: ');//--> on the page. I've read, and re-read the script, and believe it to be correct (with the single quote marks being the javascript delimiters and the double quotes being the html delimiters. I've also tried various combinations of creating piecemeal variables and then creating a final variable by concatenating the pieces. Any help would be greatly appreciated. (just started JS 2 weeks ago) -- this is also my first time posting here, if my post isnt following the proper template let me know and Ill fix it .. Thanks so much for taking the time to check this out in advance Im trying to make the first ul tag in the each slideMenus[] array index values have a position of left = 0px I keep recieving this error however ____________________________________________________ Error: slideMenus[i].getElementsByTagName("ul").style is undefined Line: 63 ------------------------------------------------------------------ the script in question is in [code]. Could someone tell me if I am just making a syntax error if not ill try redoing the whole thing. window.onload = makeMenus var currentSlide = null var timeID = null leftPos = 0 function makeMenus(){ var slideMenus = new Array() var allElems = document.getElementsByTagName("*") var slideListArr = new Array() for(var i=0 ; i < allElems.length ; i++){ if(allElems[i].className = "slideMenu") slideMenus.push(allElems[i]) } for(var i=0 ; i < slideMenus.length ; i++){ slideMenus[i].onclick = showSlide; Code: slideMenus[i].getElementsByTagName("ul")[0].style.left = "0px"; } document.getElementById("head").onClick = closeSlide document.getElementById("main").onClick = closeSlide } function showSlide(){ var slideList = this.getElementsByTagName("ul")[0] // mess with this if((currentSlide != null) && (currentSlide.id == slideList.id)) {closeSlide()} else{ closeSlide(); var currentSlide = slideList; currentSlide.style.display = "block"; timeID = setInterval('moveSlide()', 1); } } function closeSlide(){ if(currentSlide){ clearInterval(timeID); currentSlide.style.left = "0px" currentSlide.style.display = "none"; var currentSlide = null } } function moveSlide(){ var leftPos = leftPos + 5; if(leftPos <= 220) {currentSlide.style.left = leftPos + "px"} else{ clearInterval(timeID); var leftPos = 0} } Strange problem here... I'm implementing google's JS tracking code verbatim which determines whether or not the current site is using HTTP or HTTPS. It builds a dynamic URL used as the "SRC" parameter in the SCRIPT statement. On browsers I'm testing with(FF, IE, Chrome) there's no problem running the code. However, there are some people in the office who get an FF or IE error (same versions as mine) on the URL as the SRC parameter. The error, in the FF Error Console, is this: Quote: illegal character http://www.google-analytics.com/ga.js ? ? ? ? --> question marks appear in console I can't figure it out since I can't create this error on any of my browsers. Could this be related to something like browser security settings or add-ons? Hi i have this code that with Firefox work but with IE no; function showPhoto (trElemnt){ if(isKeySent) return; var photoID = ""; var photoIDCell = trElemnt.cells[1]; alert("photoID 1 ->" + photoIDCell.textContent); with IE " photoIDCell.textContent" is udefined. can some help to undertstand ? thanks in advance The following extremely simply JavaScript code: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <meta http-equiv="Content-Script-Type" content="text/javascript"> <script type="text/javascript"> onload=function(){ var n=document.getElementsByTagName('div')[0]; alert(n.innerHTML); } </script> </head> <body> <div>foo</div> </body> </html> alerts the innerHTML content in all the browsers. Except in Firefox 3.6.8, which alerts a blank value. What the f? I know that innerHTML is not a standard DOM method, but it used to be a crossbrowser one since FF 1.5, right? ------- Edit: It does not work even in case of firstChild.nodeValue or firstChild.data. FF 3.6.8 says that the DIV element has no first child, which is amazing. Hi all, I'm faced to a problem : I'm programming a styles generator for the Stylish add-on. What i want is the same thing that when i click on the button "Install with Stylish" : A Window appear to ask user if he wants to install the script with Stylish. I saved the website page on my desktop and opened it. Obviously it did not worked, nothing happens when i click. I also changed the path for javascript file in the html and so on.. There is a XMLhttprequest() function wich opens the url of the style ending by ".css". But i replaced the url by my file path ( by a locally file) and i replaced the statut (200 by 0, because i'm working on a local file). But whatever i do, nothing happens when i click. There is also a function called firecustomevent() who creates the event, but my knowledges are limited at this point. I read document on mozilla website on how to call an event but i can't get it to work. So if anybody knows how to display a windows asking the user if he wants to install the style, i will be grateful. Thanks and sorry for my bad english The url containing the javascript is a simple style url like this one : http://userstyles.org/styles/17120 where you can see the "install with stylish" button. I also attached the concerned javascript in a txt file. Hi, I'm new to JS and been thrown in at the deepend as our developer has just left! You are dealing with a total newbie! I have the following script that is not working in FF but is fine in Chrome and IE can anyone tell me what is wrong with it please?! Code: function showTotalCost(val) { if(val=='yes') { if(document.getElementById('secondaryeventtype').value == 'adventure') { document.getElementById('totalcost').innerText = Number(parseFloat(document.getElementById('cost').value) + 100).toFixed(2) + ' (including insurance)'; } else { document.getElementById('totalcost').innerText = Number(parseFloat(document.getElementById('cost').value) + 27).toFixed(2) + ' (including insurance)'; } } else { document.getElementById('totalcost').innerText = document.getElementById('cost').value; } } Code: function calculateGroupMembers() { var iMultiplier; if(document.getElementById('txtGroup1Firstname').value != '' || document.getElementById('txtGroup1Surname').value != '' || document.getElementById('txtGroup1Email').value != '') { iMultiplier=2; } if(document.getElementById('txtGroup2Firstname').value != '' || document.getElementById('txtGroup2Surname').value != '' || document.getElementById('txtGroup2Email').value != '') { iMultiplier=3; } if(document.getElementById('txtGroup3Firstname').value != '' || document.getElementById('txtGroup3Surname').value != '' || document.getElementById('txtGroup3Email').value != '') { iMultiplier=4; } if(document.getElementById('txtGroup4Firstname').value != '' || document.getElementById('txtGroup4Surname').value != '' || document.getElementById('txtGroup4Email').value != '') { iMultiplier=5; } if(document.getElementById('txtGroup5Firstname').value != '' || document.getElementById('txtGroup5Surname').value != '' || document.getElementById('txtGroup5Email').value != '') { iMultiplier=6; } document.getElementById('totalcost').innerText = Number(parseFloat(document.getElementById('cost').value) * iMultiplier).toFixed(2) + ' (inc group members)'; } It is fired from an onblur event in the div below once the chkbox is ticked, the link to the page is https://www.doitforcharity.com/book-...eid=1990&cid=0 but you may need to progress through https://www.doitforcharity.com/book-....aspx?eid=1990 first: Code: <div id="pnlGroupBooking"> <label class="boldfieldlabel" for="chkGroupBooking">Do you wish to book for others too? </label> <input id="chkGroupBooking" type="checkbox" language="javascript" onclick="__doPostBack('chkGroupBooking','')" checked="checked" name="chkGroupBooking"> (you may book up to 5 additional people) <div id="pnlGroupBookingNames" style="border: 1px solid LightGrey; width: 500px;" styles="padding:10px;"> <strong>Group Member Names</strong> <br> <p> </p> <p> </p> <p style="vertical-align: top;"> <strong>1) </strong> <input id="txtGroup1Firstname" class="formfieldsmall" type="text" onblur="calculateGroupMembers();" name="txtGroup1Firstname"> <input id="txtGroup1Surname" class="formfieldsmall" type="text" onblur="calculateGroupMembers();" name="txtGroup1Surname"> <input id="txtGroup1Email" class="formfield" type="text" onblur="calculateGroupMembers();" name="txtGroup1Email"> <br> <strong>2) </strong> <input id="txtGroup2Firstname" class="formfieldsmall" type="text" onblur="calculateGroupMembers();" name="txtGroup2Firstname"> <input id="txtGroup2Surname" class="formfieldsmall" type="text" onblur="calculateGroupMembers();" name="txtGroup2Surname"> <input id="txtGroup2Email" class="formfield" type="text" onblur="calculateGroupMembers();" name="txtGroup2Email"> <br> <strong>3) </strong> <input id="txtGroup3Firstname" class="formfieldsmall" type="text" onblur="calculateGroupMembers();" name="txtGroup3Firstname"> <input id="txtGroup3Surname" class="formfieldsmall" type="text" onblur="calculateGroupMembers();" name="txtGroup3Surname"> <input id="txtGroup3Email" class="formfield" type="text" onblur="calculateGroupMembers();" name="txtGroup3Email"> <br> <strong>4) </strong> <input id="txtGroup4Firstname" class="formfieldsmall" type="text" onblur="calculateGroupMembers();" name="txtGroup4Firstname"> <input id="txtGroup4Surname" class="formfieldsmall" type="text" onblur="calculateGroupMembers();" name="txtGroup4Surname"> <input id="txtGroup4Email" class="formfield" type="text" onblur="calculateGroupMembers();" name="txtGroup4Email"> <br> <strong>5) </strong> <input id="txtGroup5Firstname" class="formfieldsmall" type="text" onblur="calculateGroupMembers();" name="txtGroup5Firstname"> <input id="txtGroup5Surname" class="formfieldsmall" type="text" onblur="calculateGroupMembers();" name="txtGroup5Surname"> <input id="txtGroup5Email" class="formfield" type="text" onblur="calculateGroupMembers();" name="txtGroup5Email"> </p> </div> </div> Thanks! Hi all, This is my first post of many and am new to JS. I'm familiar with Java so I shouldn't be too lost. What I'm about to do is add support for a web app from Firefox to IE that uses OpenLayers. I've searched and found a link to this site from another thread which had a list of supported functions and what not he http://www.quirksmode.org/dom/w3c_core.html From what I've read in the last hour it seems as though I will have to use some browser sniffing (isMozilla, isIE8, etc) and have multiple conditions (if-else's) in my functions to use the proper calls. Does anyone have extra material that contains differences between IE and firefox? Someone mentioned to me that in lists IE doesn't support trailing commas but ff does.. Things like this would be very helpful Thanks, Chris |