JavaScript - Can Anyone Find A Bug In This Or A Way To Improve It ?
function textSize(updown) { var size = Number(readCookie('user-font-size')); if (size == 0) { size = 12; // No Cookie, Set A Default Size Of 12px } size = size + Number(updown); // Adjust The Current Size if (size > 20) { size = 20; } // Stop At 13 if (size < 12) { size = 12; } // Stop At 10 writeCookie('user-font-size', size, 12); // Update The Cookie document.body.style.fontSize = size + 'px'; // Set The Users Text Size } function writeCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = '; expires=' + date.toGMTString(); } else { expires = ''; } document.cookie = name + '=' + value + expires; } function readCookie(name) { name += '='; var cs = document.cookie.split(';'); for (var i = 0; i < cs.length; i++) { var c = cs[i]; while (c.charAt(0) == ' ') { c = c.substring(1, c.length); } if (c.indexOf(name) == 0) { //-----------// return c.substring(name.length, c.length); // Gotcha // } //-----------// } //------------// return null; // Failed // } //------------ <img id="plustext" class="zoom-in" alt="Increase text size" src="Zoom-In-icon.png" onclick="textSize (2);" style="cursorointer" /> <img id="minustext" class="zoom-out" alt="Decrease text size" src="Zoom-Out-icon.png" onclick="textSize (-2);" style="cursorointer" /> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vel fringilla arcu. Cras ullamcorper nunc ac sapien gravida ultrices. Curabitur mollis consectetur elit non tempus. Duis blandit luctus feugiat. Nullam eget tellus at quam dapibus tempus in scelerisque ligula. Phasellus turpis ante, tincidunt at aliquam vel, luctus vitae leo. Suspendisse dignissim vehicula est, ac dapibus justo pellentesque eu. </p> cheers hope thats enough code Ant. Similar TutorialsWell I made a calculator in JavaScript but I think it's kind of a dumb downed version. Ignore my html styling and tags I just threw it together quickly and wanted to avoid using a CSS. I am beginning Object Oriented Programming with JavaScript could anyone give an example of applying that on the calculator? Quote: <html> <head> <script type="text/javascript"> function mult(){ var a = document.getElementById("yal").value; var b = document.getElementById("fal").value; var h=a*b; document.getElementById("mal").innerHTML=h; } function adder(){ var a = document.getElementById("dig").value; var b = document.getElementById("yig").value; var h= a*1+b*1; document.getElementById("tig").innerHTML=h; } function divid(){ var a = document.getElementById("hos").value; var b = document.getElementById("mos").value; var h= a*1/b*1; document.getElementById("tos").innerHTML=h; } function subt(){ var a = document.getElementById("mat").value; var b = document.getElementById("sat").value; var h= a*1-b*1; document.getElementById("cat").innerHTML=h; } </script> </head> <body> <div style="float:left;"> <h3>adding</h3> <input type="text" id="dig" > <br /> <input type="text" id="yig" > <br /> <input type="button" value="submit" onclick="adder()"> <p id="tig"></p> </div> <div style="float:left;"> <h3>multiplyer</h3> <input type="text" id="fal" > <br /> <input type="text" id="yal" > <br /> <input type="button" value="submit" onclick="mult()"> <p id="mal"></p> </div> <div style="float:left;"> <h3>divider</h3> <input type="text" id="hos" > <br /> <input type="text" id="mos" > <br /> <input type="button" value="submit" onclick="divid()"> <p id="tos"></p> </div> <div style="float:left;"> <h3>subtractor</h3> <input type="text" id="mat" > <br /> <input type="text" id="sat" > <br /> <input type="button" value="submit" onclick="subt()"> <p id="cat"></p> </div> </body> </html> Hello, I was wondering if there was a way to make the code below more efficient. Code: var foo = process(bar); if( foo === false ) { alert('a problem occured'); } In PHP you would do something like: PHP Code: if(!$foo = process($bar)) { echo('a problem occured'); } I have a Javascript Dropdown Menu ( Code Below ), which is working nicely, but I want to improve it, but need help to so so. When you hover over one of the dropdown's, it shows links to a page, I would like those links to also show more to the right... For example; 1). Hover over 'Community', which shows the list of links below. 2). Hover over 'Connect With Us', will show another list to the right with links such as; 'Facebook', 'YouTube'...... The HTML Code; Code: <body> <div class="chromestyle" id="chromemenu"> <ul> <li><a href="#">Home</a></li> <li><a href="#" rel="dropmenu1">Dropdown One</a></li> <li><a href="#" rel="dropmenu2">Dropdown 2s</a></li> <li><a href="#" rel="dropmenu3">Dropdown 3</a></li> </ul> </div> <!--1st drop down menu --> <div id="dropmenu1" class="dropmenudiv"> <a href="#">Link One</a> <a href="#">Link Two</a> <a href="#">Link Three</a> <a href="#">Link Four</a> </div> <!--2nd drop down menu --> <div id="dropmenu2" class="dropmenudiv" style="width: 150px;"> <a href="#">Link One</a> <a href="#">Limk Two</a> <a href="#">Link Three</a> </div> <!--3rd drop down menu --> <div id="dropmenu3" class="dropmenudiv" style="width: 150px;"> <a href="#">Link One</a> <a href="#">Link Two</a> <a href="#">Link Three</a> </div> <script type="text/javascript"> cssdropdown.startchrome("chromemenu") </script> </body> The CSS Code; Code: .chromestyle{ width: 1020px; font-weight: bold; } .chromestyle:after{ /*Add margin between menu and rest of content in Firefox*/ content: "."; display: block; height: 0; clear: both; visibility: hidden; } .chromestyle ul{ border: 1px solid #BBB; width: 100%; background: url(chromebg4.gif) center center repeat-x; /*THEME CHANGE HERE*/ padding: 4px 0; margin: 0; text-align: left; /*set value to "left", "center", or "right"*/ } .chromestyle ul li{ display: inline; } .chromestyle ul li a{ color: #494949; padding: 4px 7px; margin: 0; text-decoration: none; border-right: 1px solid #E8BEBE; /*THEME CHANGE HERE*/ } .chromestyle ul li a:hover, .chromestyle ul li a.selected{ /*script dynamically adds a class of "selected" to the current active menu item*/ background: url(chromebg4-over.gif) center center repeat-x; /*THEME CHANGE HERE*/ } /* ######### Style for Drop Down Menu ######### */ .dropmenudiv{ position:absolute; top: 0; border: 1px solid #E8BEBE; /*THEME CHANGE HERE*/ border-bottom-width: 0; font:normal 12px Verdana; line-height:18px; z-index:100; background-color: white; width: 200px; visibility: hidden; } .dropmenudiv a{ width: 100%; display: block; text-indent: 3px; border: 1px solid #E8BEBE; /*THEME CHANGE HERE*/ padding: 2px 0; text-decoration: none; font-weight: bold; color: black; } .dropmenudiv a:hover{ /*THEME CHANGE HERE*/ background-color: #FFECEC; } The Javascript Code; Code: var cssdropdown={ disappeardelay: 250, //set delay in miliseconds before menu disappears onmouseout dropdownindicator: '<img src="down.gif" border="0" />', //specify full HTML to add to end of each menu item with a drop down menu enablereveal: [true, 5], //enable swipe effect? [true/false, steps (Number of animation steps. Integer between 1-20. Smaller=faster)] enableiframeshim: 1, //enable "iframe shim" in IE5.5 to IE7? (1=yes, 0=no) dropmenuobj: null, asscmenuitem: null, domsupport: document.all || document.getElementById, standardbody: null, iframeshimadded: false, revealtimers: {}, getposOffset:function(what, offsettype){ var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop; var parentEl=what.offsetParent; while (parentEl!=null){ totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop; parentEl=parentEl.offsetParent; } return totaloffset; }, 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" && !needle.test(el.className)) el.className+=" "+targetclass }, showmenu:function(dropmenu, e){ if (this.enablereveal[0]){ if (!dropmenu._trueheight || dropmenu._trueheight<10) dropmenu._trueheight=dropmenu.offsetHeight clearTimeout(this.revealtimers[dropmenu.id]) dropmenu.style.height=dropmenu._curheight=0 dropmenu.style.overflow="hidden" dropmenu.style.visibility="visible" this.revealtimers[dropmenu.id]=setInterval(function(){cssdropdown.revealmenu(dropmenu)}, 10) } else{ dropmenu.style.visibility="visible" } this.css(this.asscmenuitem, "selected", "add") }, revealmenu:function(dropmenu, dir){ var curH=dropmenu._curheight, maxH=dropmenu._trueheight, steps=this.enablereveal[1] if (curH<maxH){ var newH=Math.min(curH, maxH) dropmenu.style.height=newH+"px" dropmenu._curheight= newH + Math.round((maxH-newH)/steps) + 1 } else{ //if done revealing menu dropmenu.style.height="auto" dropmenu.style.overflow="hidden" clearInterval(this.revealtimers[dropmenu.id]) } }, clearbrowseredge:function(obj, whichedge){ var edgeoffset=0 if (whichedge=="rightedge"){ var windowedge=document.all && !window.opera? this.standardbody.scrollLeft+this.standardbody.clientWidth-15 : window.pageXOffset+window.innerWidth-15 var dropmenuW=this.dropmenuobj.offsetWidth if (windowedge-this.dropmenuobj.x < dropmenuW) //move menu to the left? edgeoffset=dropmenuW-obj.offsetWidth } else{ var topedge=document.all && !window.opera? this.standardbody.scrollTop : window.pageYOffset var windowedge=document.all && !window.opera? this.standardbody.scrollTop+this.standardbody.clientHeight-15 : window.pageYOffset+window.innerHeight-18 var dropmenuH=this.dropmenuobj._trueheight if (windowedge-this.dropmenuobj.y < dropmenuH){ //move up? edgeoffset=dropmenuH+obj.offsetHeight if ((this.dropmenuobj.y-topedge)<dropmenuH) //up no good either? edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge } } return edgeoffset }, dropit:function(obj, e, dropmenuID){ if (this.dropmenuobj!=null) //hide previous menu this.hidemenu() //hide menu this.clearhidemenu() this.dropmenuobj=document.getElementById(dropmenuID) //reference drop down menu this.asscmenuitem=obj //reference associated menu item this.showmenu(this.dropmenuobj, e) this.dropmenuobj.x=this.getposOffset(obj, "left") this.dropmenuobj.y=this.getposOffset(obj, "top") this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+"px" this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+1+"px" this.positionshim() //call iframe shim function }, positionshim:function(){ //display iframe shim function if (this.iframeshimadded){ if (this.dropmenuobj.style.visibility=="visible"){ this.shimobject.style.width=this.dropmenuobj.offsetWidth+"px" this.shimobject.style.height=this.dropmenuobj._trueheight+"px" this.shimobject.style.left=parseInt(this.dropmenuobj.style.left)+"px" this.shimobject.style.top=parseInt(this.dropmenuobj.style.top)+"px" this.shimobject.style.display="block" } } }, hideshim:function(){ if (this.iframeshimadded) this.shimobject.style.display='none' }, isContained:function(m, e){ var e=window.event || e var c=e.relatedTarget || ((e.type=="mouseover")? e.fromElement : e.toElement) while (c && c!=m)try {c=c.parentNode} catch(e){c=m} if (c==m) return true else return false }, dynamichide:function(m, e){ if (!this.isContained(m, e)){ this.delayhidemenu() } }, delayhidemenu:function(){ this.delayhide=setTimeout("cssdropdown.hidemenu()", this.disappeardelay) //hide menu }, hidemenu:function(){ this.css(this.asscmenuitem, "selected", "remove") this.dropmenuobj.style.visibility='hidden' this.dropmenuobj.style.left=this.dropmenuobj.style.top="-1000px" this.hideshim() }, clearhidemenu:function(){ if (this.delayhide!="undefined") clearTimeout(this.delayhide) }, addEvent:function(target, functionref, tasktype){ if (target.addEventListener) target.addEventListener(tasktype, functionref, false); else if (target.attachEvent) target.attachEvent('on'+tasktype, function(){return functionref.call(target, window.event)}); }, startchrome:function(){ if (!this.domsupport) return this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body for (var ids=0; ids<arguments.length; ids++){ var menuitems=document.getElementById(arguments[ids]).getElementsByTagName("a") for (var i=0; i<menuitems.length; i++){ if (menuitems[i].getAttribute("rel")){ var relvalue=menuitems[i].getAttribute("rel") var asscdropdownmenu=document.getElementById(relvalue) this.addEvent(asscdropdownmenu, function(){cssdropdown.clearhidemenu()}, "mouseover") this.addEvent(asscdropdownmenu, function(e){cssdropdown.dynamichide(this, e)}, "mouseout") this.addEvent(asscdropdownmenu, function(){cssdropdown.delayhidemenu()}, "click") try{ menuitems[i].innerHTML=menuitems[i].innerHTML+" "+this.dropdownindicator }catch(e){} this.addEvent(menuitems[i], function(e){ //show drop down menu when main menu items are mouse over-ed if (!cssdropdown.isContained(this, e)){ var evtobj=window.event || e cssdropdown.dropit(this, evtobj, this.getAttribute("rel")) } }, "mouseover") this.addEvent(menuitems[i], function(e){cssdropdown.dynamichide(this, e)}, "mouseout") //hide drop down menu when main menu items are mouse out this.addEvent(menuitems[i], function(){cssdropdown.delayhidemenu()}, "click") //hide drop down menu when main menu items are clicked on } } //end inner for } //end outer for if (this.enableiframeshim && document.all && !window.XDomainRequest && !this.iframeshimadded){ //enable iframe shim in IE5.5 thru IE7? document.write('<IFRAME id="iframeshim" src="about:blank" frameBorder="0" scrolling="no" style="left:0; top:0; position:absolute; display:none;z-index:90; background: transparent;"></IFRAME>') this.shimobject=document.getElementById("iframeshim") //reference iframe object this.shimobject.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)' this.iframeshimadded=true } } //end startchrome } Thank you in advance, Tim I am try to reduce the time taken to download my home page. I purchased a template and then just modified what I wanted. There is a script that calls 21 other scripts. I am told if I combined all this scripts into one or two scripts, my download time would go down. Help appreciated. Drachsi www.drachsi.com hi I need to find the average number in javascript. I have been working on it for a while but i am getting no where yes i am new to javascript and to be honest it is doing my blonde headed brain in. can someone please take a look at it and advise me on what i am doing wrong. it is the only bit of javascript that i have to do in the course but it carries a high mark of which i can not afford to lose Any way the question is : "Write code to calculate the average height and write it out in the browser window" Code: <HEAD> <TITLE> average </TITLE> <SCRIPT LANGUAGE = "JavaScript"> //Experimental results of Table 1 stored in arrays. var Height = [15,16,17,18,19]; var Number = [2,1,6,4,2]; //Part (ii). //Write code to declare and initialise new array to represent the third row of the table. var avg = new Array(5) var avg = ["60","80","187","180","114"] ; avg[0] = "60"; avg[1] = "80"; avg[2] = "187"; avg[3] = "180"; avg[4] = "114"; //Part (iv). //Write code to calculate the average height and write it out in the browser window. avg = 0; for (var count = 1; count <= 5; count = count + 1) Array.average = function(){ var avg = 0; for(var a = 0; a < this.length; a++){ avg += this[a]; } return avg / this.length; }; document.write('average height is ' +avg + '<br>'); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> sorry for my ignorance thanks in advance kelly XXXXX This is a function designed to return an array of all elements in "body" with a particular tag name and class name. It works fine up until the if (needles.length == 0); { line, according to my debugging. It seems to fail there though and I can't figure out why. It's probably just some noob error that I've missed but I can't for the life of me find it Thanks in advance for any help, it's greatly appreciated! Code: function getElementsByClassName(tagname, classname) { var haystack = document.getElementById('body').getElementsByTagName(tagname); var needles = []; var i; for (i in haystack) { if (haystack[i].hasClassName(classname)) { needles.push(haystack[i]); continue; } } if (needles.length == 0); { needles = 0; } return needles; } Hi All, I have the date in 2009-10-24 format.can anyone tell how can I get the day of any particular date entered by user. Thanks in advance... Hi, I've been trying to code a javascript fonction that uses Window.find and I'm having problems doing exactly what I want. I don't know much of java and I understand that it's not everyone who's willing to do all the work for me so I'm looking for a very kind person here I want it to find a specific string that won't change (so no use to prompt for it) in another existing page that would be loaded in a frame. When the string is found, a sound is played like an alarm. The entire thing should reload every like 5 minutes. That's the easy part. I'm having trouble with the "If found in the frame, play a sound part". I don't think it's pretty hard to do, but hey, I can't do it. As I said earlier, I understand I ask for someone to do the whole thing for me but I'm willing to pay by paypal for the service. Let's say... I don't know, ten bucks should do it. I think I've been clear with what I need but if not, please feel free to ask for more specifications. Thanks for your time. Hello. Please excuse my ignorance but I am not too clued up on javascript. Im hoping someone may be able to help me out here. I have managed to locate a script which will find text on a page, but I have a couple of requests. Firstly the script will only search up. I would like the search box to be at the top of a page but the only way to get it to work correctly is placing it at the bottom of the page. Secondly would some kind soul advise me how to place the script in an external file and then link to it. Thanks in advance. Hello, please tell me where can I find script visible on page www.frendzel.pl (Big picture changing every few second to another from the list on the left)
This is the script itself - no error messages are generated. Code: <script language="javascript" type="text/javascript"> function getXMLHTTPRequest() { try { req = new XMLHTTPRequest(); } catch(err1) { try { req = new ActiveXObject("Msxm12.XMLHTTP"); } catch(err2) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(err3) { req = false; } } } return req; } var http = getXMLHTTPRequest(); function getCattle(animal_id){ var myurl = 'find_cattle.php'; var CattleValue=animal_id; var modurl= myurl+"?d="+CattleValue; **************the alert returns the correct value from my selection and after than nothing, I never get my alert from the response portion alert("Looking For "+modurl); ******* http.open("GET", modurl, true); http.onreadystatechange=useHttpResponse; http.send(null); } function useHttpResponse(){ ************It never gets to this response alert("Made It To Response"); if (http.readyState == 4) { if(http.status == 200) { var ListValue = http.responseXML.getElementsByTagName("animal_id")[0]; document.getElementsById('cattle_data').innerHTML = animal_id.childNodes[0].nodeValue; } } } </script> thank you Hello, Below is the javascript I'm debugging (or trying to) but just can't see where the error is: The code should send a message "GOOODDD!!!" when the input box is empty (nothing typed in) and should send a message (BAAADD!!!) when a string of theee a's are typed in ("aaa"). The problem is that no matter what I type in the script ALWAYS sends me a "GOOODD!!" message. I guess it is a simple glitch but I just can't figure it out. I'd appreciate any help Thank You. Code: <script language="javascript" type="text/javascript"> <!-- function textCheck(that) { var mytext=document.getElementById("BLABLA") if (mytext == "aaa") alert("BAAAAADDDDD!!!!" + mytext.value); else alert(" GOOOODDDD!!!!" + mytext.value); } --> </script> </head> <body> <form id="form1" method="get" onsubmit="textCheck(this)" /> <input name="BLABLA" size="3" type="text"/> Input Data <br/><br/> <input name="Submit1" type="submit" value="submit" /> </body> </html> Hello, I have recently started a website which tells visitor's IP address, location and others details. I want to add some more functions to it. I found no way to detect visitors Internet Service Provider (ISP) using PHP. I would like to know if there is any way to do so in Javascript. Click the below link to view the site: Show IP Please help me ASAP. Regards, Wasif K. I am trying to do a title case project and can't figure out where I went wrong. Any help would be appreciated. <!DOCTYPE html> <html lang="en"> <head> <title>Title Case</title> <meta charset="utf-8"> <script type="text/javascript"> function titleCase() { var word = document.forms[0].string.value.split(" "); var cword = ""; for (var i = 0; i < word.length; i++) { cword = cword + word[i].substr(0, 1).toUpperCase() + word[i].substr(1).toLowerCase() + ((i < word.length - 1) ? " " : ""); } return cword; } </script> </head> <body> <h1>Title Case</h1> <form action="" method="get"> <p><input type="text" name="string" /> <input type="button" value="Convert to Title Case" onclick="titleCase()" /></p> </form> </body> </html> I have a problem finding Form in javascript. document.getElementById('MyForm'); return "HTMLUnknownElement". But if I add a dummy form previous for the one I actually want to find, then: document.getElementById('DummyForm'); returns "HTMLUnknownElement", and then document.getElementById('MyForm'); Returns "HTMLFormElement", that is what need. But this unknown element, the dummy form creates a lot of other problems with my site so this solution is no good for me. Why cant I find my Form? Thanks. Hi All, Just a quick question! Is it possible to have a text box input searching for the entered text on another webpage in the same way Find In Page would do? I have a webpage that I want users to input an item, and that this will open the targeted webpage and bring you to (and highlight) the matched item(s) like find in page does. Is this possible or is the easiest way to just make users open the link to the target page and just complete the find in page search there? Thanks Glen Hi all. Is it possible to command a find in page search from another html? I have a 'main page' and 'directory page' The directory page has find in page command on it, so if users can open the directory link from the main page and then search that page using the find in page search box. To speed this up, is there any way I can have a text box on my main page that when I enter text and submit that it carries across the text entry to the find in page box on the directory page and starts this search for me? I need to complete this using javascript so if this is possible I would great appreciate any help. Thanks I need some help finding a "find on page" script that will display the results in the middle of the page for IE. I have tried several different ones to no avail. The ones that work in all the browsers display the result in IE at the very bottom of the page. I am not very familiar with programing in Java and I am unable to modify any for my needs. The one I found that did work in IE didn't work in any other browsers. Please help, Thx
Hi Guys & Girls, I am looking for help with a technical issue, which my programmer can't find the answer to. My website has a demonstration facility which allows a client to enter their website which then in turn creates a video transparency overlaying their own website. The problem is some sites with Flash, overlay my transparency video so that you cant see my demo video. Any ideas please. Thanks Maximillion |