JavaScript - How To Define A Global Variable For All The Functions
Hi,
Here's a sample form: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Sample form</title> <script type="text/javascript"> function displayResult() { alert(document.myForm.myInput.value); } function getFocus() { if (document.myForm.myInput.value == document.myForm.myInput.defaultValue) { document.myForm.myInput.value = ""; } } function loseFocus() { if (document.myForm.myInput.value == "") { document.myForm.myInput.value = document.myForm.myInput.defaultValue; } } </script> </head> <body> <form name="myForm" method="get" onsubmit="return false;" action=""> <input name="myInput" value="Hello world!" onfocus="getFocus();" onblur="loseFocus();"><br> <input type="button" onclick="displayResult();" value="Display input value"> </form> </body> </html> It works with no problem, but the following doesn't: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Sample form</title> <script type="text/javascript"> var x = document.myForm.myInput; function displayResult() { alert(x.value); } function getFocus() { if (x.value == x.defaultValue) { x.value = ""; } } function loseFocus() { if (x.value == "") { x.value = x.defaultValue; } } </script> </head> <body> <form name="myForm" method="get" onsubmit="return false;" action=""> <input name="myInput" value="Hello world!" onfocus="getFocus();" onblur="loseFocus();"><br> <input type="button" onclick="displayResult();" value="Display input value"> </form> </body> </html> What's wrong with it and how can I define a global variable to be used by all the functions? Many thanks in advance! Mike Similar TutorialsHi, I have a programing problem that have been around for ages. I have search on google using several expressions and words and after hours of digging i'm still unable to do it. I would like to get a value from a HTML page hosted remotely with an inconstant value. Then define this value and name as a javascript variable and apply or show in my page. Thanks for all the help P.S. Is there any way to make a domain lookup in javascript? I mean a user enters a domain and the script converts to an ip and shows to the user. If not thanks, probably it can only be done in the server side... Hi everyone! I am building a simple web application in which the user inputs some html code in a <textarea> and the corresponding result (output of the code) is shown! The problem I am facing is that suppose the user enters some code and wishes to wrap it inside specific tags (e.g. <script></script>) then she just selects the corresponding code and clicks a predefined button and the selected code gets wrapped inside those tags! Now, what I am thinking right now is that when the user selects some code and clicks the button the selected text goes inside a variable (e.g. old_variable) and a new variable (new_variable = "<script>" + old_variable + "</script>") is returned! But I was just wondering how to send the selected code in the variable i.e. old_variable using JavaScript? Any help/hint/suggestion/advice would be highly valuable for me! Thanks! hello I want ask how can i declare global variable in html file , and use it in java script file . - with same value- thanks I am working with the google blogger API, and I am having an issue updating my global variable Response. I thought I understood how global variables worked, so I don't know if there is something different about the blogger API or if I'm making a dumb mistake. Code: <SCRIPT TYPE="text/javascript" src="http://www.google.com/jsapi"></ script> <script> google.load("gdata","1.x", {packages: ["blogger"]}); google.setOnLoadCallback(getMyBlogFeed); blogID = "1601946089552390859"; var feedUri = "http://www.blogger.com/feeds/"+blogID+"/posts/full?alt=json"; var Response = ""; function getMyBlogFeed(){ var myBlog = new google.gdata.blogger.BloggerService('GoogleInc-jsguide-1.0'); myBlog.getBlogPostFeed(feedUri, handleBlogFeed, handleError); } function handleBlogFeed(myResultsFeedRoot) { Response = myResultsFeedRoot.feed.entry[0].content.$t; } function handleError(e) { alert("There was an error in getBlogPostFeed"); alert(e.caue ? e.cause.statusText : e.message); } alert(Response); </SCRIPT> Here's what I think SHOULD happen: Response is initialized as a global variable with a value of "" setOnLoadCallback calls getMyBlogFeed which creates a blog object, then calls getBlogPostFeed which calls handleBlogFeed. handleBlogFeed stores a new string to global variable Response an alert pops up with the value of Response (as given by handleBlogFeed) What actually happens is that the alert pops up with the original value of Response. I know that I can issue the alert inside handleBlogFeed, but that isn't the issue. My issue is that I'd like to use Response in other functions, but it isn't being updated as a global variable. What am I doing wrong that Response isn't updating? On a related note, is there a way to return a variable from my handleBlogFeed function? How would I do that? -- I can't seem to figure it out. Thanks! P.S. I recognize that the best place to ask this is the blogger developer group. I've already posted this there, and no one has responded yet. I am trying to figure out how to assign a value to a global variable within a function and can't seem to figure it out. Here's my thought, Code: <script type="text/javascript"> var global1=""; var global2=""; function assign(vari,strng){ vari = strng; } </script>... <input name="box1" onblur="assign('global1',this.value)"/> <input name="box2" onblur="assign('global2',this.value)"/> ... The purpose behind this is creating a form that will work with an existing database that would normally have a text area with lots of information. I am trying to turn it into a checklist that I can run from a mobile device. The global variables woudl be used to fill in a hidden text area that would then be passed on to the database upon submission. I am trying to keep the code as compact as possible. Any ideas? hello im trying to change a variable set outside of a function and calling the function with an onchange... i'm having problems getting the variable to change Code: <script type="text/javascript"> var price = '<?php echo $price; ?>'; function addtwo() { if(document.add.size.value == "2xl") { price = price + 2; } } </script> Hi, Is is possible to access a global variable for use inside a function? Thanks for help in advance Mike Heres a link to the code in question http://www.scccs.ca/~W0049698/JavaTe...erlocktxt.htm# when the leftPos variable is used in the moveSlide() it somehow turns into Nan. Cant figure out why and have been racking my brain over this for a long time now.. Any help would be greatly appreciated the problem is at the end of the code(scroll to the bottom) ======================================================= Code: window.onload = makeMenus; var currentSlide = null; var timeID = null; function makeMenus(){ var slideMenus = new Array(); var allElems = document.getElementsByTagName("*"); 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++){ // alert(slideMenus.length) slideMenus[i].onclick = showSlide; slideMenus[i].getElementsByTagName("ul")[0].style.left = "0px"; } document.getElementById("head").onClick = closeSlide; document.getElementById("main").onClick = closeSlide; } function showSlide(){ slideList = this.getElementsByTagName("ul")[0]; if(currentSlide && currentSlide.id == slideList.id) {closeSlide()} else{ closeSlide(); currentSlide = slideList; currentSlide.style.display = "block"; timeID = setInterval("moveSlide()", 1); } } function closeSlide(){ if(currentSlide){ clearInterval(timeID); currentSlide.style.left="0px"; currentSlide.style.display="none"; currenSlide = null; } } Code: Hey all! Got a question I can't seem to find an answer to. I have a little JS app that is a glorified calculator which I posted the code for below. My code uses the document object to replace the html in the "content" <div> and works great. However, I want to add an inline style in order to change the background of the input (readonly field with an id of "coutput") based on either of the global variables named "MJPD" or "IJPD", (depending on the switch case selected in the user prompt at the beginning of the script.) Simplified....if the value of MJPD is less than 4.6, I want the "coutput" field's background to be red, else be green. The same goes for IJPD, except the threshold for red will be <3.83. Code and what I have tried is below. After reading the code, look below it to see what I have tried and maybe tell me what I'm doing wrong! =) Any help is greatly appreciated.......I have spent a week searching for this little answer and I can't seem to find it! Code: <script language="JavaScript"> var MJPD = 1; var IJPD = 1; function sayhello(){ // *** live test for inline JS code placement alert("IT WORKS!!! Now change me =)"); } ////////////////////////////////////////////////////// function changeScreenSize(w,h) { window.resizeTo( w,h ) } /////////////////////////////////////////////////// function iJPDCalc(form) //calculate IJPD value { var ij = parseFloat(form.IJobs.value, 10); var it = parseFloat(form.ITime.value, 10); var IJPD = 0; IJPD = (ij / it) * 8.0; form.I_JPD.value = IJPD; } ///////////////////////////////////////////////////// function mJPDCalc(form) //calculate MJPD value { var mj = parseFloat(form.MJobs.value, 10); var mt = parseFloat(form.MTime.value, 10); var MJPD = 0; MJPD = (mj / mt) * 8.0; form.M_JPD.value = MJPD; } ///////////////////////////////////////////////////// function ijpdcolor() //set bg color of coutput based on IJPD's value { if (IJPD >= 3.83) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function mjpdcolor() //set bg color of coutput based on MJPD's value { if (MJPD >= 4.6) { return ("green"); } else { return ("red"); } } ///////////////////////////////////////////////////// function startVZT3(){ var n=0; n=prompt("What would you like to do? 1: Calculate IJPD 2: Calculate MJPD 3: Exit", "Enter a value from 1-3") switch(n) { case(n="1"): document.getElementById("content").innerHTML='<FORM><h2>Combined IJPD Calculator</h2><p>Install components completed today:</p><INPUT NAME="IJobs" VALUE="3.84" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="ITime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your IJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=iJPDCalc(this.form)><p>Your current combined IJPD for today is:</p> <INPUT NAME="I_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="2"): document.getElementById("content").innerHTML='<FORM><h2>Combined MJPD Calculator</h2><p>Trouble components completed today:</p><INPUT NAME="MJobs" VALUE="4.6" MAXLENGTH="10" SIZE=10><p>Hours taken to the jobs:</p><INPUT NAME="MTime" VALUE="8" MAXLENGTH="10" SIZE=10><h4> Click the button to calculate your MJPD:</h4><INPUT NAME="calc" VALUE="Calculate" TYPE=BUTTON class="cbutton" onClick=mJPDCalc(this.form); mjpdcolor();><p>Your current combined MJPD for today is:</p> <INPUT NAME="M_JPD" class="output" style=" " id="coutput" READONLY SIZE=10></FORM>'; break case(n="3"): alert('This page will now close...'); window.close(); break default: document.getElementById("content").innerHTML='<h1 style="padding-top: 40px; color: red;">You need to enter a value! Please try again...</h1>'; break } } /////////////////////////////////////////////////////// </script> </head> <body onload="changeScreenSize(825,775)"> <div id="wrapper"> <div id="sub_wrapper"> <br /> <br /> <input type="button" class="button" onclick="startVZT3()" value="Start VZT3 Web!" /> <br /><br /> <div id="content"> <h3 style="padding-top:60px;">VZT3</h3> </div> </div> <script type="text/javascript"> <!-- trying script to ensure function and dynamic update of this value - doesnt work 2/3/2010 --> document.write(mjpdcolor()); </script> </div> </body> OK, so on the last line of each case statement where it injects html code into the content div, in this code style=" background: ** ** " and in between the ** ** marks, I have added such things as <script type="text/javascript">document.write(mjpdcolor())</script> (or ijpdcolor, depending on which case I am working with). Theoretically, this should pull the value of MJPD (or IJPD), evaluate it for the if statement, then return the value of red or green and set the value of the background dynamically - but of course it doesnt. I have also tried different inline styles and even adding the css id and trying to link it to the mjpdcolor() function, but all to no avail. Can someone help me please?? Thanks everyone, your awesome! Hi there I'm nearly completed on a game, and want to bring in "Lives", basically, rather than the game ending, running "function EndGame ()" I want to allow the player to carry on with "Lives", 3 in fact. Basically, when the player presses a wrong tile, the game needs to carry on, until the last life, life 3 is lost, then "function EndGame ()" runs.. I believe a Global Variable needs to be used? If any help could be given that would be great, also if it could be shown in JSFiddle, that would be great! Many thanks Reply With Quote 12-18-2014, 03:56 PM #2 Dormilich View Profile View Forum Posts Senior Coder Join Date Jan 2010 Location Behind the Wall Posts 3,532 Thanks 13 Thanked 372 Times in 368 Posts Originally Posted by LONDONLAD I believe a Global Variable needs to be used? nope. you can use a global, but you should not. better use the variable/container that you store the player or game status in. Is it possible to make a variable available to other functions outside a function So to make it global from within a function without using a callback Code: function() { var something = 'hello'; } function(something) { document.write(something); } something like that possible?? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <title>JS: Image Slider</title> <script type="text/javascript"> var img = []; img[img.length] = {src: "http://www.blogsdna.com/wp-content/uploads/2011/03/Google-labs.png", cap: "", url: "", des: "" }; img[img.length] = {src: "http://thenextweb.com/socialmedia/files/2010/07/youtube_logo.png", cap: "", url: "", des: "" }; img[img.length] = {src: "http://www.techlifeweb.com/facebook_logo.jpg", cap: "", url: "", des: "" }; img[img.length] = {src: "http://www.thetechherald.com/media/images/201115/Adobe_2.jpg", cap: "", url: "", des: "" }; img[img.length] = {src: "http://scm-l3.technorati.com/10/05/10/12671/twitter-logo-5.jpg", cap: "", url: "", des: "" }; img[img.length] = {src: "http://www.easyquestion.net/learninginadigitalworld/wp-content/uploads/2009/06/ms-office-logo.jpg", cap: "", url: "", des: "" }; for (var imgs=[], i=0; i<img.length; i++){ imgs[i] = new Image(); imgs[i].src = img[i].src; } var curPic = 0; var fadeTimer; var speed = 50; var opacStep = 0.5; var dirn; var curOpac = 10; var ctrl; var showTimer; dirn = -1; function autoImage(){ if(fadeTimer){clearInterval(fadeTimer);} fadeTimer = setInterval(setOpacity,speed); function setOpacity() { curOpac += opacStep * dirn; if (curOpac < 0){ swapImage(); curOpac = 0; dirn = 1; autoImage(); return; } if (curOpac > 10){ curOpac = 10; clearInterval(fadeTimer); dirn = -1; showTimer = setTimeout(autoImage,1000); return; } if (imgSlider.style.opacity=="string"){ imgSlider.style.opacity = curOpac/10; } else { imgSlider.style.filter = 'alpha(opacity=' + curOpac*10 + ')'; imgSlider.style.MozOpacity = curOpac/10; } } function swapImage(){ curPic = (++curPic > img.length-1) ? 0 : curPic; imgSlider.src = img[curPic].src; } } function shuffleImage(){ if(fadeTimer){clearInterval(fadeTimer);} fadeTimer = setInterval(setOpacity,speed); function setOpacity() { curOpac += opacStep * dirn; if (curOpac < 0){ swapImage(); curOpac = 0; dirn = 1; shuffleImage(); return; } if (curOpac > 10){ curOpac = 10; clearInterval(fadeTimer); dirn = -1; showTimer = setTimeout(shuffleImage,1000); return; } if (imgSlider.style.opacity=="string"){ imgSlider.style.opacity = curOpac/10; } else { imgSlider.style.filter = 'alpha(opacity=' + curOpac*10 + ')'; imgSlider.style.MozOpacity = curOpac/10; } } function swapImage(){ curPic = Math.ceil(Math.random()*img.length)-1; imgSlider.src = img[curPic].src; } } window.onload = function(){ imgSlider = document.getElementById('imgSlides'); imgSlider.src = img[curPic].src; } auto = true; function autoCtrl(){ if(!auto){ clearInterval(fadeTimer); clearTimeout(showTimer); auto = true; } else{ autoImage(); auto = false; } } shuffle = true; function shuffleCtrl(){ if(!shuffle){ clearInterval(fadeTimer); clearTimeout(showTimer); shuffle = true; } else{ shuffleImage(); shuffle = false; } } </script> </head> <body> <img id="imgSlides" src="" style="width: 500px; height: 500px;" alt="" /> <br /> <a href="javascript: autoCtrl()" title="Play / Pause">AUTO</a> <a href="javascript: shuffleCtrl()">SHUFFLE</a> </body> </html> My problem is that every other turn I have to click either button twice to start the desired function. Say, I autoplay the images first and I want to shuffle them, I click shuffle and the autoplay stops working and I need to click shuffle again and then the shuffle runs. How can I make it clicked once and the function runs? Hi, I have written a number of functions designed to return frequency data on 1000 randomly chosen numbers using different math functions for the rounding. I would like to include all of these functions within the wrapper of another function so that only one call is needed to get returns from all of the 'inner' functions. However, while each of the functions works in isolation, the moment I wrap them in another function they stop working. The following code is one of the functions 'frequencyWrapperOne' that has been wrapped in the function 'testWrapper'. A call to testWrapper does nothing. Can anyone see what I'm doing wrong? Code: function testWrapper() { function frequencyWrapperOne() { var numberArrayOne = new Array(0,0,0); for (var i = 0; i < 1000; i = i + 1) { var chosenNumber = Math.floor(Math.random() * 3); if (chosenNumber == 0) { numberArrayOne[0] = numberArrayOne[0] + 1; } if (chosenNumber == 1) { numberArrayOne[1] = numberArrayOne[1] + 1; } if (chosenNumber == 2) { numberArrayOne[2] = numberArrayOne[2] + 1; } } return window.alert(numberArrayOne.join(',')); } } testWrapper(); Thanks. I currently have a navigation bar with CSS. It sits by itself in a frame so it doesn't change with the other page turns. So I'm trying to figure out how to set each link class="active" since it always stays on the same page. I'm thinking javascript will be my friend. Is there an onclick function that can be defined? I'm not new to webpages but new to learning javascript, instead of borrow someone's code. I didn't know how to approach this code because I think I need it to say: If Onclick, then set to class="active", otherwise (then), set class="nothing" or anything to this regard. I was not sure how I could approach that code and how to fit into the UL/LI html code I currently have setup as well as the head code. Example code: (I have 3 frames called head, form, and body. Head is the nav bar where this code sits.) Code: <ul class="menu"> <li><a href="choose.htm" class="active"><span>Home</span></a></li> <li><a href="search.htm" target="form" onClick="top.body.location='http://www.google.com';"><Span> Google</span></a></li></ul> With my CSS code, the "menu" defines some colors/setup, as so does Span and class="active". As a bonus, if you could teach me instead of just help me, it would help me help others. I hope you will forgive the ineptitude of this question, but I'm starting from a severely beginner's level! In my website, I want each button clicked on the home page to define a variable URL that determines which 'default' page is navigated to first when people visit the Gallery section. i.e. If the "About Racing" link is clicked, then when the Gallery section fires up, the first page/picture seen is the Racing Car pic page. I am sure this is possible, but haven't managed to work out quite how to do it.... Any help will be very gratefully received! Hi all, I am working with the following code: Code: window.onload = (window.onload) ? window.onload : function () { for (var i = 0; i < onload_functions.length; i++) { eval(onload_functions[i]); } } ...and it's used like this: onload_functions.push('runSomeJS()'); The idea is that IF the "window.onload" function doesn't exist, I supply my own. My problem is that this code also uses an array: var onload_functions = new Array(); Now this array will not be present if the "window.onload" function is not present. So I need to also define it conditionally. I tried this: onload_functions = (onload_functions) ? onload_functions : new Array(); ...but it doesn't work. I also tried: onload_functions = (onload_functions) ? onload_functions : onload_functions = new Array(); ...doesn't work either. I'm sure the solution is simple, but I'm just not seeing it. Any ideas? Thanks! -- Roger Hi, I'm using ColdFusion to handle the login function for users (see login_form.cfm below). Have to click in the username box to be able to start typing. What's the best way to define the focus to be on the username when the page initially loads? Thanks <form method="post"> Username: <input type="Text" name="username"><br> Password: <input type="Password" name="password"><br> <input type="Submit" value="Login" name="login"> </form> Hello. Using the Firebug console is there a way to log the content of the global namespace? I particularly want to recognise when something is added to it by my code. I could step through my whole code but I'm hoping there is an easier way. Andy. Hello, I am trying to make an example that will change when a user selects options. Like: This is some text. <user checks box to remove "some"> This is text. <user checks box to remove "text"> This is. <user UN-checks box to remove "text"> This is text. The problem is, if I try to add the removed text back, I get the original string, even though it was previously changed. I use to have the string between the <p> tags, but then moved it as a global var in the JS file. Code: /* HTML Code */ <body> <input type="checkbox" id="anoption" /> <p id="exampletext"></p> //Text use to be here </body> /* Javascript code(including jquery) */ var example = "This is some text"; //Global in JS file $('document').ready(function(){ $('#exampletext').text(example); //Place the global var in the html }); $('#anoption').click(function() { //Place a click handler for checkbox var tmp = example; if(tmp.search(/some/)) //Attempting to check if the word is there, i don't think this works right { example = tmp.replace("some", ""); } else // if word is not there - add it back { /* Here is where I could also use some logic help. I tried a few things here. */ } I am not sure if using a string is the best way or not. Could anyone please point me in the right direction? Thank you! |