JavaScript - Function Defined In Global Scope Not Being Called By Settimeout (func Arg As String)
Hey everyone,
I wanted to write my own script for a fade-in animation, since the ones I have found have got too many options or need some framework, which makes them unnecessarily big. I wanted to learn too. Unfortunately, the code didn't work as I wanted, and I commented some things so as to find out what's happening. The only function called from outside is fadeIn with a string as argument (in the example, this string is: d1296668690535). This is the code: Code: var fadems = 500; // Anim. duration in milliseconds var fps = 20; // Frames per second function fadeIn(elemId){ var frames = fadems/1000 * fps; var delay = 1000 / fps; var incrOp = 1 / frames; //document.getElementById(elemId).style.zoom = '1'; setOp(elemId, 0); for(i=1; i<=frames; i++){ debugOutLn("(fadeIn for) elemId = " + elemId); setTimeout("setOp(" + elemId + "," + incrOp*i + ")", delay*i); } } function setOp(elemId, val){ debugOutLn("(setOp) elemId = " + elemId + "; val = " + val); // document.getElementById(elemId).style.opacity = val; // document.getElementById(elemId).style.filter = 'alpha(opacity = ' + val * 100 + ')'; } Code: function debugOutLn(str){ document.getElementById("debug").innerHTML += str + "<br />"; } And this is the text it outputs (on Opera 11.01): Code: (setOp) elemId = d1296668690535; val = 0 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (fadeIn for) elemId = d1296668690535 (setOp) elemId = [object HTMLDivElement] ; val = 0.1 (setOp) elemId = [object HTMLDivElement] ; val = 0.2 (setOp) elemId = [object HTMLDivElement] ; val = 0.30000000000000004 (setOp) elemId = [object HTMLDivElement] ; val = 0.4 (setOp) elemId = [object HTMLDivElement] ; val = 0.5 (setOp) elemId = [object HTMLDivElement] ; val = 0.6000000000000001 (setOp) elemId = [object HTMLDivElement] ; val = 0.7 (setOp) elemId = [object HTMLDivElement] ; val = 0.8 (setOp) elemId = [object HTMLDivElement] ; val = 0.9 (setOp) elemId = [object HTMLDivElement] ; val = 1 Why is an object reference assigned to what was previously a string? Thanks for the help! Similar TutorialsHi, I have a button that when you click it displays the results of my db in a div. What I am trying to do is to get the results to update every five seconds. I thought setTimeout was the best way to achieve this. However I am getting the error message that ID is not defined on the setTimeout line. I thought it would automatically input ID into the fields marked ID when the onloadXMLDocRefresh('File.php','txtHint') button is clicked? The button works to load the script, but the refreshing the div is not. My script is: Code: <script type="text/javascript"> function loadXMLDocRefresh(File,ID){ if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById(ID).innerHTML=xmlhttp.responseText; timer = setTimeout('loadXMLDocRefresh(File,ID)',5000); } } xmlhttp.open("POST",File,true); xmlhttp.send(); } </script> 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, ok so Code: <p> Howdy <p> expressed as a literal string that is passed to the setTimeout() function might look like this: Code: setTimeout("document.getElementById('first').innerHTML = '<p>' + 'HOWDY' + '<\/p>';", 2000); ..so I guess you can't just put quotes around an expression like this: "'<p> HOWDY <\/p>;" So tags have to be isolated, but it get confusing with expressions like this, which I am not sure how to express as a string: Code: <p><h2 class="pos_left"> <img src="car1.jpg" name="slide" width="400" height="250" /> </h2> </p> ^ I wish I could change the " in there to ' and then just wrap the whole thing in double " This is what I came up with but it did not work: Code: setTimeout("document.getElementById('first').innerHTML = '<p>' + '<h2' + 'class='pos_left'' + '>' + '<img' + 'src='car1.jpg'' + 'name='slide'' + 'width='400'' + 'height='250'' + '/>' + '</h2>' + '<\/p>';", 4000); 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> Hello I am just learning, what am I doing wrong here , I'm trying to display an image after 3 seconds after the page opens with js from an external file listed below: Code: <html> <title>Insert Page</title> <body> var call; call=("<?php echo $image1;?>"); function myfunction() { setTimeout =(call, 3000); } document.write(myfunction); </body> </html> Hi all, I'm just starting out with Javascript as a development language and this will probably be a relatively simple problem for someone to solve for me. I am trying to access a variable (this.bodyEl.innerHTML) from within a function but get an error message indicating that it is "undefined". I know that it is a valid variable because I call it elsewhere outside of the inner function itself. I'm sure this is just a scope issue, but I'd welcome any suggestions on how to solve it with an explanation of where I've gone wrong if you have the time. Here's the code: Code: displayFeed: function(responseData) { this.bodyEl.innerHTML = "xxxx"; // I can see this var responseDoc = Presto.Util.parseXml(responseData); var items = Ext.DomQuery.select("/rss/channel/item", responseDoc); items.each(function(item, bodyHTML) { var rssTitle = Ext.DomQuery.selectValue("/title", item); var rssDescription = Ext.DomQuery.selectValue("/description", item); var rssLink = Ext.DomQuery.selectValue("/link", item); // but this results in an undefined error this.bodyEl.innerHTML = '<a href="' + rssLink + '">' + rssTitle + '</a><br/>'; }); // end of items processing } This is a fragment of the code from my script. The first access of "this.bodyEl.innerHTML" works fine, but the second access in the items.each loop doesn't and I get an undefined variable error. Is this a scoping problem, and if so how is it best solved. Thanks in advance, Innes (NZ) Hi all, I have what I hope will be a simple question for someone to help me with. I simply want to add a timeout to the folowing code: Code: $(function(){ $('#slides').slides({ effect: 'fade', crossfade: true, preload: true, preloadImage: '<?php bloginfo('template_directory'); ?>/img/loading.gif', play: 4500, pause: 500, hoverPause: false, animationStart: function(current){ $('.caption').animate({ bottom:-35, },100); if (window.console && console.log) { // example return of current slide number console.log('animationStart on slide: ', current); }; }, animationComplete: function(current){ $('.caption').animate({ bottom:0 },200); if (window.console && console.log) { // example return of current slide number console.log('animationComplete on slide: ', current); }; }, slidesLoaded: function() { $('.caption').animate({ bottom:0 },200); } }); }); As you can see this is a slideshow code. All I want to do is delay the first slide sliding in when the slideshow loads. I have tried wrapping the whole function in a settimeout but to no avail. Thanks in advance Dan (PS: I had no idea what to call this thread so, hopefully it's okay) I'm trying to make a time script for an app I'm making (this is not an HTML document; it's a .js file to be used with Titanium) however I'm having trouble getting the function to display and update. Code: function updateClock() { setInterval ( 'kiTime()', 1000 ); } function kiTime () { //Get current date and time var currentTime = new Date (); //Create variables for hours, minutes, and seconds from current time var currentHours = currentTime.getHours (); var currentMinutes = currentTime.getMinutes (); var currentSeconds = currentTime.getSeconds (); //Add a leading zero to minutes and seconds if less than ten currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes; currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds; //Create the string of time data currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds; return currentTimeString; } var win3 = Titanium.UI.createWindow({ title:'Clock', backgroundColor:'#fff' }); var tab3 = Titanium.UI.createTab({ icon:'clock.png', title:'Clock', window:win3 }); var label3 = Titanium.UI.createLabel({ color:'#999', text:updateClock(), font:{fontSize:20,fontFamily:'Helvetica Neue'}, textAlign:'center', width:'auto' }); win3.add(label3); If I use kiTime() under the text field I will get the current time (or at least the time the app was opened), however if I call updateClock() it's blank. all, does anyone know if the setTimeout() function in js has been just recently supported? i created an online demonstration of a product that uses this function to delay the playing of .wav files after various second intervals. i know that Opera doesn't support this function because when I click my button, all of the .wav files that i have in the function that runs behind the button play at once. i have probably 10 wav files that are played throughout the function, at various conditional statements. does anyone know if earlier (like REALLY old) versions of IE do not support this function? or maybe ie8 doesn't support it? i developed this and tested it in all major browsers except IE8 and any version earlier than IE6. thank you for any help on this... Hi guys, calling a php page through AJAX. and it works Aok. I wanted the ajax backend php file to call a function in the front end page. even a simple alert from the backend php file wont work. Any help is greatly appreciated. My code to call the alert and parent's javascript functions are below. Simple alert Code: echo "<script language='javascript'>alert('Please Help Me');</script>"; Calling Front End Page Function Code: echo "<script language='javascript'>frontend_function();</script>"; Cheers Elabuwa Here is my function: Code: function mod_selection(val1,val2) { if( -1 != navigator.userAgent.indexOf ("MSIE") ) { var range = document.selection.createRange(); var stored_range = range.duplicate(); if(stored_range.length > 0) { stored_range.moveToElementText(textArea); stored_range.setEndPoint('EndToEnd', range); textArea.selectionStart = stored_range.text.length - range.text.length; textArea.selectionEnd = textArea.selectionStart + range.text.length; } alert('hi'); // Get the text area var textArea = $("#text_edit"); textArea.hover(function() {alert('hi');}) // Do we even have a selection? if (typeof(textArea.selectionStart) != "undefined") { // Split the text in three pieces - the selection, and what comes before and after. var begin = textArea.value.substr(0, textArea.selectionStart); var selection = textArea.value.substr(textArea.selectionStart, textArea.selectionEnd - textArea.selectionStart); var end = textArea.value.substr(textArea.selectionEnd); // Insert the tags between the three pieces of text. textArea.value = begin + val1 + selection + val2 + end; } } } Basically what it does is insert BBCode tags for whatever text you have highlighted. Here is my HTML for it: Code: <div class="two-row"> <label>Content: </label> <a href="#" onclick="mod_selection('','');return false;">B</a> <input type="button" value="I" onclick="mod_selection('','')" /> <input type="button" value="U" onclick="mod_selection('','')" /><br /> <textarea id="text_edit" name="body" rows="25" cols="51"><?php if(isset($_POST['submit']) || isset($_POST['preview'])) { echo $_POST['body']; }else { echo $news_body; } ?></textarea> </div> It says the mod_selection is not defined. I'm doing alert('hi'); for testing purposes and it won't print hi.. sooooo I feel like I need a second pair of eyes. I want it to at least recognize the function before I debug it any further. Hi guys my site is not working fireug says that the function 'changevalu()' ia not defined but it is heres my site Code: <!doctype html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html" > <title> portl - beta 0.1 </title> <meta name="description" content="portl Is a file transfer system. "> <meta name="author" content="Techyonomics"> <meta name="viewport" content="width=device-width"> <meta name="keywords" content="portl,techyonomics,school,free,privet,trans,files,ui,cool" > <link rel="stylesheet" href="style.css"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="javascript/text"> function changevalu() { var valueofpress = $(this).text(); var passval = $(#password).val(); $(#password).val(passval + valueofpress); alert(passval + valueofpress); } </script> </head> <body> <header> </header> <div role="main"> <div id="keypad"> <div id="keys"> <div class="key" onmouseup="javascript:changevalu()">1</div> <div class="key">2</div> <div class="key">3</div> </br> </br> </br> <div class="key">4</div> <div class="key">5</div> <div class="key">6</div> </br> </br> </br> <div class="key">7</div> <div class="key">8</div> <div class="key">9</div> </br> </br> </br> <div class="key">C</div> <div class="key">0</div> <div class="key">E</div> </div> <form id="hiddenform" action="login.php" method="post"> <input id="password" type="text" value="" name="pass"></form> </div> </div> <footer> </footer> </body> </html> JavaScript: Code: function test() { alert('dsd'); } HTML: Code: <a href="#" onClick="test()">Test Link</a> JS Error: Code: Error ``ReferenceError: test is not defined'' [x-] in file ``file:///C:/Users/Martyn%20Ball/Desktop/test.php#'', line 1, character 0. Okay wtf. Ok, I have an event handler for a click - ala: using prototype and here is a snippet. Code: spotL = some_length_of_an_array; $R(1,spotL).each(function(n) { $('spot_btn_' + n).style.display = 'block'; $('spot_btn_' + n).observe("click", function(){countdwn_clear();} ); }); Now, that code above fires off AFTER I call an init function that just runs thru some things... But not only that, that function "countdwn_clear()" loads before I call the code above... so its there. Now, the "element" I am trying to attach that event handler in an anchor tag in a UL element ala. Code: <ul id="buttons" style="display: none;"> <li id="spot_btn_1" class="selected"><a href="javascript://" id="btn1">1</a></li> <li id="spot_btn_2"><a href="javascript://" id="btn2">2</a></li> </ul> so, I originally thought it that I was trying to attach an event handler to an element in another that had a display of none -- so I switched it to block and I'd still get this error: countdwn_clear is not defined NOW -- if put this right below the function call, ala: Code: function countdwn_clear(){d_some_code_here} $$("#buttons li")[0].observe("click", function(){countdwn_clear();} ); $$("#buttons li")[1].observe("click", function(){countdwn_clear();} ); ^^^^ that works! why? In one case, i am calling it right below the function and I am using a different reference: $$("#buttons li")[1] in the code where I "build" it, I have: $('spot_btn_' + n).observe("click", function(){countdwn_clear();} ); ???? could it be the event is on the "li" instead of the "a" or ? I don't get it. Any ideas? Hi friends, I am trying to use the window.setTimeout feature so that a message pop-up with yes/no appears on the screen asking whether to extend the session. The actual sessions expires on 5 seconds. *If yes is clicked, the current page reloads. *If no is clicked, nothing happens. (the session will expire anyway). Many pages is open fastest, but other delays several seconds or minutes! Quote: var w = 800; var width = 800; var h = 800; var height = 800; var left =(screen.width/2)-(w/2); var top = (screen.height/2)-(h/2); window.open ("","myNewWin", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left); var a = window.setTimeout("document.form1.submit();",5000); Letchev Hello everybody I need your help in this problem At first, this is the code used HTML Code PHP Code: <input type="text" onfocus="fadeIn(this)" /><div class="box" style="opacity: 0.0"></div><br /> <input type="text" onfocus="fadeIn(this)" /><div class="box" style="opacity: 0.0"></div> JavaScript Code PHP Code: function fadeIn(elem){ element = elem.nextSibling; elemOpacity = element.style.opacity; element.innerHTML = elemOpacity; if (elemOpacity < 1.0) element.style.opacity = parseFloat(elemOpacity) + 0.1; timeIn = setTimeout(fadeIn, 100); } I have used the opacity property to make fading element like fadeIn() function in jquery , and i have used onfocus event to execute the code . Problem exists in setTimeout function, this function Does not work But the code works without this function What is the cause of the problem , Please help me 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? I've read through the past threads and did not find anything that quite matched my problem, which surprises me because I thought it would be fairly common. Anyway, I have a script where I define an array and populate the array. In the same script is a function that tries to scan the table looking for a match with the value in a global primitive. In the HTML, a button click invokes the function. But while the function can correctly access the global primitive, it simply stops running when it encounters the reference to the global array. Here's a shortened, simplified snippet of the code: [code] <script type="text/javascript"> var len = 2; var course_code = new Array(); course_code[0] = "A010"; course_code[1] = "A500"; function runcodes() { alert('In runcodes'); alert('len = '+len); alert('course_code.length = '+course_code.length); for (i = 0 ; i < course_code.length ; i++) {alert(course_code '+i+' = '+course_code[i]);} } </script> <body> <button type="button" name="runc" id="runc" onclick="runcodes()"; > Click to display course codes table. </button> </body> [ICODE] When I bring this up in a browser and click the button, I get the following alerts: In runcodes len = 2 and then the script simply stops. So it stops on the first reference to the array. Clearly I am getting to function, and the function is able to handle the global primitive 'len', but it stops on encountering the global array. I've tried a lot of variations on the the theme, but nothing gets past this restriction. How do I access elements in a global array from inside a function? Hi! I'm trying to run this script on Firefox. I'm copying and pasting the whole thing in here just to be safe, but I'm mostly concerned with getting the findLegendary function to call catchPok(). The script executes fine, goes into the battle, but then...does nothing. It runs the catchPok function if I manually click and deselect the "Find Legendary" window option, so alternately, if somebody knows how to make the program automatically click the element at that point to stop repeating the function (maybe?) and it works, I'd be just as happy with that. My best guess is that the autoContinue function might be interfering somehow, since it runs that portion of the code with the manual findLegendary shutoff, but to be honest I'm pretty clueless. What I want it to do is run the catch function through, catch the game pixel, and then go back to repeating. I don't care how this is accomplished as long as it can feasibly loop. The game rules allow botting, so this isn't against any site rules, either. Any and all help/advice is much appreciated! Code: // ==UserScript== // @name Pokemon Vortex Tool // @namespace vortexrising.tk // @include http://*pokemonvortex.org/* // @exclude http://*pokemonvortex.org/adv.php* // ==/UserScript== var legends = [ // Custom // Grass 'Shaymin (Sky)', 'Celebi', 'Latios', 'Latias', 'Rayquaza', 'Shaymin', 'Mew', 'Cresselia', 'Azelf', 'Uxie', 'Mesprit', 'Virizion', 'Genesect', // Grass (water) 'Manaphy', 'Phione', 'Suicune', 'Keldeo', // Ice 'Articuno', 'Suicune', 'Lugia', 'Regice', 'Kyurem', // Cave (land) 'Groudon', 'Arceus', 'Regigigas', 'Palkia', 'Dialga', 'Deoxys', 'Jirachi', 'Registeel', 'Regirock', 'Mewtwo', 'Cobalion', 'Terrakion', 'Virizion', 'Reshiram', 'Zekrom', 'Kyurem', 'Genesect', 'Tornadus', 'Landorus', // Cave (water) 'Kyogre', 'Lugia', 'Keldeo', // Ghost 'Mew', 'Giratina', 'Rotom', 'Mesprit', 'Azelf', 'Uxie', 'Celebi', 'Darkrown', 'Darkrai', // Electric 'Zapdos', 'Raikou', 'Jirachi', 'Darkrai', 'Darkrown', 'Thundurus', 'Zekrom', 'Genesect', // Fire 'Heatran', 'Ho-oh', 'Moltres', 'Entei', 'Reshiram', 'Victini' ]; var settings = { 'keys': ['autoBattle', 'findRare', 'findLegendary','catchPok','findNewpoke'], 'data': {}, 'save': function() { for (var i = 0; i < this.keys.length; i++) { GM_setValue(this.keys[i], this.data[this.keys[i]]); } }, 'load': function() { for (var i = 0; i < this.keys.length; i++) { this.data[this.keys[i]] = GM_getValue(this.keys[i], false); } } }; var movPos = 0; function moveAround() { movPos += 10; if (movPos > 360) { movPos = 0; } var xpos = parseInt(Math.sin(movPos * (Math.PI / 180))*10); var ypos = parseInt(Math.cos(movPos * (Math.PI / 180))*10); unsafeWindow.PlayRequest(xpos + 14, ypos + 14, parseInt(Math.random()*8)+1); /* var btnArrow = unsafeWindow.document.querySelector('#arrows img[onclick]') if (btnArrow) { btnArrow.click(); } else { unsafeWindow.console.info('No buttons?'); }*/ } function catchPok() { try { var btnPo = unsafeWindow.document.querySelector('#battleForm input[type="submit"][value="Continue"]'); if (btnPo) { btnPo.click(); } var radMaster = unsafeWindow.document.querySelector('#itemForm input[type="radio"][value="Master Ball"]'); if (radMaster) { radMaster.click(); } var btnItem = unsafeWindow.document.querySelector('#itemForm input[type="submit"][value="Use Item"]'); if (btnItem) { btnItem.click(); } var btnCont2 = unsafeWindow.document.querySelector('#battleForm input[type="submit"][value="Continue!"]'); if (btnCont2) { btnCont2.click(); } var linkReturnToMap = unsafeWindow.document.querySelector('.optionsList a'); if (linkReturnToMap && linkReturnToMap.textContent.trim() == 'Return to the Map') { settings.data.nextBattle = new Date().getTime() + 10000; unsafeWindow.location.href = linkReturnToMap.href; } }catch (e) { unsafeWindow.console.warn('Exception: ', e); } } function findNewpoke() { var aPoke = unsafeWindow.document.querySelector('#appear p'); var oldPoke = unsafeWindow.document.querySelector('#appear strong'); var searchPoke = unsafeWindow.document.querySelector('#alert p') if (!aPoke) { moveAround(); return; } else if (oldPoke) { moveAround(); return; } else if (searchPoke) { moveAround(); return; } else { var btnDo = unsafeWindow.document.querySelector('input[type="submit"][value="Battle!"]'); if (btnDo) { btnDo.click(); } catchPok(); return; } } function findLegendary() { var wildText = unsafeWindow.document.querySelector('#appear p'); if (!wildText) { moveAround(); return; } wildText = wildText.textContent.trim(); for (var i = 0; i < legends.length; i++) { if (wildText.match(legends[i])) { var btnDo = unsafeWindow.document.querySelector('input[type="submit"][value="Battle!"]'); if (btnDo) { btnDo.click(); } catchPok(); return; } } moveAround(); } function findRare() { var wildText = unsafeWindow.document.querySelector('#appear p'); if (!wildText) { moveAround(); return; } wildText = wildText.textContent.trim(); if (!wildText.match(/Wild (Shiny|Shaymin (Sky)|Celebi|Latios|Latias|Rayquaza|Shaymin|Mew|Cresselia|Azelf|Uxie|Mesprit|Virizion|Genesect|Manaphy|Phione|Suicune|Keldeo|Articuno|Lugia|Regice|Kyurem|Groudon|Arceus|Regigigas|Palkia|Dialga|Deoxys|Jirachi|Registeel|Regirock|Mewtwo|Cobalion|Terrakion|Reshiram|Zekrom|Tornadus|Landorus|Kyogre|Giratina|Rotom|Zapdos|Raikou|Darkrai|Darkrown|Thundurus|Heatran|Ho-oh|Moltres|Entei|Victini)/)) { moveAround(); return; } unsafeWindow.console.info('Rare found ', wildText); } function autoBattle() { try { var btnContinue = unsafeWindow.document.querySelector('#battleForm input[type="submit"][value="Continue"]'); if (btnContinue) { btnContinue.click(); } var btnContinue2 = unsafeWindow.document.querySelector('#battleForm input[type="submit"][value="Continue!"]'); if (btnContinue2) { btnContinue2.click(); } var btnAttack = unsafeWindow.document.querySelector('#battleForm input[type="submit"][value="Attack!"]'); if (btnAttack) { btnAttack.click(); } var linkReturnToMap = unsafeWindow.document.querySelector('.optionsList a'); if (linkReturnToMap && linkReturnToMap.textContent.trim() == 'Return to the Map') { settings.data.nextBattle = new Date().getTime() + 10000; unsafeWindow.location.href = linkReturnToMap.href; } // check for battle button var btnBattle = unsafeWindow.document.querySelector('#appear form input[type="submit"][value="Battle!"]'); var linkRebattle = unsafeWindow.document.querySelector('.optionsList a'); if (btnBattle) { // wait until 10 seconds since last battle //var delay = GM_getValue('lastBattle'); window.setTimeout(function() { btnBattle.click(); }, 10000); } else if (linkRebattle && linkRebattle.textContent.trim() == 'Rebattle Opponent') { window.setTimeout(function() { unsafeWindow.location.href = linkRebattle.href; }, 10000); } else { // if not found, click a direction var btnArrow = unsafeWindow.document.querySelector('#arrows img[onclick]') console.info('arrow', btnArrow); if (btnArrow) { btnArrow.click(); } } } catch (e) { unsafeWindow.console.warn('Exception: ', e); } } function autoContinue() { if (settings.data.findRare) { findRare(); } if (settings.data.autoBattle) { autoBattle(); } if (settings.data.findLegendary) { findLegendary(); } if (settings.data.catchPok) { catchPok(); } if (settings.data.findNewpoke) { findNewpoke(); } } unsafeWindow.AjaxRequest = function () { if (!this.xmlhttp) { try { // Try to create object for Firefox, Safari, IE7, etc. this.xmlhttp = new XMLHttpRequest(); } catch (e) { try { // Try to create object for later versions of IE. this.xmlhttp = new ActiveXObject('MSXML2.XMLHTTP'); } catch (e) { try { // Try to create object for early versions of IE. this.xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { // Could not create an XMLHttpRequest object. return false; } } } } this.method = 'post'; this.async = true; this.url; this.query = ''; this.data = ''; this.reponseText; this.reponseXML; this.responseHandler; this.abortHandler; this.showLoading = false; this.send = function () { if (this.method && this.url) { var self = this; this.xmlhttp.onreadystatechange = function () { if (self.xmlhttp.readyState == 4) { if (self.xmlhttp.status && (self.xmlhttp.status == 200 || self.xmlhttp.status == 304)) { //unsafeWindow.console.info('success', self); self.responseText = self.xmlhttp.responseText; if (self.xmlhttp.responseXML) { self.responseXML = self.xmlhttp.responseXML; } else { self.responseXML = null; } if (self.responseHandler) { self.responseHandler(); var evt = document.createEvent('Event'); evt.initEvent('gm:ajaxhook', false, true); document.dispatchEvent(evt); //autoContinue(); } } else { showAlert('<p>An error occured while requesting the data.</p><p>Status Msg: ' + self.xmlhttp.statusText + '</p><p><input type="button" name="ok" value="OK" onclick="removeAlert();" id="alertFocus"></p>'); } if (self.showLoading && self.loading) { self.loading.style.visibility = 'hidden'; } } } if (this.showLoading) { this.displayLoading(); } this.xmlhttp.open(this.method, this.url + '?' + encodeURI(this.query), this.async); if (this.method == 'post') { this.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); } this.xmlhttp.send(encodeURI(this.data)); } else { showAlert("<p>An error occured while requesting the data.</p><p>No method, URL, and/or query string provided.</p><p><input type=\"button\" name=\"ok\" value=\"OK\" onclick=\"removeAlert();\" id=\"alertFocus\"></p>"); } } this.abort = function () { this.xmlhttp.onreadystatechange = function () {}; this.xmlhttp.abort(); if (this.abortHandler) { this.abortHandler(); } } this.getFormValues = function (form) { for (i = 0; i < form.elements.length; i++) { switch (form.elements[i].type) { case 'text': case 'hidden': case 'password': case 'textarea': this.data += form.elements[i].name + "=" + form.elements[i].value + "&"; break; case 'checkbox': case 'radio': if (form.elements[i].checked) this.data += form.elements[i].name + "=" + form.elements[i].value + "&"; break; case 'select-one': this.data += form.elements[i].name + "=" + form.elements[i].options[form.elements[i].selectedIndex].value + "&"; break; } } this.data = this.data.substr(0, (this.data.length - 1)); } this.appendHTML = function (object, flag) { if (this.xmlhttp.responseText) { if (flag) { object.innerHTML = this.responseText; } else { object.innerHTML += this.responseText; } } else {} } this.displayLoading = function () { if (this.showLoading == 'sidebar') { this.loading = document.getElementById('sidebarLoading'); this.loading.style.height = document.getElementById('sidebar').offsetHeight - 2 + 'px'; this.loading.style.width = document.getElementById('sidebarContent').offsetWidth + 'px'; this.loading.innerHTML = '<p style="text-align: center; margin-top: 150px;"><img src="http://static.pokemonvortex.org/images/loading.gif" width="100" height="100" alt="Loading..." /></p>'; } else if (this.showLoading == 'message') // message { this.loading = document.getElementById('messageContent'); this.loading.style.height = document.getElementById('message').offsetHeight + 'px'; this.loading.style.width = document.getElementById('message').offsetWidth + 'px'; this.loading.innerHTML = '<p style="text-align: center; margin-top: 75px;"><img src="http://static.pokemonvortex.org/images/loading.gif" width="100" height="100" alt="Loading..." /></p>'; } else if (this.showLoading == 'messageList') // message list { this.loading = document.getElementById('messageList'); this.loading.style.height = document.getElementById('messageList').offsetHeight + 'px'; this.loading.style.width = document.getElementById('messageList').offsetWidth + 'px'; this.loading.innerHTML = '<p style="text-align: center; margin-top: 50px;"><img src="http://static.pokemonvortex.org/images/loading.gif" width="100" height="100" alt="Loading..." /></p>'; } else if (this.showLoading == 'map') // map { this.loading = document.getElementById('mapLoading') this.loading.innerHTML = '<p style="text-align: center; margin-top: 150px;"><img src="http://static.pokemonvortex.org/images/loading_white.gif" width="100" height="100" alt="Loading..." /></p>'; } else if (this.showLoading == 'live') { this.loading = document.getElementById('loading'); this.loading.style.height = document.getElementById('scroll').offsetHeight + 'px'; if (document.getElementById('scrollContent')) { this.loading.style.width = document.getElementById('scrollContent').offsetWidth + 'px'; } else { this.loading.style.width = document.getElementById('scroll').offsetWidth + 'px'; } this.loading.innerHTML = '<p class="large" style="margin-top: 75px; text-align: center;"><strong>Waiting for the other user to respond...</strong></p><p style="text-align: center;">You have been waiting <span id="waitTime">0 seconds</span>.</p>'; waitTime(0); } else // main { this.loading = document.getElementById('loading'); this.loading.style.height = document.getElementById('scroll').offsetHeight + 'px'; if (document.getElementById('scrollContent')) { this.loading.style.width = document.getElementById('scrollContent').offsetWidth + 'px'; } else { this.loading.style.width = document.getElementById('scroll').offsetWidth + 'px'; } this.loading.innerHTML = '<p style="text-align: center; margin-top: 150px;"><img src="http://static.pokemonvortex.org/images/loading.gif" width="100" height="100" alt="Loading..." /></p>'; } this.loading.style.visibility = 'visible'; } } function createToggler(container, title, varname) { var toggleEnable = unsafeWindow.document.createElement('p'); container.appendChild(toggleEnable); toggleEnable.innerHTML = title + ' <b>' + (settings.data[varname] ? 'Enabled' : 'Disabled') + '</b>'; toggleEnable.addEventListener('click', function() { settings.data[varname] = !settings.data[varname]; toggleEnable.innerHTML = title + ' <b>' + (settings.data[varname] ? 'Enabled' : 'Disabled') + '</b>'; settings.save(); autoContinue(); }, false); } function init() { var iframes = unsafeWindow.document.getElementsByTagName('iframe'); for (var i = 0; i < iframes.length; i++) { iframes[i].parentNode.removeChild(iframes[i]); } var sty = unsafeWindow.document.createElement('style'); unsafeWindow.document.querySelector('head').appendChild(sty); sty.textContent = '#fscctrl { background: green; border: 1px solid yellow; cursor:pointer; margin: auto; padding: 10px; width: 1010px; } #fscctrl p { margin: 0; } #alert{position:absolute; z-index: 1; background:#ffc; padding: 0 10px; right: 0; width: 100px;} #alert p { margin: 0; } #loading {z-index: 0; top: 0; height: 200px;} #loading p {margin-top:0 !important;} #header{ height: 70px; }'; unsafeWindow.disableSubmitButton = function(form) { for (i = 0; i < form.elements.length; i++) { if (form.elements[i].type == 'submit') { form.elements[i].value = 'Please Wait... or click again - by rockingdo'; } } return true; } settings.load(); document.addEventListener('gm:ajaxhook', function() { autoContinue(); }, false); var container = unsafeWindow.document.createElement('div'); unsafeWindow.document.body.insertBefore(container, unsafeWindow.document.body.firstChild); container.setAttribute('id', 'fscctrl'); createToggler(container, 'Auto-battle', 'autoBattle'); createToggler(container, 'Find Rare', 'findRare'); createToggler(container, 'Find Legendary', 'findLegendary'); createToggler(container, 'Catch Pokemon', 'catchPok'); createToggler(container, 'Find New Pokemon', 'findNewpoke'); autoContinue(); } init(); |