JavaScript - Simple Js Code - Just Need Some Minor Assistance
Similar TutorialsI have a javascript code, which initiates via "onClick" when a user clicks on a checkbox. I downloaded the sample code, but the problem is is that I need the javascript to be initiated automatically, not when a user clicks on a checkbox. I would greatly appreciate it if anyone could help me resolve this issue. Below is a sample of the code I'm using. Thanks in advance. Code: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <!-- iPad/iPhone specific css below, add after your main css > <link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="ipad.css" type="text/css" /> <link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="iphone.css" type="text/css" /> --> <!-- If you application is targeting iOS BEFORE 4.0 you MUST put json2.js from http://www.JSON.org/json2.js into your www directory and include it here --> <script type="text/javascript" charset="utf-8" src="phonegap.0.9.6.min.js"></script> <script type="text/javascript" charset="utf-8" src="SAiOSAdPlugin.js"></script> <script type="text/javascript" charset="utf-8"> // If you want to prevent dragging, uncomment this section /* function preventBehavior(e) { e.preventDefault(); }; document.addEventListener("touchmove", preventBehavior, false); */ var gLastAdLoadedDate = null; var gTotalAdsLoaded = 0; var gTimerId = null; function onBodyLoad() { document.addEventListener("deviceready", onDeviceReady,false); } function onOrientationChange() { //alert(window.orientation); } /* When this function is called, PhoneGap has been initialized and is ready to roll */ function onDeviceReady() { // listen for orientation changes window.addEventListener("orientationchange", window.plugins.iAdPlugin.orientationChanged, false); // listen for the "iAdBannerViewDidLoadAdEvent" that is sent by the iAdPlugin document.addEventListener("iAdBannerViewDidLoadAdEvent", iAdBannerViewDidLoadAdEventHandler, false); // listen for the "iAdBannerViewDidFailToReceiveAdWithErrorEvent" that is sent by the iAdPlugin document.addEventListener("iAdBannerViewDidFailToReceiveAdWithErrorEvent", iAdBannerViewDidFailToReceiveAdWithErrorEventHandler, false); var adAtBottom = false; setTimeout(function() { window.plugins.iAdPlugin.prepare(adAtBottom); // by default, ad is at Top }, 1000); } function iAdBannerViewDidFailToReceiveAdWithErrorEventHandler(evt) { alert(evt.error); window.plugins.iAdPlugin.showAd(false); var elem = document.getElementById("showAd"); elem.checked = false; } function iAdBannerViewDidLoadAdEventHandler(evt) { // if we got this event, a new ad is loaded var elem = document.getElementById("lastAdLoaded"); gLastAdLoadedDate = new Date(); elem.innerHTML = gLastAdLoadedDate.toLocaleString(); elem = document.getElementById("showAd"); elem.disabled = false; elem.checked = true; window.plugins.iAdPlugin.showAd(true); gTotalAdsLoaded++; elem = document.getElementById("totalAdsLoaded"); elem.innerHTML = gTotalAdsLoaded.toString(); if (gTimerId) { clearInterval(gTimerId); } gTimerId = setInterval(lastAdLoadedInterval, 1000); } function lastAdLoadedInterval() { var now = (new Date()).getTime(); var diff = now - gLastAdLoadedDate.getTime(); var elem = document.getElementById("lastAdLoaded"); var ms_in_a_year = 31449600000; /* 1000ms x 60s x 60m x 24hrs x 7d x 52w */ var ms_in_a_week = 604800000; /* 1000ms x 60s x 60m x 24hrs * 7d */ var ms_in_a_day = 86400000; /* 1000ms x 60s x 60m x 24hrs */ var ms_in_an_hour = 3600000; /* 1000ms x 60s x 60m */ var ms_in_a_minute = 60000; /* 1000ms x 60s */ var ms_in_a_second = 1000; var milliseconds = Math.floor(diff); var seconds = Math.floor(milliseconds / ms_in_a_second) % 60; var minutes = Math.floor(milliseconds / ms_in_a_minute) % 60; var hours = Math.floor(milliseconds / ms_in_an_hour) % 24; var days = Math.floor(milliseconds / ms_in_a_day) % 7; var weeks = Math.floor(milliseconds / ms_in_a_week) % 52; var years = Math.floor(milliseconds / ms_in_a_year); var caption = seconds + "s ago"; if (minutes > 0) { caption = minutes + "m " + caption; } if (hours > 0) { caption = hours + "h " + caption; } if (days > 0) { caption = days + "d " + caption; } if (weeks > 0) { caption = weeks + "w " + caption; } if (years > 0) { caption = years + "yr " + caption; } elem.innerHTML = caption; } function showAdClicked(evt) { window.plugins.iAdPlugin.showAd(evt.checked); } </script> </head> <body style="margin:0; padding:0;border:1px solid blue;" onload="onBodyLoad()"> <span style="position:absolute; top:0;"> This is some text at the top of the webview. </span> <br /><br /> <form> <input type="checkbox" id="showAd" name="showAd" disabled="disabled" onclick="showAdClicked(this);">Show iAd</input><br /> <br /> <span>New Ad Loaded: <span id="lastAdLoaded">Waiting.</span></span><br /> <span>Total Ads Loaded: <span id="totalAdsLoaded">None.</span></span> </form> <br /> <span style="position:absolute;bottom:0"> This is some text at the bottom of the webview. </span> </body> </html> The javascript (SoiOSADPLUGIN.JS) that is referenceD in this html page i also pasted below he Code: /** * Constructor */ function SAiOSAdPlugin() { } /** * show - true to show the ad, false to hide the ad */ SAiOSAdPlugin.prototype.orientationChanged = function() { PhoneGap.exec("SAiOSAdPlugin.orientationChanged", window.orientation); } /** * show - true to show the ad, false to hide the ad */ SAiOSAdPlugin.prototype.showAd = function(show) { PhoneGap.exec("SAiOSAdPlugin.showAd", show); } /** * atBottom - true to put the ad at the bottom, false to put the ad at the top */ SAiOSAdPlugin.prototype.prepare = function(atBottom) { if (!atBottom) { atBottom = false; } PhoneGap.exec("SAiOSAdPlugin.prepare", atBottom); } /** * Install function */ SAiOSAdPlugin.install = function() { if ( !window.plugins ) window.plugins = {}; if ( !window.plugins.iAdPlugin ) window.plugins.iAdPlugin = new SAiOSAdPlugin(); } /** * Add to PhoneGap constructor */ PhoneGap.addConstructor(SAiOSAdPlugin.install); I get the code to work when I click the checkbox, and it satisfies my needs, but having a checkbox toggle is not exactly ideal for this function. Is there anyway for me to have the "Onclick" function in this code changed to onload? hey guys i downloaded the 'Content Slider v2.4', and this has a feature which will save a cookie used to remember and recall the last content viewed by the user when they return to the page. (click here for more information on the script.) the only thing is that this is made for pages with URLs such as: Quote: www.mysite.com/gallery_album_1/content.php but my URLS are set out like: Quote: www.mysite.com/content.php?gallery_album_1 is there a way to make to so the cookie remembers the page via the "php?gallery_album_1" part instead of the "content.php" part. i need it to be like this simply because i have multiple galleries coming from the oe page, eg: Quote: www.mysite.com/content.php?gallery_album_1 www.mysite.com/content.php?gallery_album_2 www.mysite.com/content.php?gallery_album_3 the main code of the js is as follows: Code: //** Featured Content Slider script- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com. //** May 2nd, 08'- Script rewritten and updated to 2.0. //** June 12th, 08'- Script updated to v 2.3, which adds the following features: //1) Changed behavior of script to actually collapse the previous content when the active one is shown, instead of just tucking it underneath the later. //2) Added setting to reveal a content either via "click" or "mouseover" of pagination links (default is former). //3) Added public function for jumping to a particular slide within a Featured Content instance using an arbitrary link, for example. //** July 11th, 08'- Script updated to v 2.4: //1) Added ability to select a particular slide when the page first loads using a URL parameter (ie: mypage.htm?myslider=4 to select 4th slide in "myslider") //2) Fixed bug where the first slide disappears when the mouse clicks or mouses over it when page first loads. var featuredcontentslider={ //3 variables below you can customize if desired: ajaxloadingmsg: '<div style="margin: 20px 0 0 20px"><img src="../images/loading.gif" /> Fetching slider Contents. Please wait...</div>', bustajaxcache: true, //bust caching of external ajax page after 1st request? enablepersist: true, //persist to last content viewed when returning to page? settingcaches: {}, //object to cache "setting" object of each script instance jumpTo:function(fcsid, pagenumber){ //public function to go to a slide manually. this.turnpage(this.settingcaches[fcsid], pagenumber) }, ajaxconnect:function(setting){ var page_request = false if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) try { page_request = new ActiveXObject("Msxml2.XMLHTTP") } catch (e){ try{ page_request = new ActiveXObject("Microsoft.XMLHTTP") } catch (e){} } } else if (window.XMLHttpRequest) // if Mozilla, Safari etc page_request = new XMLHttpRequest() else return false var pageurl=setting.contentsource[1] page_request.onreadystatechange=function(){ featuredcontentslider.ajaxpopulate(page_request, setting) } document.getElementById(setting.id).innerHTML=this.ajaxloadingmsg var bustcache=(!this.bustajaxcache)? "" : (pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime() page_request.open('GET', pageurl+bustcache, true) page_request.send(null) }, ajaxpopulate:function(page_request, setting){ if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){ document.getElementById(setting.id).innerHTML=page_request.responseText this.buildpaginate(setting) } }, buildcontentdivs:function(setting){ var alldivs=document.getElementById(setting.id).getElementsByTagName("div") for (var i=0; i<alldivs.length; i++){ if (this.css(alldivs[i], "contentdiv", "check")){ //check for DIVs with class "contentdiv" setting.contentdivs.push(alldivs[i]) alldivs[i].style.display="none" //collapse all content DIVs to begin with } } }, buildpaginate:function(setting){ this.buildcontentdivs(setting) var sliderdiv=document.getElementById(setting.id) var pdiv=document.getElementById("paginate-"+setting.id) var phtml="" var toc=setting.toc var nextprev=setting.nextprev if (typeof toc=="string" && toc!="markup" || typeof toc=="object"){ for (var i=1; i<=setting.contentdivs.length; i++){ phtml+='<a href="#'+i+'" class="toc">'+(typeof toc=="string"? toc.replace(/#increment/, i) : toc[i-1])+'</a> ' } phtml=(nextprev[0]!=''? '<a href="#prev" class="prev">'+nextprev[0]+'</a> ' : '') + phtml + (nextprev[1]!=''? '<a href="#next" class="next">'+nextprev[1]+'</a>' : '') pdiv.innerHTML=phtml } var pdivlinks=pdiv.getElementsByTagName("a") var toclinkscount=0 //var to keep track of actual # of toc links for (var i=0; i<pdivlinks.length; i++){ if (this.css(pdivlinks[i], "toc", "check")){ if (toclinkscount>setting.contentdivs.length-1){ //if this toc link is out of range (user defined more toc links then there are contents) pdivlinks[i].style.display="none" //hide this toc link continue } pdivlinks[i].setAttribute("rel", ++toclinkscount) //store page number inside toc link pdivlinks[i][setting.revealtype]=function(){ featuredcontentslider.turnpage(setting, this.getAttribute("rel")) return false } setting.toclinks.push(pdivlinks[i]) } else if (this.css(pdivlinks[i], "prev", "check") || this.css(pdivlinks[i], "next", "check")){ //check for links with class "prev" or "next" pdivlinks[i].onclick=function(){ featuredcontentslider.turnpage(setting, this.className) return false } } } this.turnpage(setting, setting.currentpage, true) if (setting.autorotate[0]){ //if auto rotate enabled pdiv[setting.revealtype]=function(){ featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id]) } sliderdiv["onclick"]=function(){ //stop content slider when slides themselves are clicked on featuredcontentslider.cleartimer(setting, window["fcsautorun"+setting.id]) } setting.autorotate[1]=setting.autorotate[1]+(1/setting.enablefade[1]*50) //add time to run fade animation (roughly) to delay between rotation this.autorotate(setting) } }, urlparamselect:function(fcsid){ var result=window.location.search.match(new RegExp(fcsid+"=(\\d+)", "i")) //check for "?featuredcontentsliderid=2" in URL return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index }, turnpage:function(setting, thepage, autocall){ var currentpage=setting.currentpage //current page # before change var totalpages=setting.contentdivs.length var turntopage=(/prev/i.test(thepage))? currentpage-1 : (/next/i.test(thepage))? currentpage+1 : parseInt(thepage) turntopage=(turntopage<1)? totalpages : (turntopage>totalpages)? 1 : turntopage //test for out of bound and adjust if (turntopage==setting.currentpage && typeof autocall=="undefined") //if a pagination link is clicked on repeatedly return setting.currentpage=turntopage setting.contentdivs[turntopage-1].style.zIndex=++setting.topzindex this.cleartimer(setting, window["fcsfade"+setting.id]) setting.cacheprevpage=setting.prevpage if (setting.enablefade[0]==true){ setting.curopacity=0 this.fadeup(setting) } if (setting.enablefade[0]==false){ //if fade is disabled, fire onChange event immediately (verus after fade is complete) setting.contentdivs[setting.prevpage-1].style.display="none" //collapse last content div shown (it was set to "block") setting.onChange(setting.prevpage, setting.currentpage) } setting.contentdivs[turntopage-1].style.visibility="visible" setting.contentdivs[turntopage-1].style.display="block" if (setting.prevpage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted) this.css(setting.toclinks[setting.prevpage-1], "selected", "remove") if (turntopage<=setting.toclinks.length) //make sure pagination link exists (may not if manually defined via "markup", and user omitted) this.css(setting.toclinks[turntopage-1], "selected", "add") setting.prevpage=turntopage if (this.enablepersist) this.setCookie("fcspersist"+setting.id, turntopage) }, setopacity:function(setting, value){ //Sets the opacity of targetobject based on the passed in value setting (0 to 1 and in between) var targetobject=setting.contentdivs[setting.currentpage-1] if (targetobject.filters && targetobject.filters[0]){ //IE syntax if (typeof targetobject.filters[0].opacity=="number") //IE6 targetobject.filters[0].opacity=value*100 else //IE 5.5 targetobject.style.filter="alpha(opacity="+value*100+")" } else if (typeof targetobject.style.MozOpacity!="undefined") //Old Mozilla syntax targetobject.style.MozOpacity=value else if (typeof targetobject.style.opacity!="undefined") //Standard opacity syntax targetobject.style.opacity=value setting.curopacity=value }, fadeup:function(setting){ if (setting.curopacity<1){ this.setopacity(setting, setting.curopacity+setting.enablefade[1]) window["fcsfade"+setting.id]=setTimeout(function(){featuredcontentslider.fadeup(setting)}, 50) } else{ //when fade is complete if (setting.cacheprevpage!=setting.currentpage) //if previous content isn't the same as the current shown div (happens the first time the page loads/ script is run) setting.contentdivs[setting.cacheprevpage-1].style.display="none" //collapse last content div shown (it was set to "block") setting.onChange(setting.cacheprevpage, setting.currentpage) } }, cleartimer:function(setting, timervar){ if (typeof timervar!="undefined"){ clearTimeout(timervar) clearInterval(timervar) if (setting.cacheprevpage!=setting.currentpage){ //if previous content isn't the same as the current shown div setting.contentdivs[setting.cacheprevpage-1].style.display="none" } } }, css:function(el, targetclass, action){ var needle=new RegExp("(^|\\s+)"+targetclass+"($|\\s+)", "ig") if (action=="check") return needle.test(el.className) else if (action=="remove") el.className=el.className.replace(needle, "") else if (action=="add") el.className+=" "+targetclass }, autorotate:function(setting){ window["fcsautorun"+setting.id]=setInterval(function(){featuredcontentslider.turnpage(setting, "next")}, setting.autorotate[1]) }, getCookie:function(Name){ var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair if (document.cookie.match(re)) //if cookie found return document.cookie.match(re)[0].split("=")[1] //return its value return null }, setCookie:function(name, value){ document.cookie = name+"="+value }, init:function(setting){ var persistedpage=this.getCookie("fcspersist"+setting.id) || 1 var urlselectedpage=this.urlparamselect(setting.id) //returns null or index from: mypage.htm?featuredcontentsliderid=index this.settingcaches[setting.id]=setting //cache "setting" object setting.contentdivs=[] setting.toclinks=[] setting.topzindex=0 setting.currentpage=urlselectedpage || ((this.enablepersist)? persistedpage : 1) setting.prevpage=setting.currentpage setting.revealtype="on"+(setting.revealtype || "click") setting.curopacity=0 setting.onChange=setting.onChange || function(){} if (setting.contentsource[0]=="inline") this.buildpaginate(setting) if (setting.contentsource[0]=="ajax") this.ajaxconnect(setting) } } as far as i can see, the parts of the code which are about the cookies are labeled "enablepersist" thanks guys I have been looking around for a while on google and have come accross a few things but still am unable to find the exact codes. I am trying to have a page setup so that when the user clicks a button it will add preset text to a form box and keep the chronological order of buttons that are clicked. This is going to be used for my ambulance service to assist dispatch so basically i am looking for preset buttons that the dispatcher can click disp. and have the dispatch and time added to a list in the form box that can later be copied and emailed to our cell phones. Thanks for any help. My code is working pretty well, except I have an issue validating. I think it may be to do with when there is an empty string. I know that NaN is Not a Number, but the only issue I can find with my code is when I input a non-digit such as "k" for example. And because I have put some code in to reload the page when it does not validate, when it refreshes it has 2 popup boxes. Thanks for taking the time to read my post Code: <html> <head> <title>Sound Travel Calculator</title> <script type="text/javascript"> // Setting our variables based on user input var hours = 0; var mins = 0; var m_per_secs = 340; alert("Speed of Sound \n\nAt Sea Level Sound Travels At 340 Metres Per Second \n\nIf You Would Like To Know How Far Sound Will Travel In A Given Time, Click OK"); hours = prompt("Please Enter Hours (If less than 1 hour, just type 0)"); mins = prompt("Please Enter Minutes"); // Validating input for a number less than zero or an not a number if ((isNaN(hours)) || (hours < 0) || (isNaN(mins)) || (mins < 0)) { alert("Please enter a numeric value, zero or greater"); window.location.reload(true); } // if there is no input, the value is set to zero if (hours =="") { hours = 0; } if (mins =="") { mins = 0; } // Calculations dist = (((parseFloat(hours)) * 60 * 60) + (parseFloat(mins * 60)) * parseFloat(m_per_secs) / 1000) // Output our calculation alert("The Distance of Sound Travelled is " + (dist) + " Kilometres"); </script> </head> <body> </body> </html> AC_ActiveX.js & AC_RunActiveContent.js is for java app that detect my client mac address I have java application running on my computer. I've tested on several pc, sometimes it detect the mac address, but sometimes nothing came out. In create_users.php, somehow im not able to store the mac address into a variable..( var mac = getMacAddress(); ) 1) Are my java coding would run on every pc? 2) I'm able to print out the mac address with "document.write(getMacAddress());" but why isit having stored in the variable is an issue? 3) which explorer would be the best to have the java running? IE/FF/Opera? create_users.php PHP Code: <script src="Scripts/AC_ActiveX.js" type="text/javascript"></script> <script src="Scripts/AC_RunActiveContent.js" type="text/javascript"></script> <!--[if !IE]> Firefox and others will use outer object --> <embed type="application/x-java-applet" name="macaddressapplet" width="0" height="0" code="MacAddressApplet" archive="macaddressapplet.jar" pluginspage="http://java.sun.com/javase/downloads/index.jsp" style="position:absolute; top:-1000px; left:-1000px;"> <noembed> <!--<![endif]--> <!----> <script type="text/javascript"> AC_AX_RunContent( 'classid','clsid:CAFEEFAC-0016-0000-FFFF-ABCDEFFEDCBA','type','application/x-java-applet','name','macaddressapplet','style','position:absolute; top:-1000px; left:-1000px;','code','MacAddressApplet','archive','macaddressapplet.jar','mayscript','true','scriptable','true','width','0','height','0' ); //end AC code </script><noscript><object classid="clsid:CAFEEFAC-0016-0000-FFFF-ABCDEFFEDCBA" type="application/x-java-applet" name="macaddressapplet" style="position:absolute; top:-1000px; left:-1000px;" > <param name="code" value="MacAddressApplet"> <param name="archive" value="macaddressapplet.jar" > <param name="mayscript" value="true"> <param name="scriptable" value="true"> <param name="width" value="0"> <param name="height" value="0"> </object></noscript> <!--[if !IE]> Firefox and others will use outer object --> </noembed> </embed> <script> function getMacAddress(){ document.macaddressapplet.setSep( "-" ); return (document.macaddressapplet.getMacAddress()); } var mac = getMacAddress(); </script> AC_ActiveX.js Code: function AC_AX_RunContent(){ var ret = AC_AX_GetArgs(arguments); AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs); } function AC_AX_GetArgs(args){ var ret = new Object(); ret.embedAttrs = new Object(); ret.params = new Object(); ret.objAttrs = new Object(); for (var i=0; i < args.length; i=i+2){ var currArg = args[i].toLowerCase(); switch (currArg){ case "pluginspage": case "type": ret.embedAttrs[args[i]] = args[i+1]; break; case "data": case "codebase": case "classid": case "id": case "onafterupdate": case "onbeforeupdate": case "onblur": case "oncellchange": case "onclick": case "ondblClick": case "ondrag": case "ondragend": case "ondragenter": case "ondragleave": case "ondragover": case "ondrop": case "onfinish": case "onfocus": case "onhelp": case "onmousedown": case "onmouseup": case "onmouseover": case "onmousemove": case "onmouseout": case "onkeypress": case "onkeydown": case "onkeyup": case "onload": case "onlosecapture": case "onpropertychange": case "onreadystatechange": case "onrowsdelete": case "onrowenter": case "onrowexit": case "onrowsinserted": case "onstart": case "onscroll": case "onbeforeeditfocus": case "onactivate": case "onbeforedeactivate": case "ondeactivate": ret.objAttrs[args[i]] = args[i+1]; break; case "width": case "height": case "align": case "vspace": case "hspace": case "class": case "title": case "accesskey": case "name": case "tabindex": ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1]; break; default: ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1]; } } return ret; } AC_RunActiveContent.js Code: var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false; var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false; function ControlVersion() { var version; var axo; var e; // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry try { // version will be set for 7.X or greater players axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); version = axo.GetVariable("$version"); } catch (e) { } if (!version) { try { // version will be set for 6.X players only axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); // installed player is some revision of 6.0 // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29, // so we have to be careful. // default to the first public version version = "WIN 6,0,21,0"; // throws if AllowScripAccess does not exist (introduced in 6.0r47) axo.AllowScriptAccess = "always"; // safe to call for 6.0r47 or greater version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 4.X or 5.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 3.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = "WIN 3,0,18,0"; } catch (e) { } } if (!version) { try { // version will be set for 2.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); version = "WIN 2,0,0,11"; } catch (e) { version = -1; } } return version; } // JavaScript helper required to detect Flash Player PlugIn version information function GetSwfVer(){ // NS/Opera version >= 3 check for Flash plugin in plugin array var flashVer = -1; if (navigator.plugins != null && navigator.plugins.length > 0) { if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) { var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description; var descArray = flashDescription.split(" "); var tempArrayMajor = descArray[2].split("."); var versionMajor = tempArrayMajor[0]; var versionMinor = tempArrayMajor[1]; var versionRevision = descArray[3]; if (versionRevision == "") { versionRevision = descArray[4]; } if (versionRevision[0] == "d") { versionRevision = versionRevision.substring(1); } else if (versionRevision[0] == "r") { versionRevision = versionRevision.substring(1); if (versionRevision.indexOf("d") > 0) { versionRevision = versionRevision.substring(0, versionRevision.indexOf("d")); } } var flashVer = versionMajor + "." + versionMinor + "." + versionRevision; } } // MSN/WebTV 2.6 supports Flash 4 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4; // WebTV 2.5 supports Flash 3 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3; // older WebTV supports Flash 2 else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2; else if ( isIE && isWin && !isOpera ) { flashVer = ControlVersion(); } return flashVer; } // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) { versionStr = GetSwfVer(); if (versionStr == -1 ) { return false; } else if (versionStr != 0) { if(isIE && isWin && !isOpera) { // Given "WIN 2,0,0,11" tempArray = versionStr.split(" "); // ["WIN", "2,0,0,11"] tempString = tempArray[1]; // "2,0,0,11" versionArray = tempString.split(","); // ['2', '0', '0', '11'] } else { versionArray = versionStr.split("."); } var versionMajor = versionArray[0]; var versionMinor = versionArray[1]; var versionRevision = versionArray[2]; // is the major.revision >= requested major.revision AND the minor version >= requested minor if (versionMajor > parseFloat(reqMajorVer)) { return true; } else if (versionMajor == parseFloat(reqMajorVer)) { if (versionMinor > parseFloat(reqMinorVer)) return true; else if (versionMinor == parseFloat(reqMinorVer)) { if (versionRevision >= parseFloat(reqRevision)) return true; } } return false; } } function AC_AddExtension(src, ext) { if (src.indexOf('?') != -1) return src.replace(/\?/, ext+'?'); else return src + ext; } function AC_Generateobj(objAttrs, params, embedAttrs) { var str = ''; if (isIE && isWin && !isOpera) { str += '<object '; for (var i in objAttrs) { str += i + '="' + objAttrs[i] + '" '; } str += '>'; for (var i in params) { str += '<param name="' + i + '" value="' + params[i] + '" /> '; } str += '</object>'; } else { str += '<embed '; for (var i in embedAttrs) { str += i + '="' + embedAttrs[i] + '" '; } str += '> </embed>'; } document.write(str); } function AC_FL_RunContent(){ var ret = AC_GetArgs ( arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" , "application/x-shockwave-flash" ); AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs); } function AC_SW_RunContent(){ var ret = AC_GetArgs ( arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000" , null ); AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs); } function AC_GetArgs(args, ext, srcParamName, classid, mimeType){ var ret = new Object(); ret.embedAttrs = new Object(); ret.params = new Object(); ret.objAttrs = new Object(); for (var i=0; i < args.length; i=i+2){ var currArg = args[i].toLowerCase(); switch (currArg){ case "classid": break; case "pluginspage": ret.embedAttrs[args[i]] = args[i+1]; break; case "src": case "movie": args[i+1] = AC_AddExtension(args[i+1], ext); ret.embedAttrs["src"] = args[i+1]; ret.params[srcParamName] = args[i+1]; break; case "onafterupdate": case "onbeforeupdate": case "onblur": case "oncellchange": case "onclick": case "ondblClick": case "ondrag": case "ondragend": case "ondragenter": case "ondragleave": case "ondragover": case "ondrop": case "onfinish": case "onfocus": case "onhelp": case "onmousedown": case "onmouseup": case "onmouseover": case "onmousemove": case "onmouseout": case "onkeypress": case "onkeydown": case "onkeyup": case "onload": case "onlosecapture": case "onpropertychange": case "onreadystatechange": case "onrowsdelete": case "onrowenter": case "onrowexit": case "onrowsinserted": case "onstart": case "onscroll": case "onbeforeeditfocus": case "onactivate": case "onbeforedeactivate": case "ondeactivate": case "type": case "codebase": case "id": ret.objAttrs[args[i]] = args[i+1]; break; case "width": case "height": case "align": case "vspace": case "hspace": case "class": case "title": case "accesskey": case "name": case "tabindex": ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1]; break; default: ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1]; } } ret.objAttrs["classid"] = classid; if (mimeType) ret.embedAttrs["type"] = mimeType; return ret; } The code I commeted out dosen't work I want to check if its null and if so alert them. { // PART 2: YOUR CODE STARTS AFTER THIS LINE correctAnswer = Math.floor((Math.random() * 100) + 1); // For testing purposes. alert("Testing purposes, correct answer is: " + correctAnswer); var number = 0; //// Calculations //if (isNaN(number) = true) { // alert("Thats not a number"); //} //document.write(number); while (number != correctAnswer) { number = prompt("Wrong Number, guess again."); number = Number(number); if (number < correctAnswer) { document.writeln("Small guess: " + number); } if (number > correctAnswer) { document.writeln("Large guess: " + number); } if (number == correctAnswer) { document.writeln("Correct guess: " + number); } } } index.html Code: <html> <head> <title>:: wtmp</title> </head> <body> <p>Welcome to my page</p> <script type="text/javascript" src="file.js"></script> </body> </html> file.js Code: function one(p1, p2) { var j_text=p1+" "+p2; return j_text; } function two() { var rslt=one("Hi", "there!"); } document.write(rslt); var mainscrpt=one("Hello", "world!"); window.alert(mainscrpt); I would like to compare my work to the work of others, can you please solve this and post your result? Declare an 8 x 8 matrix and an array of length 22. 1.- Populate the matrix. 2.- Copy the elements of the first row of the matrix, the anti-diagonal, and the last row of the matrix into the array, to form a Z shape. 3.- Sort the array. 4.- Assuming that the data in the arrays are grades, compute the average of the grades stored in the even locations of the array. 5.- Copy the array back into the matrix.(back into the Z) 6.- Print out the matrix values. I just started learning JavaScript. I'm sure it's something really simple but I cannot figure out what is missing from my code. No matter what year I enter into the text box, I keep getting "The year you entered, 2080393, is a leap year." It's not returning false...ever. Can someone please tell me what I'm doing wrong so I can stop pulling my hair out? Thanks! <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Is It A Leap Year?</title> <script type="text/javascript"> /* <![CDATA[ */ function isLeapYear(year) { year = parseInt(year); var leapYear = true; var remainder = 0; if(isDivisibleBy(year, 4)) { leapYear = true; } if(isDivisibleBy(year, 100)) { leapYear = false; } if(isDivisibleBy(year, 400)) { leapYear = true; } if(leapYear) { window.alert("The year you entered, " + year + ", is a leap year."); } else { window.alert("The year you entered, " + year + ", is not a leap year."); } } function isDivisibleBy(year, divisor) { var remainder = 0; remainder = year%divisor; if(remainder == 0) { return true; } else { return false; } } /* ]]> */ </script> </head> <body> <form action="" id="GetLeapYear"> <p><strong>Is It a Leap Year?</strong></p> <p><strong>Enter a valid 4-digit year below to find out!</strong><br /></p> <p> <input type="text" name="year" size="20" style="color: black; border-style: solid; border-color: inherit; border-width: medium; background-color: Transparent" value="" /> <input type="button" value="Leap Year?" onclick="isLeapYear(document.getElementById('GetLeapYear').year.value);" /> </p> </form> </body> Here's the basic concept, its somewhat of a counter, and I think javascripts the way to go... Basically I'm looking to generate a running number... x + 11 = print the number The tricky part is, I need it to never stop, somewhat like a timer (example http://www.hashemian.com/tools/javascript-countdown.htm) but not a timer... Think the tally mark on McDonald's 99 billion served.. Any suggestions or ideas? Simple random pic script that I found on the some other forum (I forget what it was) [CODE]var aryimages = new Array('images/pic/01.jpg', 'images/pic/37.jpg', 'images/pic/02.jpg', 'images/pic/family/08.jpg','images/pic/08.jpg', 'images/pic/food/03.jpg'); randompic.src = aryimages[Math.floor(Math.random() * aryimages.length)]; [CODE] code anchors to HTML markup [CODE]<img name="randompic" id="bg" />[CODE] it is working perfectly for Safari and Chrome. Nothing is showing for FF. Any suggestions appreciated. Hi... i have this code: <script type='text/javascript'> cookie_name = GetCookie("href_location"); if(cookie_name){ alert("Cookie found, redirecting to stored cookie."); document.location.href=cookie_name; } </script> I will like to create a iframe using the info from the "cookie_name" value <iframe name="FRAME1" src="cookie_name" width="350" height="320" frameborder="0" scrolling="auto"></iframe> I have a script that set a cookie with the value of a chosed website, what i need now is to create an iframe with that value. Any help will be apriciated. Sorry for my poor enlish Basically, I have a Simon Says game with very simple functions but I added an image map with buttons that I now want to use, rather than a table with images as buttons. The problem is, now I can't get the game to work with the image map. Can anyone help me?
Hi everyone, I've been coding Perl for quite some time, but I'm new to Javascript and can't quite figure this out. I want to call a Javascript function that is sent to the browser via a perl script. When I hard code the string "Fargo" into the code it works just fine, when I pass the word Fargo via a variable the script will not call the function what so ever. Is it possible to call a javascript function via a Perl script with Perl providing all the necessary data? Here is my code: #!/usr/local/bin/perl use CGI qw(:all); use CGI::Carp qw(fatalsToBrowser); use Cwd; print header; print "top<br><br>"; $data = "fargo"; print <<html; <html><head></head>my heading is here<br><body></body> <script type="text/javascript"> function testz(inbound) { document.write("im in ", inbound); } //the script will only work if I uncomment the line below and comment out two lines below //var data1="fargo"; var data1 = $data; testz(data1); </script> </html> html Thanks to everyone in advance for your help. can some please tell me what this line does... Code: <div onClick="getElementById('tInfo').onclick();"> Hello, What I need is a simple service area, zip code validation form that redirects to a certain URL when a valid zip code is submitted and a different URL when an invalid zip code is submitted. I found a form script example that works well with only a single zip code. My problem is I can't figure out how to modify it so that multiple zip codes are valid. Here is the head part. 60016 is one of about 50 valid zip codes I need the form to accept as valid - [code] <script> var correctCode = "60016"; function validateCode() { var code = document.getElementById("codeTextBox").value; if (code == correctCode) { window.location.href = "/ggc/test1"; } else { window.location.href = "/ggc/test2"; } } </script> [code] Here is the body part - [code] Please enter your zip code: <input type="text" name="codeTextBox" id="codeTextBox" /> <input type="submit" name="Submit" value="Submit" onclick="validateCode()" /> [code] So frustrating that lately I've been having trouble with the simplest of code, and this is about as simple as it gets. Matched it up with every similiar example I can find both in books and on the net, and it seems to be perfectly valid code, but when I run it, nothing. :S 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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <script language="javascript" type="text/javascript"> function favouriteColour() { var index = document.getElementById("select1").options[document.getElementById("select1").selectedIndex].value; document.getElementById = "Your favourite colour is " + index; } </script> </head> <body> <select id="select1"> <option></option> <option id="black" onchange="favouriteColour()">Black</option> <option id="white" onchange="favouriteColour()">White</option> <div id="favcolour"></div> <option> </select> </body> </html> Thanks in advance. Hi there, I'm not a js coder but needed to cobble something together for a simple IE7 "sniffing" task. It's basically taken from a helpful poster over at http://css-tricks.com/snippets/javas...rnet-explorer/ I'm pretty sure that what I've done is as inelegant as hell!! Although it works, I'd be grateful if someone could show me how to tidy things up. Many thanks Code: $(function(){ if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x; var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number if (ieversion<=7) $(".tooltipthumb").tipTip({attribute: "title", defaultPosition: "top", fadeIn: 200, delay: 0}); else if (ieversion>=8) $(".tooltipthumb").tipTip({attribute: "title", edgeOffset: 130, defaultPosition: "top", fadeIn: 200, delay: 0}); } else { $(".tooltipthumb").tipTip({attribute: "title", edgeOffset: 130, defaultPosition: "top", fadeIn: 200, delay: 0}); } }); $(function(){ $(".tooltip").tipTip({attribute: "title", fadeIn: 200, delay: 0}); }); $(function(){ $(".tooltip_small_thumb").tipTip({attribute: "title", edgeOffset: 90, defaultPosition: "top", fadeIn: 200, delay: 0}); }); $(function(){ if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x; var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number if (ieversion<=7) $(".tooltip_small_thumb").tipTip({attribute: "title", defaultPosition: "top", fadeIn: 200, delay: 0}); else if (ieversion>=8) $(".tooltip_small_thumb").tipTip({attribute: "title", edgeOffset: 90, defaultPosition: "top", fadeIn: 200, delay: 0}); } else { $(".tooltip_small_thumb").tipTip({attribute: "title", edgeOffset: 90, defaultPosition: "top", fadeIn: 200, delay: 0}); } }); |