JavaScript - Running A Function Within A Function
How can I run function neutral() within function front()?
Code: <SCRIPT type="text/javascript"> function neutral() { document.getElementById("front").style.color = "silver"; document.getElementById("front").style.cursor = "pointer"; document.getElementById("back").style.color = "silver"; document.getElementById("back").style.cursor = "pointer"; } function front() { / WILL RUN HERE document.getElementById("front").style.color = "rgb(255,215,0)"; document.getElementById("front").style.cursor = "text"; } </SCRIPT> Similar TutorialsI have changed my event listener around a bit. Basically the "compare_fields" function is running when the "load_doc" function is run. Here is my JavaScript: PHP Code: function load_doc(doc, parent) { document.getElementById(parent).innerHTML = "<h1>Loading...</h1>"; var http = getHTTPObject(); if (http != undefined) { http.onreadystatechange = function() { req_doc(doc, parent, http); }; http.open("GET", doc, true); http.send(""); } } function req_doc(doc, parent, req) { if (req.readyState == 4) {//only if req is loaded if (req.status == 200) {//And if its okay document.getElementById(parent).innerHTML = req.responseText; add_event_listeners(page) } else { document.getElementById(parent).innerHTML = "Error fetching data: " + req.status + "\n" + req.statusText; add_event_listeners(); } } } //Script used to hide elements. Usage: expand(element id) function expand(elm) { var ex = document.getElementById(elm).style.display; if (ex == "none") { var obj = document.getElementById(elm); obj.style.display = "inline"; } else if (ex == "inline") { var obj = document.getElementById(elm); obj.style.display = "none"; } } function check_database(obj) { //Not written yet } //Function to test the password validation, should rewrite in future //to make it multifunctional function compare_fields(obj) { alert("com"); var field2 = obj.split("_"); field2 = document.getElementById(field2[1]+"2"); if (obj == field2) { if (obj.length >= 4) { document.getElementById("pass_status").style.color = "#00CC00"; document.getElementById("pass_status").innerHTML = "OK!"; } else { document.getElementById("pass_status").innerHTML = "Please must be between 5 - 14 characters long! "; document.getElementById("pass_status").style.color = "#FF0000"; } } else { document.getElementById("pass_status").innerHTML = "Passwords do not match!"; document.getElementById("pass_status").style.color = "#FF0000"; } } Global JavaScript: PHP Code: //Get httpobject function getHTTPObject() { var http = false; if (window.XMLHttpRequest) { http = new XMLHttpRequest(); } else if (window.ActiveXObject) { http = new ActiveXObject("Microsoft.XMLHTTP"); } return http; } //This function attaches events to elements. var addEvent = function( elm, evt, fun ) { if ( elm.addEventListener ) { elm.addEventListener( evt, fun, false ); } else if ( elm.attachEvent ) { elm.attachEvent( 'on' + evt, fun ); } else { elm [ 'on' + evt ] = fun; } }; Here is the first form, this contains the button: Code: <div style="border-color:#09C; border-width:1px; border-style:solid;"> <div class="register_button" onClick="load_doc('pages/forms/register_form.php', 'login_form')">Register</div> <h1>Login</h1> <h3>DrawSomething - WordGuesser</h3> <br /> <form id="login" action="php/check_login.php" method="post"> Username<br /><input type="text" name="username" class="text login_field"><br /> Password<br /><input type="password" name="password" class="text login_field"><br /> <input type="submit" value="Login" class="button blue" /> </form> <br /> <h2>Forgot Username/Password?</h2> <span class="expand" onClick="expand('forgot_p')"></span> <form class="forgot_p" action="php/forgot_p.php" method="post" style="display:none;" id="forgot_p"> Email<br /> <h3>Recover username</h3> <input type="text" name="forgot_email" class="text login_field"><br /> <span style=" font-weight:bold; font-size:21px;">- OR -</span><br /> Username<br /> <h3>Recover password</h3> <input type="text" name="forgot_password" class="text login_field"><br /> <input type="submit" value="Recover" class="button" /> </form> </div> Form which is loaded, this is when the "comare_fields" function is run when it shouldn't be. Edit: Oh and here is the PHP script which creates the event listeners. PHP Code: include "js/common.js"; include $js[$page]; //Write JS variables for event listeners $page_listeners = $listeners[$page]; //Check if there are some event listeners for this page if (count($page_listeners) > 0) { ///Start function echo "function add_event_listeners() { "; //Start loop to add event listeners for ($i = 0; $i < count($page_listeners); $i++) { $doc_elm = "document.getElementById('".$page_listeners[$i][1]."')"; echo "addEvent(\"document.getElementById('".$page_listeners[$i][0]."')\", \"".$page_listeners[$i][1]."\", ".$page_listeners[$i][2].");"."\n"; } //End function echo "}"; } Code that is written with the above PHP Code: function add_event_listeners() { addEvent("document.getElementById('reg_username')", "click", check_database); addEvent("document.getElementById('reg_email')", "click", check_database); addEvent("document.getElementById('reg_password')", "click", compare_fields('reg_password')); } And here are global PHP variables: PHP Code: <?php //Define page titles $titles = array( "login" => "Login - DrawSomething", "main" => "DrawSomething - Word Guesser", "admin" => "Administrator" ); //Require JavaScript files when onscreen HTML is selected $js = array( "login" => "js/login_js.js", "main" => "js/main_js.js", "admin" => "js/admin_js.js" ); //Pages to require $pages = array( "login" => "pages/login_page.php", "main" => "pages/main_page.php", "admin" => "pages/admin_page.php" ); //Event listeners to add $listeners = array( "login" => array(array("reg_username", "click", "check_database"), array("reg_email", "click", "check_database"), array("reg_password", "click", "compare_fields('reg_password')") ), ); ?> Hello I am setting up a Javascript function in a page called functions.php function onAddBookmarkPressed() { <? mail("XXXXXXX", "Mail","Bookmark"); ?> } And calling it from another place within the page <div class="barstepimg"><img src="http://staggan.com/my_dir/images/progress_bar/fb_buttons/add_bookmark.gif" onclick="onAddBookmarkPressed();"/></div> I include functions.php in my index.php page... When I run the index.php page the function above runs and emails me... Any idea why? I have an external js file which contains the function which for now opens an alert box. The div on the page should run the function when it is clicked but it isn't. I have tried changing the function to an alert to check the click event is working and i have tried running the javascript in the address bar Code: javascript:hasFocus(); to ensure it has loaded correctly. Both are working fine and i am getting no errors. Below is a snippet of the code: Code: function hasFocus() { alert("a"); } 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"> <head> <script type="text/javascript" language="javascript" src="scripts/cms.js"></script> </head> <body> <div id="tab_panel"> <div id="tabs"></div> <div id="content" contenteditable="true" onclick="hasFocus();"></div> </div> </body> </html> Thanks in advance It would be great if anyone can help me with this list-scrolling animation problem. The animation works fine but I want another action to execute only after the animation finishes. Made several unsuccessful attempts, but here is the basic code. Code: function coreAnimate(obj, elm, begin, end, duration, fps) { if(!duration) duration = 1000; if(!fps) fps = 20; begin = parseFloat(begin); end = parseFloat(end); duration = parseFloat(duration); fps = parseFloat(fps); var change = end-begin; var interval = Math.ceil(1000/fps); var totalframes = Math.ceil(duration/interval); var step = change/totalframes; for(i = 1 ;i <= totalframes; i++) { (function() { var frame=i; function inner() { var increase = linearTween(frame, begin, change, totalframes); unit = 'px'; obj.style[elm] = increase+unit; }; timer = setTimeout(inner,interval*frame); }) (); }; }; function linearTween(t, b, c, d) { return c*t/d + b; }; Thanks, Chris Is it possible to set onmouseover only in js file without running the function on html code? P.S. I found a coding thread here but I don't understand it and it's too old (2005 archive). Thank you very much Hi, I am facing a problem in passing replace() function as an argument in user defined java function, can any one help me how to resolve it? intention is to pass a file path to my user defined function, but before passing the path i want to replace the character '\' to '\\' I am posting my javascript function he <a href="#" onclick="OpenDocPreview('<%# Eval("PATH")%>'.replace(/\\/g,"\\\\"), '<%# Eval("Filename")%>')"><%# Eval("DocTitle") %></a> function OpenDocPreview(url, docname) { alert('message from search base : ' + url + ' ' + docname); } thank you, I was working on a tutorial for some ajax uploading stuff and I ran across a new function syntax I don't recognize. I am not a Javascript pro, but I am not a newbie either. here is the code I am working on: Code: function handleFileSelect(e){ var files = e.target.files; var output = []; for(var i=0,f;f=files[i];i++){ if(f.type.match('image.*')){ var reader = new FileReader(); reader.onload = (function(theFile){ return function(e){ var span = document.createElement('span'); span.innerHTML = ['<img class="thumb" src="',e.target.result,'" title="',theFile.nbame,'" />'].join(''); document.getElementById('list').insertBefore(span,null); }; })(f); reader.readAsDataURL(f); } } document.getElementById('list').innerHTML = '<ul>'+output.join('')+'</ul>'; } document.getElementById('files').addEventListener('change',handleFileSelect,false); To be a little more clear, the code in question is that is the very middle. The syntax I don't understand is: Code: class.event = (function(arguments){ //stuff you put in a function... })(more Arguments?); I tried to customize a simple one to learn for myself and I wrote this: Code: var a = 'A'; var b = 'B'; test = (function(t){ alert(t); alert(b); })(b); test(a); The browser would alert 'B' and that's it. The console would tell me that 'test is not a function.' OK, so I am confused. The topmost code works. What I am wondering is what the syntax is called for creating a function (or event listener?) that way, and how it works. Although if I new what it was called I could just google how it works. Hi! I'm trying to toggle a class and one works and the other does not and I don't know why. I'm just getting my feet wet with jquery and javascript and I figured this was a pretty easy task to take on! Maybe. Link to the page: Franklin Township Soccer Club - Change Field Status My sad, sorry attempt =| Code: $( "li.open" ).click(function() { $( this ).toggleClass( "closed" ); }); $( "li.closed" ).click(function() { $( this ).toggleClass( "open" ); }); The first function works with open, so I figured I'd just use opposite on closed! Ha! I don't think so! In the end within those function there is an element in a form on that page it's hidden. I'd like to change the value from a 0 to 1 for vice versa. That' will be my next step. If you could give me a little nudge in the right direction I'd appreciate it! But first understanding why one works and the other does not, that is the primary mission! I do appreciate any help given! Dave Hi All, I'm trying to convert an anonymous function to a real function (nesting is getting out of hand), however the msg object becomes undefined after conversion. Here is the converted anonymous function which fails: https://gist.github.com/2587613 and here is the original anonymous function which works: https://gist.github.com/2587667 Any help would be greatly appriciated 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 <p> <script type="text/javascript">// <![CDATA[ var metrics = { "mm" : 1, "cm" : 10, "m" : 1000, "inch" : 25.4, "foot" : 304.8 }; function convert(num, dec){ var val = document.getElementById("fromVal").value; if(isNaN(val)){ return } function roundNumber(num, dec) { var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec); return result; } document.getElementById("toVal").value = val * metrics[document.getElementById("fromSystem").value]/ metrics[document.getElementById("toSystem").value]; } var interval = null; function watchChanges(){ interval == null ? setInterval("convert()", 500) : clearInterval(interval); } // ]]></script> </p> <table> <tbody> <tr> <td><input id="fromVal" style="width: 100px;" onfocus="watchChanges()" onblur="watchChanges()" type="text" /><select id="fromSystem" onchange="convert()"> <option value="mm">millimeters</option> <option selected="selected" value="cm">centimeters</option> <option value="m">meters</option> <option value="foot">feet</option> <option value="inch">inches</option> </select></td> </tr> <tr> <td colspan="1" align="center">=</td> </tr> <tr> <td><input id="toVal" style="width: 100px;" type="text" disabled="disabled" /><select id="toSystem" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option value="m">meters</option> <option selected="selected" value="foot">feet</option> <option value="inch">inches</option> </select></td> i keep getting error Call to undefined function codeandurl() below is my code PHP Code: <?php $value= strip_tags(get_field('link',$post)); $resultid=get_field('resultid',$post); codeandurl($resultid,$value); ?> <div id="result"></div> <script type="text/javascript"> function codeandurl(resultid,url){ $( "#result" ).text(resultid); $( "#result" ).dialog({ modal: true, buttons: { Ok: function() { $( this ).dialog( "close" ); } } }); window.open(url); return false; } </script> 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 I'm trying to "progressively enhance" one of my surveys using javascript. Basically, I have rating scales that make use of radio buttons as each point on the scale. Each radio button occupies its own cell in a table. I wrote some functions that will highlight cells on mouseover in a color corresponding to its position on the scale (e.g. the lowest point is red, the midpoint is yellow, the highest point is green). When a radio button is clicked, the background of the button's cell and preceding cells in the same row will be colored accordingly. The functions are working well in FireFox and Chrome (I just have to add a few lines using the addEvent function to make it compatible with IE). The effect looks a lot nicer when I add a function that makes the visibility of the radio buttons hidden. However, I want to make sure that there is a fallback option in case the functions that color the cells don't work for whatever reason. I would not want the radio buttons hidden in this case. Is there a method whereby I can call the "hideRadiobuttons" function only if the other functions are successfully executed? How can I call a PHP Function inside a Javascript Function? This is what I have so far, but I don't think I'm doing it the right way. Any suggestions? PHP Code: <?php function phpQuery(){ $query = mysql_query("INSERT INTO mytable VALUES('','name','email')"); } ?> <script type="text/javascript"> function delayQueries() { timeoutID = window.setTimeout(doQueries, 2000); } function doQueries() { var runQuery = "<?php phpQuery(); ?>"; } </script> 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. Code: <html> <head> <title>TESTING</title> <script type="text/javascript"> <!-- document.write("<input type='submit' value='submit' onclick='func()'>"); function func() { document.write("<input type='submit' value='New Button' onclick='func()'>"); window.alert("THIS"); } --> </script> </head> <body> <!--input type="button" value="Read" onclick="ReadFiles()"--> </body> </html> This is a very basic version of what I am trying to do. I have a dynamic list which is set in a table. When clicked, a function is run to set up a new list.. The reason I explain that, is that I need to keep it dynamic. Now for the problem: When I run this page, I have the button made right away, then when clicked it creates the new button. The new button should also run the function to create the new button again, but when I click it, I only receive "error on page". I don't know if there is a better way to go about this, but as for this route, I am stuck. Any help is greatly appreciated! -Shane Hi, Any one help me In one variable i have some data ex: var data = document.getElementById("imageId").value; I want to pass this data to another function inside another function ex: var button1 = '<img src="images/Remove-button.gif" width="70" height="15" onclick="removeVerifyImageRow(this),saveLibData('+data+')"/>'; while running the application i am getting an error incase if the data is string ex:if data is 'image1' i am getting an error, but with number there is no problem ex: if data is '1122'. this is very urgent to solve this problem plz any one help me Hello all. I have fairly simple questions regarding modifying this script: http://papermashup.com/create-a-dynamic-form-preview/ to dynamically show different parts of a form on another part of the page. I am looking to use it on most parts of my form and would like a little clarification. First is the use of $(document).ready(function() or $(function(). It works using either, my question is which is preferred? As I understand it using $(document).ready(function() starts the DOM immediately on page load and is useful if you need something right away. I am also using this script: http://www.dynamicdrive.com/dynamici...formwizard.htm for the form. Since the preview script is being used with the form to wizard, I don't really need it until the rest of the form loads. Another question would be, is there a cleaner way to go about using the preview script on say 10 different form inputs independently? For example in a single function rather than 10 different function/updates? I have an example of what I am trying he http://jsfiddle.net/anhyG/1/ Thank you in advance for any help! Hi everyone, I am pretty new at javascript OOP. I have a javascript file that has plenty of javascript functions, variables, arrays, etc. I need to convert this into an object. Here is an example: Code: var myvar1 = ''; var myvar2 = new array(); var myvar3 = new array(); var myvar4; var myvar5 = 60; var myvar6 = ''; function myfunc1(){ myvar1 = 'hello'; return myvar1; } function myfunc2(somenum=0){ myvar5 = somenum; //calling myfunc1() from within this function. //do something in here } function myfunc3(){ //calling myfunc1() from within this function. for(i=0;i<somelength;i++){ myvar2 = myvar3[i]; (something to put into the array) } } 1. I need to create an object and put ALL the varibles (myvar1 - myvar5) in that object. 2. Then the first two functions "myfunc1 and myfunc2" inside the same object. 2. And the function myfunc3 needs to sit OUTSIDE my object as a regular javascript function. It calls on myfunc1 (which is inside the object) and also inserts data into myvar2 (which is classified inside the object) and myvar3 (which is classified inside the object as well). This is what i came up with, but it's not going well: Code: var myobj1 = function(){ this.myvar1 = ''; this.myvar2 = new array(); this.myvar3 = new array(); this.myvar4; this.myvar5 = 60; this.myvar6 = ''; var myfunc1 = function(){ this.myvar1 = 'hello'; return this.myvar1; } var myfunc2 = function(somenum=0;){ this.myvar5 = somenum; //calling this.myfunc1() from within this function. //do something in here } } function myfunc3(){ //calling mynewobj.myfunc1() from within this function. for(i=0;i<somelength;i++){ mynewobj.myvar2 = mynewobj.myvar3[i]; (something to put into the array) } } var mynewobj = myobj1; HELP.....!!!! i really want to get into object oriented world, so thanks in advance. |