JavaScript - Refresh Detection Algorithm Not Working
Hello,
I'm trying to write some javascript that will detect if the page has been loaded because of the refresh button being pressed. I've searched google on how to do this, and several websites recommend something similar to the code I'm implementing below: Code: <script type="text/javascript" language="javascript"> // in head function checkRefresh() { alert("BEFO value = " + document.getElementById("visited").getAttribute("value")); if (document.getElementById("visited").getAttribute("value") == null || document.getElementById("visited").getAttribute("value") == "") { document.getElementById("visited").setAttribute("value", "refreshed") } alert("AFTER: value = " + document.getElementById("visited").getAttribute("value")); } </script> ... <body onload="Javascript:checkRefresh();"> ... <form id="hiddenform"> <input type="hidden" id="visited" value="" /> </form> </body> My variation differs from most of the examples on the internet in a few ways (which may or may not affect its functionality): 1) Most examples access the elements by directly using their names (as in: document.hiddenForm.visited.value). I'm using document.getElementById(...).getAttribute(...) just because that seems to be the safest way to ensure you are in fact getting the elements you want, and setAttribute(...) to ensure you're setting the attribute in the proper way. This entails that I need to set the ID in the form and input elements rather than the name. 2) I'm accessing the input tag directly (rather than going through the form) because I really don't see how this would make a difference. 3) I'm doing all this within asp:content tags which, from what I understand, can affect the behavior of the elements within it. I'm not sure if this works out for other programmers, but for me it doesn't seem to be working. My alert messages in the checkRefresh function tell me that the value of the input element does indeed change as expected, but it seems to get wiped out and reinitialized to the original value of "" when the page is refreshed. Am I doing something wrong? Thanks for any help. Similar TutorialsI would like to mention: I DON'T KNOW MUCH (ANYTHING) ABOUT JAVASCRIPT I am using this script to reload my minicart every 1 second but it doesn't work in IE. I don't want to use php (because the e-commerce site I am using doesn't allow php). Code: <script type="text/javascript"> function cartRefresh() { $("#minicart").load(location.href+" #minicart>*",""); $("#sliderContent").load(location.href+" #sliderContent>*",""); } setInterval(function() { cartRefresh(); }, 1000); </script> Can anyone help me out with either a new code or make this workable with IE? thnx a bunch! not sure why this wont sort in asending order... i tend to make little dumb mistakes sorry. :/ Code: <script type="text/javascript"> function sort(nums) { var rangeStart = 0; var rangeEnd = nums.length - 1; var i = 0; var minPosition = rangeStart; while(rangeStart < rangeEnd) { // find minumum for(i = rangeStart; i < rangeEnd; i++) { if(nums[i] <= nums[minPosition+1]) { minPosition = i; } } // swap var temp = nums[rangeStart]; nums[rangeStart] = nums[minPosition]; nums[minPosition] = temp; // change range rangeStart++; } } document.write("<h3>Examples</h3>"); first10 = [2,3,5,7,9,4,8,0,6,1]; document.write("<div>Sorting <tt>["+first10+"]</tt> with current code gives "); sort(first10); document.write("<tt>["+first10+"]</tt></div>"); ages = [19,34,20,66,82,53,88,74,39,13]; document.write("<div>Sorting <tt>["+ages+"]</tt> with current code gives "); sort(ages); document.write("<tt>["+ages+"]</tt></div>"); </script> SO, thanks for checking this out. If i have 3 text areas for output and an array that can be of size 0 to however big a user passes in values. How would I display the last 3 values of the array in the text areas? Here's what I was thinking psuedoCode, but I just want to know if there is an easier way. thnx! Code: //handling all the cases (ie if i have less than 3 items) var size = array.length display 0 if(size <= 3) if(size == '3'){ display0 = array[0] display1 = array[1] display2 = array[2] if(size == '2') do the same but copy the 2 elements if(size == '1') do the same else var newSize = (size -1) - 1 //to find where the first of the 3 elements will be display0 = array[newsize] display1 = array[newsize+1] display2 = array]newsize+2] Its seems a bit extraneous doing it this method, so i was just wondering if anyone could think of a better way. Thanks again! Hi, I have the below code: Code: <script type="text/javascript"> function loadQuickMessageCheck(File,ID){ var xmlhttp; 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; eucalyptus = setInterval(function(){loadQuickMessageCheck(File,ID)},20000); } } xmlhttp.open("POST",File,true); xmlhttp.send(); } </script> But I am overloading the server and crashing it. I've googled the issue and have found people with similar problems who talk about the need to cancel the last refresh request before they send the next refresh. I even found this nice piece of code which worked for someone else. Quote: try{window.clearTimeout(tRefresh)} catch(err) {} tRefresh = setInterval(setContext, varInterval*60*1000); } I am not sure if this is the solution that I am looking for but if it is all my attempts at applying this code has been a bit of a disaster. I've written a function that "condenses" a string if it is too long. Code: function shortenMsg(msg,maxLen){ if (msg.length > maxLen){ var over = msg.length - maxLen, // amount that needs to be trimmed method1 = (msg.match(/,\s/g) || []).length, // amount that method1 can trim method2 = (msg.match(/\]\s\[/g) || []).length; // etc... method3 = (msg.match(/demonstration/gi) || []).length * 6, // etc... if (method1 >= over){ msg = msg.replace(/,\s/g, ","); } else if (method2 >= over){ msg = msg.replace(/\]\s\[/g, "]["); } else if (method3 >= over){ msg = msg.replace(/nstration/gi, ""); } else { // optimal combination of 2+ methods } } return msg; } var longMsg = "...", shortMsg = shortenMsg(longMsg, 50); // example usage Each of the methods 1-3 is the amount that that specific method can trim from the string. I'd like to be able to trim as little as possible. For example, if the string needs 5 characters to be trimmed, and method1 can trim 8 characters, but method3 can trim 6, then method3 should be used. If none of the methods can individually trim the string enough, then I'd like the optimal combination of the methods that will get the job done. I can't figure out what sort of code structure I need for this (besides a ton of if/else statements). Maybe an array that contains each of the methods, arranged in increasing order....? Help would be appreciated! Sorry for posting so much recently I have an assignment to code a java class that plays rock, paper, or scissors. The class can access the history of past gestures played by both itself and its opponent, but nothing else. The class will be played against others in 10,000 matches and the winner will be determined via round robin format. Other than using a greedy algorithm to determine statistically the best choice from prior gestures and basic pattern recognition I have no decent ideas. I'd appreciate any suggestions.
I doubt this is possible without third party applications. But I was wondering if there is a way to detect where the eyes are routhly in an image on someone face (which may have multiple faces). Basically I want to get the position of both eyes and se if they are horizontal or verticle. So then I can rotate the iimage if the eyes are more verticle then horizontal. I use the youtube javascript api. Now the users of my website can start the player with an imacro and the function player.playVideo(). Is it possible that I can detect or disable this funtion? Thanks Hey I am in need of some help with a hash removal detection code, currently I have everything I need to do what I want but when I click the back button and the hash is removed from the url I need to have a script run to then change the page content. My design looked sort of like this. Code: function detect() { var url = window.location; if(url.indexOf('#') === -1) { // run the code } } But that ran the code every time there wasn't any hash in the url so if a user went to lets say /index.php the page content would keep being re-generated as there isn't any hash, so my question is how can I make it so it only runs only if there has been a hash in the url and then has been removed so like if you went to /index.php and clicked a link that took you to /index.php#tags and then the page content was changed with ajax, then the user clicked the browsers back button to go back to /index.php, the page would still have the tags content on it so that's when I need the function to run to change it back again. If anyone can help with my problem please reply. Thank you - DJCMBear Hey, I'm working on a mobile website and need some help with my mobile browser detection script. I have it working for iPhone, iPod Touch, and Windows Mobile Devices. I need help getting it to detect for Blackberry Browser (Blackberry Devices), Blazer Browser (Palm Devices), Opera Mini Browser, Opera Mobile Browser, and other mobile browsers if possible. Does anyone know how to modify (and test if you have a phone to test with, as I don't have all of these devices) this javascript?: Code: if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {location.replace("mobile.html");} if((navigator.appVersion.indexOf("Windows CE")>0)) {location.replace("mobile.html");} Thanks for your help! -Chris I have a website (www.andrewburns.net.au) that displays differently according to OS. Currently in OSX the text in the menu lines up with the image text of the site title - this is what we want to have happen and it looks fine across all browsers using OSX. However, in Windows it's offset by about 10px, and similarly displays the same offset in all Windows browsers incl Chrome, FF, Safari, and of course ie. I'm trying to use javascript to sniff out the OS and display alternate css accordingly. I'm not a JS coder at all and a friend who is has got me this far... Code: var isms=( navigator.appVersion.indexOf("Windows") != -1); document.write("Browser Version: " + isms); if(isms) $('DIV .menu').css('left','100px'); What I'm not sure about is where to put it to make it work given there is a fair amount of other scripts operating on the site. Is there anyone out there who can have a look at the site/source code and offer any insight/suggestions/solutions? I'd really appreciate it... I'm under a fair bit of pressure from the designer to get it pixel perfect and this is the last aspect of the site to sort out before I can sign it off. Thanks Hi, How do I detect change event on textarea using javascript? I'm trying to detect any change, but without any type. For example, instead to have an "onclick submit button" to copy the contents of the textarea to another file, how it can be done automatically when focos is in? In short words, I want to submit a form without pressing a submit button! Regards Jan Lee i cant get collission detection to work. i tryed but it always caused an infinite loop. heres the code. Code: <html> <!-- main file.--> <head> <title>lightning generator</title> </head> <body> <canvas id='world' width='500' height='500' style='border: 1px solid black; padding:0;'></canvas> <script type="text/javascript" src='world.js'></script> <script type='text/javascript' src='eC.js'></script> <script type='text/javascript' src='world.ground.js'></script> <script type='text/javascript'> world.bolt = { } ; world.bolt.paths = []; // main obj inits world.bolt.draw = function(){ var x, y; for( var id = 0; id <= world.bolt.draw.num; id ++ ){ world.ctx.moveTo( world.bolt.paths[id].x[world.bolt.paths[id].x.length-1], world.bolt.paths[id].y[world.bolt.paths[id].y.length-1] ); var mdx=Math.floor(Math.random()*world.bolt.paths[id].mdx); x = world.bolt.paths[id].x[world.bolt.paths[id].iters] + ((Math.random()<Math.random())?mdx:-mdx); y = ++ world.bolt.paths[id].iters; world.bolt.paths[id].x.push( x ); world.bolt.paths[id].y.push( y ); world.ctx.strokeStyle = world.bolt.paths[id].color; world.ctx.lineTo( x, y ); world.ctx.stroke(); //world.ctx.beginPath(); } if(x%3==0){ world.ctx.fillStyle=world.skyColor; world.ctx.fillRect(0,0,world.w,world.h);} } world.bolt.draw.num=-1; world.bolt.cpath = function( x, y, mdx, srate, id, color ){ world.bolt.paths[id] = { } ; world.bolt.paths[id].iters = 0; world.bolt.paths[id].x = []; world.bolt.paths[id].y = []; world.bolt.paths[id].x[0] = x; world.bolt.paths[id].y[0] = y; world.bolt.paths[id].mdx = mdx; world.bolt.paths[id].srate = srate; world.bolt.paths[id].color = color; world.bolt.draw.num += 1; } world.bolt.cpath(250,0, 5,5,0,'rgba(255,255,150,.5)'); window.setInterval(world.bolt.draw,100) window.setTimeout('world.bolt.cpath(125,0,5,5,1,"rgba(255,10,0,.5)")',1000); </script> </body> </html> Code: //world.js var world = { skyColor:'rgba(0,0,100,.009)' } ; world.canvas = document.getElementById( 'world' ) world.canvas.cstyle = document.defaultView.getComputedStyle( world.canvas, null ) world.w = parseInt( world.canvas.cstyle.width, 10 ); world.h = parseInt( world.canvas.cstyle.height, 10 ); world.ctx = world.canvas.getContext( '2d' ); finally, Code: // world.ground.js world.ground = { } ; world.ground.level = []; world.ground.make = function( GArray, length ){ world.ctx.strokeStyle = '#000000'; world.ground.level = []; world.ctx.fillStyle = '#FFF'; world.ctx.fillRect( 0, 0, world.w, world.h ); world.ground.level = GArray; for ( world.ground.make.i = 0; world.ground.make.i <= length; world.ground.make.i ++ ){ if ( GArray[world.ground.make.i + 1] === undefined ){ GArray[world.ground.make.i + 1] = GArray[world.ground.make.i]; } world.ctx.moveTo( world.ground.make.i, ( world.h ) ); world.ctx.lineTo( world.ground.make.i, ( world.h - GArray[world.ground.make.i] ) ); } world.ctx.stroke(); world.ctx.beginPath(); } ; world.ground.create = function( func, width ){ func = ec( func ); if( func === false ){ alert( 'Pass equation as a string without the "y=", "f(x)=", "g(x)=" or similar.' ); return world; } if( func == 'perspicaciousness' ){ return world; } var temp = []; for( var x = 0; x <= width; x ++ ){ temp[x] = eval( func ); } world.ground.make( temp, width ); } ; world.ground.create.test='4'; world.ground.create( world.ground.create.test, 500 ); in the end of world.bolt.cpath,there should be a way to use the local varis X and Y, and world.ground.js's world.ground.level[] to detect it. sorry for the gigantic length. thanks in advanced. the jsnerd Good day! I have an intranet website that was in the server and it has a flash. My problem is the client computer has no flash installer; I want that they can access the flash.exe in the server so they can install it to their computer. I read some forum that it could happen using JavaScript detection code. Honestly I have no idea about it. Thank you i don't know what has changed in last releases of Firefox and Opera but before i used this script to detect browser versions (IE, Opera, FF) and block or redirect depending on version Code: <script language="javascript"> <!-- //Detect IE greater than 1 - we are blocking it completely version=0 if (navigator.appVersion.indexOf("MSIE")!=-1){ temp=navigator.appVersion.split("MSIE") version=parseFloat(temp[1]) } if (version>1) window.location="ie-error.html" //Detect Opera less than 10 (9.80) if (navigator.userAgent.indexOf("Opera")!=-1){ var versionindex=navigator.userAgent.indexOf("Opera")+6 if (parseInt(navigator.userAgent.charAt(versionindex))<9.8) window.location="op-error.html" else (window.location="index2.html") } //Detect Firefox less than 3.6 if (navigator.userAgent.indexOf("Firefox")!=-1){ var versionindex=navigator.userAgent.indexOf("Firefox")+8 if (parseInt(navigator.userAgent.charAt(versionindex))<3.6) window.location="ff-error.html" else (window.location="index2.html") } // --> </script> it worked last with Opera 9.5, FF 3.0 but after that it doesnt work at all Firefox'es version (3.6) doesn't get detected and is redirected to error page same goes with Opera (9.8 which is 10.0-10.5) can anyone tell me why this happens ? or can anyone "fix it" i know many people are against this kind of scripts (blockers and redirecters) but i do it so people who come with older and less compatible browsers with W3C standards to get warned so they don't load deformed page Hi, I need a javascript that detects flash and replace z-index value. i have 2 div. div1 (alternate HTML content) has z-index=-3 and div2 (flash object) z-index=0. If flash is detected, do nothing. if flash is not detected, i would like to set div1 z-index to a positive 3. can someone please help me? Greetings, I'm working on a php/mysql app that has multiple tabs with multiple form fields. I am trying to incorporate a javascript form field detection function that alerts the user that they have not submitted their changes if they try to navigate away. The detection works as designed, but the problem I am having is when the form is submitted, the script senses an unload and still fires the alert. The form submits to itself and updates the database and then reloads the page with the new values. Is there a way to have the script ignore the forms submit url and skip the form check? Here is the code ( NOT mine, found it somewhere else.) Code: <script language="javascript"> var ids = new Array('description'); var values = new Array('<?php echo $detail['description']; ?>'); function populateArrays() { // assign the default values to the items in the values array for (var i = 0; i < ids.length; i++) { var elem = document.getElementById(ids[i]); if (elem) if (elem.type == 'checkbox' || elem.type == 'radio') values[i] = elem.checked; else values[i] = elem.value; } } var needToConfirm = true; window.onbeforeunload = confirmExit; function confirmExit() { if (needToConfirm) { // check to see if any changes to the data entry fields have been made for (var i = 0; i < values.length; i++) { var elem = document.getElementById(ids[i]); if (elem) if ((elem.type == 'checkbox' || elem.type == 'radio') && values[i] != elem.checked) return "Your changes have not been saved. Are you sure you want to leave?"; else if (!(elem.type == 'checkbox' || elem.type == 'radio') && elem.value != values[i]) return "Your changes have not been saved. Are you sure you want to leave?"; } // no changes - return nothing } } </script> The url of the page is "edit.php?&mode=edit&t=2&id=284&cn=2009-002" The only detectable change to the query string would be the 't' variable. Basically what I want to do is have the script look for a change in the 't' variable and if detected, check the form values for changes. If 't' doesn't change, skip the script completely. Thanks.. hey guys i'm making a lunar lander game using javascript.i want the player to land the spaceship on a black line i've drawn. but i have problems getting it right.when the player lands it properly in the line i want it to display a dialogue box which says u landed it perfectly.but the problem is even if i land it outside the line it gives me that message.so after spending sometime with it i figured out that my if statement is not working properly.it doesn't take the value from my x axis and only considers the value from my y axis.for eg lets say i drew the line from 560px to 600px on the x axis and its located at 700px on the y axis and this is my if statement if((TopPos>695)&&(rightPos>560)&&(rightPos<600)) { alert('you landed perfectly') } this is supposed to work but if i go above 600px but still maintains the height above 695 it says i have won.i have included the code could some point me out where i'm making the mistake thank you . Code: <html> <head> <title>Lunar lander</title> <script language="JavaScript"> var TopPos=100; var fuel = 300; var gravity = 0.0001; var speed = 0.0005; var moveBy = 366; var Xpix = 1000; function animation(){ TopPos +=gravity document.getElementById("divlander").style.top = TopPos + "px"; if ((TopPos>604)&&(Xpix<526)){ alert('win'); } else if ((moveBy<100)&&(moveBy>500)){ alert('crashed'); } if(TopPos<610) window.setTimeout("animation()",30); gravity +=0.03; gravity += speed; var f = document.game.fuel.value; f--; document.game.fuel.value = f; if (f<=0){ document.game.fuel.value ="0"; gravity=10; gr=0; speed=10; f=1; alert('out of fuel'); } } function moveObj(name, Xpix, Ypix) { obj = document.getElementById(name); px = parseInt(obj.style.left) + Xpix; py = parseInt(obj.style.top) + Ypix; obj.style.left = px; obj.style.top = py; } function ProcessKeypress(e) { var myObj = "divlander"; var moveBy = 10; if (e.keyCode) keycode=e.keyCode; else keycode=e.which; ch=String.fromCharCode(keycode); if(ch=='a') moveObj(myObj, -moveBy, 0); else if(ch=='d') moveObj(myObj, moveBy, 0); else if(ch=='w') gravity = -1; } </script> <form name='game'> <body onKeyPress="ProcessKeypress(event);"> <body onload ="animation();"> <input type=button value='200' name="fuel"> <p><img id="divlander" style="z-index: 0; left: 1000px; position: absolute; top: 100px" img src="lunar_lander_72dpi2.png"></p> <img src="Serenity2.jpg";> <p><<body> </body> </form> </html> I'm looking for a javascript that will detect the following user information: OS version, browser version, quicktime + flash + adobe reader + java + windows media player + sliverlight versions of the users computer. I am looking to put this script into an HTML page and the information be displayed so the user can see what versions of the programs they have. I don't know a whole lot about javascript so if there is a script i could copy and paste, that would be great!!!! Also, is it possible to have the current versions of these programs displayed and automatically updated as well so the user can compare the version they have with the most current version of the program? Any help would be great! Thanks!!! |