JavaScript - Referring To An Already Defined Property In Object Literals
I'm using closure to make a function return an object in the form of the literal.
Code: function myFunction() { return { a : 'foo', b : 'bar', c : 'baz', d : this.a } } I'd want the d property to be equal to "foo". However, when I do that, "this" is tied to the global namespace as opposed to the object. Any ideas? Julian Similar TutorialsI am and seem to remain newbie ... I have a JS script that presents a series of "pages" with different questions inside a single HTML file, by rewriting certain <div>s. I have an object like this that contains the questions and information about answer labels etc (the idea is that this should be easy to modify for someone who doesn't know JS): Code: var Questions = [ { "question" : "How good is this?", "labels" : ["excellent","very good","good","bad","very bad","awful"], "page" : 0 , "random" : false , "type" : "default", "varname" : "allgood" }, { "question" : Change[curCase]+"What do you think now?", "labels" : BetterLabels, "page" : 1 , "random" : true , "type" : "default", "varname" : "betteradapt" } ] This object is initialized when the page loads, and a function reads the total number of pages by getting the maximum number of the "page" property across elements. Later, the object is accessed by thenextQuestion() function which uses the "page" property to looks whether each element belongs on the current page , then reads out the properties and presents the question. This works okay. Now the tricky bit: For some questions, their text should be different depending on which case is currently on the screen (Change[curCase]). curCase is different on each page, an integer between 0 and Change.length. I cannot get this to work for the Questions object, probably because the Questions object has been already initialized when the page loaded. How can I get my function nextQuestion() to "re-evaluate" the property "question" for all the elements of the Questions objectwhen nextQuestion() is called , using the current value of "curCase"? nextQuestion() is longer, but the (i think!) crucial bits are he Look whether question belongs on current page and push it onto new array: Code: for (i=0; i < Questions.length; i++) { Questions[i].page = Questions[i].page; if ( Questions[i].page == BlockNum ) { // if the q belongs on the current page QuestionsObjectThisPage.push(Questions[i]); } } Then, extract an array containing the questions, which will then be presented: Code: for (i=0; i < QuestionsObjectThisPage.length; i++) { QuestionsThisPage.push(QuestionsObjectThisPage[i].question) ; } So what I'm looking for is something to change either of these two Object.push() functions so they don't simply take the value they find in the Questions (or QuestionsThisPage) object, but to re-evaluate the code for the "questions" property, taking into account the current value of curCase Phew. I found that really hard to describe; hope it's somewhat clear. Hello, how can I make the following object work properly so when I use 'layers.photo1.layer' a jQuery element is returned rather than the text of the function as it is now. I also need to be able to find the element by the photo1 object its contained in not have to input a string there so that I can also reuse it in the background layer. Code: var layers = { photo1 : { layer: function() { return $(element).find($('photo1'))} }, background : { layer: function() { return $(element).find($('background'))} } } Thx Very Much! Hello just a quick problem with a seemingly difficult solution that I'm not aware throughout. What I'm attempting to do is increment a value when the mouse hovers over the element by using this move_right function: Code: function Move_Right( event, element, number) { number++; var elem = document.getElementById(element); elem.style.right = number + "px"; } inside the mouseover event trigger function which I figured out. The problem is it doesn't move incrementally only once every mouse hover no matter the technique of setInterval(); and or setTimeout(); also ontop of this problem I'm getting errors like : 2014-10-12 20:07:57.785Uncaught TypeError: Cannot read property 'style' of null even after the changes I made also after this original function call : This is the current code so far which is different to the previous code above "obviously" : Edit fiddle - JSFiddle Thanks if someone knows the issues here, I hope it makes sense . My website is working perfectly on Firefox but when I visit it with IE(7), I get the following errors and some things aren't where they're supposed to be. Quote: Webpage Script Errors User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30618) Timestamp: Fri, 25 Sep 2009 08:31:56 UTC Message: Object doesn't support this property or method Line: 8 Char: 186 Code: 0 URI: http://icarwakim.com/media/system/js/mootools.js Message: Object doesn't support this property or method Line: 59 Char: 102 Code: 0 URI: http://icarwakim.com/media/system/js/mootools.js Website: http://www.icarwakim.com Any advise? I'm Sunita. I am working in ASP .net . I have created Class1.dll file . and in javascript I am creating ActiveXobject . when i debug the application . Its gives error like Object doesn't support this property or method. my code is Code: Class1.cs using System; using System.Collections.Generic; using System.Text; using System.IO.Ports; namespace Ana7140 { public class Class1 { //Declare Variables string data = ""; string log = ""; bool DoneDataReceived = false; bool tare = false; private SerialPort comport = new SerialPort(); public void send() { //Send comport comport.Write("?1"); if (data.Length > 1) { data = data.Replace('\r', ' '); char sign = data[1]; string DelimeterStr = "+-"; char[] delimiter = DelimeterStr.ToCharArray(); string[] splited = null; splited = data.Split(delimiter); data = Convert.ToString(sign) + Convert.ToString(Convert.ToDouble(splited[1])); } else { data = ""; } } public string GetValue() { //Send command to port if (comport.IsOpen) { if (tare == true) { comport.Write("?1"); log = log + "Sent ?1 command"; //if (data.Length > 1) //{ // data = data.Replace('\r', ' '); // char sign = data[1]; // string DelimeterStr = "+-"; // char[] delimiter = DelimeterStr.ToCharArray(); // string[] splited = null; // splited = data.Split(delimiter); // data = Convert.ToString(sign) + Convert.ToString(Convert.ToDouble(splited[1])); //} //else //{ // data = ""; //} while (true) { if (DoneDataReceived == true) { DoneDataReceived = false; break; } } tare = false; }//end of if(tare==true) else { data = "-2"; } } else { data = "-1"; } //This will return the data only return data; } //To fetch the data from Serial Port public void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { if (comport.IsOpen) { //Reading Data from Serial Port data = comport.ReadLine();//.ReadExisting(); log += data; // GetValue(); if (data.Length > 1) { data = data.Replace('\r', ' '); char sign = data[1]; string DelimeterStr = "+-"; char[] delimiter = DelimeterStr.ToCharArray(); string[] splited = null; splited = data.Split(delimiter); data = Convert.ToString(sign) + Convert.ToString(Convert.ToDouble(splited[1])); } else { data = ""; } DoneDataReceived = true; //Done with data processing } } catch (Exception ex) { //MessageBox.Show(ex.Message); } } public string getLog() { return log; } //This Function initialiases the serial port //public void Initialise() //{ // try // { // isInitialise = true; // correct = false; // init = true; // //sending command to serial port for initialization // //comport.Write("*\n"); // } // catch (Exception ex) // { } //} public void Tare() { try { //sending command to serial port for initialization comport.Write("T\n"); tare = true; } catch (Exception ex) { } } //This function opens the comport public void Start() { try { //if previously comport is open the firstly close this connection then open again comport if (comport.IsOpen) { comport.Close(); } else { //set Baudrate value as 300 comport.BaudRate = 300; //to read data in string set Data bits as 8 comport.DataBits = 8; //set stop bits as 1 comport.StopBits = (StopBits)1; //set parity bit as None comport.Parity = (Parity)Enum.Parse(typeof(Parity), "None"); //Set Port Name as COM1 //comport.PortName = "COM1"; //Set Read Time Out as 100 comport.ReadTimeout = 100; //Open comport comport.Open(); //Call event for serial data received comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); //data = ""; // comport.Write("?1"); } } catch (Exception ex) { } } //close the connection and close the comport public void Stop() { try { //check whether comport is open or not //if comport is open then close the comport if (comport.IsOpen) { //comport.ReadExisting(); comport.Close(); } } catch (Exception ex) { } }//End of Stop //To check Connection is Opened or not public string getStart() { string check = ""; try { if (comport.IsOpen) { check = "0"; //If the connection is opened,then check=0 } else { check = "-1"; //If the connection is closed,then check=-1 } }//End of try catch (Exception ex) { } return check; }//End of getStart } } JavaScript program is <!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" > <head><title> Untitled Page </title> <script language="javascript"> var wshell; wshell=new ActiveXObject("Ana7140.Class1"); function GetVal() { var val= wshell.GetValue(); alert(val); } function setip() { wshell.Start(); wshell.Initialise(); alert(val); } function Stop() { wshell.Stop(); //alert(val); // wshell.Stop(); //alert(val); } function Tares() { wshell.Tares(); //alert(val); // wshell.Stop(); //alert(val); } </script> </head> <body> <form name="form1" method="post" id="form2"> <div> <a href="#" onclick="javascript:setip()"> Connect </a> <a href="#" onclick="javascript:GetVal()"> Acquire Weight </a> <a href="#" onclick="javascript:Stop()"> Disconnect </a> <a href="#" onclick="javascript:Tares()"> Tares </a> </div> </form> </body> </html> plz help me Hi All, Need some urgent. We are having a javascript which is throwing the foll error "Object doesn't support this property or method". The javascript function being called is using a Scanner API. So this is using some ActiveX. Below is the code for javascript <script language="javascript"> // Initialize scanning function OnLoad() { try { Scanner.OpenScanner(); // Scanner.ScanPriority = 0; // Set scanner to Foreground Read mode before enable scanning // Scanner.EnableScanning(1); document.forms["mobileform"]["rm07m-bwartwe[1]"].value = "101"; } catch (e) { alert(e.message); } } // Clean up function OnUnload() { Scanner.CloseScanner(); // Calling Dispose is necessary for Pocket IE because of a Microsoft issue related to releasing object. if (navigator.appName == "Microsoft Pocket Internet Explorer") Scanner.Dispose(); } // Scan through soft trigger function Scan() { try { Scanner.SetSoftTrigger(1); } catch (e) { alert(e.message); } } //User-defined function to format error codes. //VBScript has a Hex() function but JScript does not. function hex(nmb) { if (nmb > 0) return nmb.toString(16); else return (nmb + 0x100000000).toString(16); } </script> There is a object tag in html <object id="Scanner"></object> The javascript functions are called from body tag. Can someone please provide some help. Thanks, Nikhil Hello I am in need of help desperatley. I am trying to get a video to launch from my homepage. see test homepage here http://www.nuviewinc.com/index3.html the video should pop up and play. Like it does here- http://www.nuviewinc.com/testv.html But it doesnt... can anyone help this poor marketing manager with coding? I simply followed the directions here http://www.vmatrixonline.com/vplayer...structions.pdf. all the code appears correct. I do not really understand what is happening to my code but it just tell me the following: Code: document.getElementById("#movingword") is null How could the movingword be null when I have declared it in my code? The following is my code: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="language" content="english"> <meta http-equiv="Content-Style-Type" content="text/css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <title></title> <style type="text/css"> body { background-color:#000; } #scenery { position:relative; } #moving { position:absolute; float:right; top:100px; left:50px; } #movingword { position:absolute; float:right; top:0px; left:0px; } </style> <script type="text/javascript"> var a=120; $(document).ready(function() { document.getElementById("#movingword").style.top = a + "px"; }); </script> </head> <body> <font color=white><h1> Hello World </h1></font> <div id="scenery"> <img src="http://www.deshow.net/d/file/travel/2009-10/new-zealand-scenery-738-20.jpg" alt=""> <div id="moving"> <img src="http://maadinfo.com/images/blinking.gif" alt=""> </div> <div id="movingword"> <font color="yellow"><font size="3"><b>This is the place</b></font><br>Welcome!</font> </div> </div> </body> </html> I found strange for the following code: Code: var allextRules = Ext.util.CSS.getRules(); Object.keys(allextRules).forEach(function(key) { var keyname = key; if(keyname.indexOf("js") != -1){ Ext.util.CSS.removeStyleSheet(keyname); console.log(keyname + " Removed"); } }); When the above work is tested in other browser (say - Google Chrome), there is no error. However, when tested in IE 9, there is error as follows: Code: SCRIPT438: Object doesn't support property or method 'keys' According to this article (https://developer.mozilla.org/en/Jav...ts/Object/keys), the Object.keys is supported by IE. Have I miss out something? Hi, When I try and geocode an addres to my google map I receive the error: Object does not support this method or property I have gone over the script and can't work out what I did wrong. Code: <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html {height:250px} body {height:250px} #bookmark_map {width:90%; height:250px; margin-left:15px;} </style> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true" /> </script> <script type="text/javascript"> var geocoder; var map; function createGMapFromAddress(){ geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(0,0); var map_options = { zoom: 4, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("bookmark_map"), map_options); } function loadBookMarkMap(location){ alert(location); var address = location; alert(address); geocoder.geocode({address: address}, function(results, status){ if (status == google.maps.GeocoderStatus.OK && results.length){ if (status != google.maps.GeocoderStatus.ZERO_RESULTS){ map.set_center(results[0].geometry.location); var marker = new google.maps.Marker({ position: results[0].geometry.location, map: map }); } } else { alert("Geocode was unsuccessful due to: " + status); } }); alert(marker); } </script> </head> <body onload="createGMapFromAddress()"> //php get from table $possumshaw ="{$row['address']}"; } echo '<input type="button" class="button4" value="View Map" onclick="loadBookMarkMap(\'' . $possumshaw . '\')" />'; ?> Hi,
I have a form in my site.when the form is submit successfully it's go to another page, which shows "submission is success".
and that page has a link to go back to a page which is viewing previously(before to form)
this is the code for it Code: <a href="javascript:history.go(-2)">Go back to previous</a> I want to know, how to go to previous page by automatically ??? this should be happen after 10 seconds! please help me.... Hi, I'm a retired social worker with beginner skills in scripting a web page and need some suggestions. I create eLearning materials which are given away as a communty service to help people improve their health. A typical eLearning project has a few educational screens (using a Learner Management System-LMS-template) and an interactive exercise (on an external web page-htm or html-usually accessed by button which navigates to the exercise's URL). The interactive exercise should only be accessed from inside the eLearning lesson using the button, because it requires understanding of the way it works plus important cautions to assure proper use. I need to prevent the use of the URL outside of taking the lesson (for example, someone taking the lesson acquires the exercise's URL from their browser history and then may give this to others who access the exercise directly-without necessary knowledge and cautions). I tried document.referrer, using JavaScript. Using the referrer URL from inside the lesson and adding the JavaScript to the exercise's htm code worked OK in FF, but not in IE 8. In FF, if the referrer was not the correct single URL from inside the lesson, then it redirected; if the correct URL, the exercise appears. The JS code follows: Code: <script language="JavaScript" type="text/javascript"> <!-- var oksite = "http://www.mysite.com/xyz/courseidxxxxx/yyyy/zzz.html"; var redirect = "http://mysite.com/error.html"; if (document.referrer != oksite) { location.replace(redirect); } //--> </script> In IE 8, I was not able to get it to work. Using an alert, I noticed that the referrer in IE 8 was blank. My web hosting (GoDaddy) is a shared Windows hosting. I would have to upgrade from IIS6 to IIS7 to use PHP. Bigger challenge: I've never used PHP. If possible, I would prefer to use JS. But, I am open to any suggestion that will help. I am also wondering if part of the IE 8 issue is that I am using IE 8 X 64? I'm stuck and hope someone can suggest a way to solve this access issue. Thanks for your help. Kind Regards, saratogacoach I want to append a string "&sid=xyz" to the current page URL if the referring URL comes from site www.xyz.com. I have the following code - var query = location.search.substring(1); if (document.referrer.indexOf(/xyz/) > 0) { query = query + "&sid=xyz"; } However, the string is not being appended. Can anyone see where the problem lies? I am using a third party shopping cart service written in php. I don't have access to the php code so I decided to use javascript to write a cookie. What I'm trying to do is have the cookie capture the referring URL and then keep it for a day and have it follow where ever the visitor goes in the shopping cart. Then when they check out, the referring URL will populate a form field and be returned as part of the form results. This way I can track where my visitors come from. My code is below and I'm adding it to the file designated as the head section. (The files I have access to must use some form of include but I can't use php in them - just html and javascript. I've tried.) I have an alert in the code that suggests something to do as well as set the cookie. The alert comes up and the cookie is set but when you go to another page, the alert comes up again and another cookie is set. I just need to have it set once so when they fill out the order form, I'll know where they came from. This is my code and thanks for the help. Code: <SCRIPT LANGUAGE="JavaScript"> cookie_name = "dataCookie"; var referred; function getName() { if(document.cookie) { index = document.cookie.indexOf(cookie_name); if (index != -1) { namestart = (document.cookie.indexOf("=", index) + 1); nameend = document.cookie.indexOf(";", index); if (nameend == -1) {nameend = document.cookie.length;} referred = document.cookie.substring(namestart, nameend); return referred; } } } referred=getName(); if (referred == "dataCookie") {referred = "No-Referral"} function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "=") if (c_start!=-1) { c_start=c_start + c_name.length+1 c_end=document.cookie.indexOf(";",c_start) if (c_end==-1) c_end=document.cookie.length return unescape(document.cookie.substring(c_start,c_end)) } } return "" } function setCookie(c_name,value,expiredays) { var exdate=new Date() exdate.setDate(exdate.getDate()+expiredays) document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : "; expires="+exdate.toGMTString()) } function checkCookie() { { var cookieEnabled=(navigator.cookieenabled)? true : false //if not IE4+ nor NS6+ if (typeof navigator.cookieenabled=="undefined" &&!cookieEnabled) { document.cookie="testcookie" cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false } if (cookieEnabled) { var todaysdate = new Date() var day = todaysdate.getDay() switch (day) { case 1: day = "Monday" break case 2: day = "Tuesday" break case 3: day = "Wednesday" break case 4: day = "Thursday" break case 5: day = "Friday" break case 6: day = "Saturday" break case 0: day = "Sunday" break } var thedate = getCookie('thedate') if (thedate != null && thedate != "") { if (day == thedate) {} else {alert('Be sure to subscribe to our newsletter.')} } else { thedate = day if (thedate!=null && thedate!="") { { cookie_name = "dataCookie"; var referred; if(document.cookie != document.cookie) {index = document.cookie.indexOf(cookie_name);} else { index = -1;} if (index == -1) { referred=document.referrer; document.cookie=cookie_name+"="+referred; } } {setCookie('thedate', thedate, 365)} alert('Be sure to subscribe to our newsletter.') } } } else {alert('Please Enable Cookies. This site uses Cookies during your visit.')} } } 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() { checkCookie(); }); //--> </script> In the body I am reading it with a form field of Code: <SCRIPT LANGUAGE="javascript"> document.write("<FORM>") document.write("Originally Referred by:") document.write("<INPUT id='cookiealert' TYPE=text style='width:300px' VALUE=" +referred+ ">"); document.write("</FORM>") </SCRIPT> I am using a web tracking tool called REinvigorate, which is great but doesn't give you the ability to exclude specific referring domains from the stats. However, their support guy told me that I can accomplish this by referencing the referring domain in a small script that only calls the tracking code when the referring site is not "This one we don't want in our stats". I only know C# and SQL, though, so I'm not entirely sure how to do this. Is this right? spreecommerce.com is the domain we want to exclude... <script type="text/javascript"> if (document.referrer.search("/spreecommerce/") != -1) { document.getElementById('iFrameId').src = '<trackingcode>'; } </script> Thanks! Austin Hi, every time I try and alert: [ { number:0, secondnumber:0 }, { number:2, secondnumber:1 }, { number:1, secondnumber:2 } ] it just shows [object object], [object object], [object object]. Why is this and what can I do to make the record be shown as it is above in an alert? Thanks. I created a method for displaying an object's properties: Code: renderfunction = false; function showProperty (object, property) { document.write ('<td class="type">' + (typeof object[property]) + '</td>' + '<td class="name">' + property + '</td>'); document.writeln('<td class="value">' + ( (typeof object[property] != 'function') ? object[property] :( (property != 'showProperties') ? ( renderfunction ? object[property]() : ('<span class="self">NOT RENDERED</span>') ) : ('<span class="self">THIS</span>') ) ) + '</td>'); document.writeln('<td class="hasOwnProperty" >' + ( object.hasOwnProperty(property) ? "Local" : "Inherited" ) + '</td>'); if (typeof object[property] == 'function') { document.writeln ('<td class="function">' + object[property] + '</td>'); } else { document.writeln ('<td class="function"> </td>'); } } As long as renderfunction = false, the object is fine coming out of this function. However, if I change renderfunction to true, all my properties become undefined. Why isn't this working as I expect it to? How should I fix it? Thanks in advance, -Brian. I can't get any info from Firebug except that one line, uncaught exception [object Object]. The code fully worked, then I needed to make it dynamically create Sortables from the scriptaculous library based on how many X were in a table in my database, which I've done, and I'm thinking it may be a simple slight parse error of some type, I'm not too good with Javascript, because now my script barely works. I've double checked the script's source code, the PHP variables are exactly what they should be. Code: print<<<HERE Sortable.create('sortlist$box', { tag: 'img', overlap:'horizontal',constraint:false, containment: $list, dropOnEmpty: true, onChange: function(item) { var list = Sortable.options(item).element; if(changeEffect) changeEffect.cancel(); changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" }); }, onDrop: function(item) { var thing=Sortable.options(item).element.identify(); var anchors = document.getElementById(thing).childNodes.length-2; if(anchors > 20){ alert('This box had 20 creatures in it already, your last action has not been saved.'); window.location.reload(); } else{ new Ajax.Request("saveImageOrder.php", { method: "post", parameters: { data: Sortable.serialize("sortlist$box") } }); } } }); HERE; $box++; } ?> }); </script> if you solve this I'll send ya $10 via paypal I'm writing a program that involves a network of interconnected nodes (or simply objects in my example below). It depends on being able to access properties of an object's linked objects (a bit oddly worded, sorry)... Problem is I'm not sure how to properly access those properties... see below please. <script> //This is an example of a problem im having in my own code... //I want to access the name of the object within the links array wintin the object... var objA = {name: "Object A", links: [objB, objC]}; var objB = {name: "Object B", links: [objC, objD, objE]}; var objC = {name: "Object C", links: [objB]}; var objD = {name: "Object D", links: [objE]}; var objE = {name: "Object E", links: [objD]}; //ex: I want to access the name of Object A's first link... console.log(objA.links[0].name); </script> I'm hoping to get "Object B"... But instead I get: TypeError: Result of expression 'objA.links[0]' [undefined] is not an object. Is there another way around this? Any thoughts are appreciated. Hi all, I'm stumped on finding a way in javascript to create an object factory whose instances are also object factories. In short I want something like that below, but no joy ... any clues? Code: function createClass () { return new createClass() function createClass() { return new createInstance () function createInstance () { //Default properties, values and methods which might later be extended } } } var createDoor = createClass(); var door1 = createDoor(); var door2 = createDoor(); var createChair = createClass(); var chair1 = createChair (); var chair2 = createChair (); |