JavaScript - Make A Variable Available To Other Functions Outside A Function
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?? Similar TutorialsHi! I'm as new as they come when it deals with website development but forums have been useful to me in the past and I'm hoping I can get some kind of direction from all the wonderful people on this forum! I have an idea for a website that I'd like to pursue, and it would need functions such as: -Live news feed -Member logins, profiles, ability to rate/leave feedback for members -Mobile phone friendly -Comment on postings -Create an intro video (maybe even with animated stick figures to explain how the site works) -Accept paypal or other payment method -And basically, need to understand the monthly maintenance cost of all these functions, how to minimize expenses, etc. I know it seems far fetched for a newbie! But I need to know if this is possible.. how would I begin implementing a site like this.. Do I need to find a programmer to code it from scratch? Are there pre-written scripts available for all the functions I listed? What can I expect the costs to be? What's the best way to move forward? I am working on a site and in the process borrowed some js from some one to get dropdown menus to work, but after a while got reports from people who tested my site of some problems and decided to verify all my code, and i have fixed most bugs but the one listed in the title. Code: sfHover = function() { var sfEls = document.getElementById("nav").getElementsByTagName("LI"); for (var i=0; i<sfEls.length; i++) { sfEls[i].onmouseover=function() { this.className+=" sfhover"; }; sfEls[i].onmouseout=function() { this.className=this.className.replace(new RegExp(" sfhover\\b"), ""); }; } }; if (window.attachEvent) {window.attachEvent("onload", sfHover);} and i am verifying it on jslint the error i get is: Quote: Error: Problem at line 6 character 10: Don't make functions within a loop. }; Problem at line 9 character 10: Don't make functions within a loop. }; Implied global: sfHover 1,12, document 2, window 12 any help will be appreciated, and I'm sure this isn't complex but i don't know much js and want to keep it the same. 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, 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 Note: major noobage here I'm sure... but can't seem to figure this out... How do I make these three functions into one script? Much love if you can help! Code: <script type="text/javascript"> setTimeout('yourFunction();', 2500); function yourFunction(){ document.getElementById('hide').style.display='block'; } </script> <script type="text/javascript"> setTimeout('yourFunction2();', 8000); function yourFunction2(){ document.getElementById('hide').style.position='fixed'; } </script> <script type="text/javascript"> setTimeout('yourFunction3();', 8500); function yourFunction3(){ document.getElementById('hide').style.margin='0 -310px'; } </script> <script type="text/javascript"> setTimeout('yourFunction4();', 15500); function yourFunction4(){ document.getElementById('hide').style.margin='0 610px'; } </script> Hi everyone, i thought about following code snippet: Code: var newfunc = function() { //... } func = (function (oldfunc,newfunc) { return function () { oldfunc(); newfunc(); } }(func || function(){},newfunc)) There is a function "func" and with the above method i want to add a new function "newfunc" to this function, so when i call "func" in the futur, both functions will be executed. It works good, but suppose i want to add multiple functions to func, each time with the described method...could there be a problem with the stack? As far as i understand, the program creates something like a wrapper-function each time, that contains the two functions it combines. So in the case of adding 3 functions, a call of "func" would lead to this: call "wrapper 2", call "wrapper 1", call func1, call func2, call func3, call func 4. The really poor graphic should illustrate what i mean __________ F1|....|....| __|W1|....| F2|....|....| __|___|W2| ...|F3 |....| ...|___|___| ..........| F4| ..........|___| Has anyone an idea, if my thoughts on that are correct oder if this behaviour could be a problem? And is there probably a better way to combine functions, so that all functions would be in one column? Thanks and Greetings! moon-safari Hi, I would like to do something like this: Code: function searchLocations(count) { var found = false; var input = document.getElementById('autocomplete').value; var inp = input.toLowerCase(); var count = 0; for (var j = 0; j < gmarkers.length; j++) { gmarkers[j].hide(); var str=gmarkers[j].myname.toLowerCase(); var patt1=inp; if (str.match(patt1)) { found = true; gmarkers[j].show(); count++; } } if (count==1) myclick(j); if (count>1) centerZoom(); if ( ! found ) alert("No matches found. Please check your spelling or refine your search."); } on this page here, but the functions - myclick(j); and centerZoom(); aren't getting called. I tried it with switches here, but that only made things worse. I know the functions work because if I put them two } up, they get called, but that takes them out of the if statements. Those if (count...) statements have to be where they are so that "count" will get the right value. Any ideas? I found this script, and it works great: Code: <script type="text/javascript"> function disable(element) { var input = document.getElementById(element).getElementsByTagName("input"); for(var i = 0; i < input.length; i++) { input[i].setAttribute("disabled","true"); } } </script> I tried to make the inverse by simply reversing the setAttribute() like so: Code: <script type="text/javascript"> function enable(element) { var input = document.getElementById(element).getElementsByTagName("input"); for(var i = 0; i < input.length; i++) { input[i].setAttribute("disabled","false"); } } </script> But that didn't do it. Can someone show me why, and how to fix it? Here's the sample form which I'm trying to test it on: Code: <form> <input type="radio" name="test" onclick="disable('D1')" /> disable<br/> <input type="radio" name="test" onclick="enable('D1')" /> enable<br/> <fieldset id="D1"> <input class="" type="text" value="test value1" /><input class="" type="text" value="test value2" /><br/> <input class="" type="text" value="test value3" /><input class="" type="text" value="test value4" /><br/> <input class="" type="text" value="test value5" /><input class="" type="text" value="test value6" /><br/> </fieldset> </form> Edit: The ultimate goal which I'm working toward now (step by step =) is to have a form more like: Code: <form> <input type="radio" name="test" onclick="disable('D1')" /> <fieldset id="D1"> <input class="" type="text" value="test value1" /><input class="" type="text" value="test value2" /> </fieldset> <input type="radio" name="test" onclick="disable('D2')" /> <fieldset id="D2"> <input class="" type="text" value="test value3" /><input class="" type="text" value="test value4" /> </fieldset> <input type="radio" name="test" onclick="disable('D3')" /> <fieldset id="D3"> <input class="" type="text" value="test value5" /><input class="" type="text" value="test value6" /> </fieldset> </form> And have the fieldsets enable and disable according the selection of the radio buttons. Also, the fieldsets (and their ID's) will be dynamically generated via PHP Thanks-a-bunch, ~ Mo I made a mouseover event of a caption on a picture, when I hover the opacity of the background color of the hover and the text goes down. What I want is that when I hover over the image which the caption is floating on, the onmouseover event gets activite. For an imaginary example: Code: function unhighlight(x) { x.style.backgroundColor="transparent" } Function ActivationFuction() { activate.function="unhighlight" } thanks Hello, Our website is built in ASP.NET and uses a content management system. The CMS came with a wealth of JavaScript files and I decided to use one of these files for form validation. Although the file is over 2,300 lines, from what I can tell it is supposed to return true if the form is valid and false otherwise. The problem is that a function inside that file seems to get to a certain point, and somehow quit and return true no matter if the form is valid or not. I am calling this JS from an ASP.NET button control. When the button is clicked, a JS function ValidateForm(document.forms[0]) is called. My ValidateForm function calls another function inside the JS file (which calls another, and another...). No matter what, when that second function is called and executed, code execution stops at some point and the form submits (postbacks). I can see that the validation is working just before the postback, but it is not preventing the form from being submitted, and it also stops executing any code after it. Here is my code: ASP: Code: <asp:Button ID="SubmitBtn" runat="server" Text="Submit Form" CausesValidation="false" CssClass="submit_button" OnClientClick="FmValidate(document.forms[0]); return false;" OnClick="SubmitBtn_Click" /> My Javascript: Code: function FmValidate(formObj) { var strError = ''; var e = null; if (strError == '' && 'function' == typeof design_validateHtmlForm) { alert('before'); // this line causes execution to stop - located in external JS file // code states "Returns first invalid element, or null." e = design_validateHtmlForm(formObj); alert("e is " + e); if (e) { strError = e.title; } return false; } } In my ASP.NET button, changing the OnClientClick method to "return false" will prevent form submission, but "return FmValidate(formObj);" will not if that function calls design_validateHtmlForm(formObj). I receive the message box saying "before" but I never receive the second one. I have debugged using Fire bug, but the code seems to cycle through each element on the page and stepping through the code is not realistic (I have done so for 20-minute stretches). I am wondering if anyone has any ideas what code I could look for that would stop execution and return true no matter what, or how I could begin debugging this monster. I don't know how I should do ? Quote: <html> <head> <script type="text/javascript"> function add(a,b){ y=a+b return y } var aaa = add(one,two) //one needs to get somehow get the value of yil, in this case 10 var one = function reas(){i=10;if(i<10){yil = 15}; else{yil = 10; yil = one;}; var two = 20; document.write(y) </script> </head> </html> also why doesn't this work? Quote: <html> <head> <script type="text/javascript"> function adder(a,b){ var k=a+b; return k } var hes=adder(5,kol); kol=40; alert(hes); </script> </head> </html> you cannot have variables in callback functions? Hey all, I am confused about the true difference between the two below examples. Code: first example: // Demonstrating a problem with closures and loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array(); // Loop through myArray and create a closure for each that outputs that item for (var i = 0; i < myArray.length; i++) { var theItem = myArray[i]; closureArray[i] = function() { document.write(theItem + “ < br / > ”); } } // Loop through the closures and execute each one. for (var i = 0; i < closureArray.length; i++) { closureArray[i](); } Here we iterate through the length of myArray, assigning the current index of myArray to theItem variable. We declare closureArray 4 times as an anonymous function. The anonymous function in turn declares the predefined write() function, which is passed parameters. Since write() is in closureArray() a closure is created??? During each iteration, theItem is reassigned its value. The four closures reference this value. Since they reference this same value and since this value is reassigned ultimately to the value of the fourth index position, tHe time we execute closureArray later on, all four closures output the same string. This is because all four closures are within the same scope "the same environment" and therefore are referencing the same local variable, which has changed. I have a couple of problems with this example: 1) I thought a closure is a function that is returned - the inner function is not returned above. 2) theItem is not even a local variable of the parent function (closureArray) - I thought in order for a closure to work, the inner function only accesses the local variables of the outer function, but in this case the local variable is defined OUTSIDE of the parent function. 3) The guy says the "the four closures are sharing the same environment." The thing is even in the second example, they are sharing the same environment. Second example: Code: // A correct use of closures within loops var myArray = [“Apple”, “Car”, “Tree”, “Castle”]; var closureArray = new Array(); function writeItem(word) { return function() { document.write(word + “ < br / > ”); } } // Loop through myArray and create a closure for each that outputs that item for (var i = 0; i < myArray.length; i++) { var theItem = myArray[i]; closureArray[i] = writeItem(theItem); } // Loop through the closures and execute each one. for (var i = 0; i < closureArray.length; i++) { closureArray[i](); } Here we iterate over the length of myArray (4 times), assigning the index of myArray to theItem variable. We also return a function reference to the closureArray during each iteration (closureArray[i]), where i is index number so we assign 4 functon references. So when we iterate through myArray, we immediatelly call the writeItem() fucntion passing an argument of theItem at its current value. This returns a child anonymous function and when that child function is called, it will execute a block that calls the predefined write() method. We assign that returned anonymous function to the variable closureArray. Hence, closureArray holds a reference to that anonymous function. So closureArray during each iteration holds a reference to the anonymous function and we later call closureArray, which in turn calls the anonymous function, therefore calling the predefined write() function to output the local variable of the parent function. This outputs each distinct index of myArray. QUESTION: This is because since we created the closure, when we call writeItem, passing theItem argument, since theItem is a local variable of the parent function of the closure, it is never destroyed when we later call closureArray (the reference to the child anonymous function)? Yet weren't we using a closure in the first example as well? So whey wasn't those variables preserved? I don't think it has anything to do with assigning a returned anonymous function to closureArray. Even though an anonymous function creates a new memory position in the javascript engine, therefore not overwriting the other function references we create during the iteration, it's still referring to a local variable declared outside the reference. So if it's about the closure retaining value of parent's local variable even after exiting the parent function allowing for the current indexes to be preserved, then why did the closure in the first example fail to retain each index? Thanks for response Thank you in advance if someone can help. I have been banging my head against the wall for hours now. Here is the code: Code: for (var i = 0; i < BS_crm['activityTypes'].length; i++) { var clickFunc = function(){ activityList.showForm( -1, {blockType:[""+BS_crm['activityTypes'][i]['id'], "0"]} ); }; var type = { value: BS_crm['activityTypes'][i]['id'], label: "Add New "+BS_crm['activityTypes'][i]['label'], css: BS_crm['activityTypes'][i]['css']+"_16", onClick: clickFunc }; previewLinks.items.push( type ); } Now, basically what I am doing here is running through one array to create an array of objects, that will be used to create links that will use whatever onClick function I pass it. The problem is that on the second line I need the BS_crm['activityTypes'][i]['id'] to be a value, not a reference. If that line was simply changed to: Code: var clickFunc = function(){ activityList.showForm( -1, {blockType:["3", "0"]} ); }; then everything would work as I need. How can I make this happen? I would really appreciate any help. Thank you again in advance. i am new to javascript and i can't seem to make it work for me to make a script that gets the current time on the browser and leaves a message for a certain time I can make 3 max variables by doing if, else if, else i need 4 variables so that i can make a background for the certain times for the current day time (morning, evening, afternoon, night) Thank you for listening (and/or helping me out) I've just discovered (through trial and error) that if a variable is assigned a value without first being declared, it automatically has global scope, even if it is assigned inside a function. This is a pain in the butt because if you forget the var keyword, then suddenly ... whoops! You've got yourself a global variable! Is there any way that I can make javascript throw an exception if I fail to declare a variable before assigning a value to it? It would make things much easier, rather than having to hunt through increasingly complex functions to find that pesky unintentionally global variable. i need to make a function that will send a string to my perl script then recieve the answer and set a div innerhtml to the answer.. i plan on sending the string from the div onload as i will have about 30 divs that need changing. Code: <body> <div name="example1" onload="javascript:retrieve('getstring1')">my retieved string1</div> <div name="example2" onload="javascript:retrieve('getstring2')">my retieved string2</div> </body> <head> <SCRIPT language="JavaScript"> function retieve('var') { } </SCRIPT> </head> im not quite sure where to go with this but i can easily make the perl script do if statements on the string and return the correct string to put into the div. the reason for this is that the string will be changed every couple weeks. there is probably a better way to do this but this would be more appropriate for me I am trying to display some images in, say, 500ms intervals, but I want to loop through images, so I use a for loop and setTimeouts and function calls... Code: for (i=0;i<=5;i++) { setTimeout(DisplayTheImage, 500); } (a var that increments the image like image[x] is somewhere else) but I think all I accomplish is that while the above code calls the function 5 times alright, all five function calls occur simultaneously. Right? Eh, I want the function to be called 5 times, but at five different times, namely in 500ms intervals. I thought the function would wait to finish (500 ms) then another call and so on. How can I do that? Hi, I have a function that I'm trying to modify. It adds an element to the page. The problem is, I require that ClickGeocode() finishes executing before the rest of the code in the function completes. Currently that is not the case... Any ideas? Code: Event.add(window, 'load', function() { Event.add('addressSearch', 'click', function() { ClickGeocode(); var el = document.createElement('p'); el.innerHTML = " " + addressSearchAddress + " : [" + addressSearchRadius + "]"; Dom.add(el, 'AddressesVisited'); Event.add(el, 'click', function(e) { Dom.remove(this); }); }); }); Hi there, Sorry that the title of this is not very descriptive but I really don't know how to describe what it is i am after. I have a variable that contains an image source. (well I hope it does) Code: var imagebackground = (this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).src; Now I need that variable to spit out the image source into where it says background, but wrapped in a url( ) Code: $jQ(document).ready(function(){ $jQ(".btn-cart").click(function(){ $jQ('#floater').animate_from_to('.block-cart', { pixels_per_second: 200, initial_css: { background: (THIS IS WHERE I WANT IT) } }); $jQ(this).attr('id', ''); $jQ(this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).attr('id', ''); }); }); So basically if the variable was to equal - http://www.google.co.uk/image.jpg - it would function like: Code: $jQ(document).ready(function(){ $jQ(".btn-cart").click(function(){ $jQ('#floater').animate_from_to('.block-cart', { pixels_per_second: 200, initial_css: { background: url(http://www.google.co.uk/image.jpg) } }); $jQ(this).attr('id', ''); $jQ(this.parentNode.parentNode.parentNode.childNodes[1].childNodes[0]).attr('id', ''); }); }); I hope I have provided enough information for someone to assist me with this, but if i havent then please tell me and i will try and explain some more. Cheers, Chris |