JavaScript - Keeping 4 Digits Below 1000..
hi, i'm trying to keep a copy of a variable at 4 digits.. this is what i came up with.. it's working but i'm only a noob, so i would very like to know is there any other simpler and/or elegant way to do this..
also i would appreciate it if you could point out any bad syntax or something.. Code: page = 100 function makeit4digits(){ page4digit = page if (page<10) { page4digit = "000"+ page } else if (page<100) { page4digit = "00"+ page } else if (page<1000) { page4digit = "0"+ page } } Similar TutorialsHi, well I have like 1000 images on the same page, unfortunately I can't use sprites on them, as the number of images increases continuously. So you can imagine it sends 1000 http requests, so it takes lots of time for the images to load plus it's not good experience for the visitors. I have seen one of the scripts named as Lazy Load, but I was thinking if there is more SMARTER WAY of loading images (good regarding SEO, loads images faster and is good for user experience). So, I was wondering if there is a way out to loading images in a better way? Please help I am a newbie and need some assistant. I'm trying to get a full date. In this script I want the user to be able to enter a date and get a 1000 day result a full (date) mm/dd/yyy. So far this give me the year only. I've tried so many ways. <script language="javascript"> var reply = prompt("Please enter the date you and your love begin dating (mm/dd/yyyy)", " "); var newstring = new String(reply); var arrTemp = new Array(); arrTemp = newstring.split("/"); var year = parseInt(arrTemp[arrTemp.length-1]); year += 3; alert("You begin dating your love in " + parseInt(arrTemp[arrTemp.length-1]) + "\nYou should be married before or in the year of " + year); </script> FireFox is throwing a DOM security error. And i don't really know why. i've used toDataURL() before, and it's never done this. Hopefully i can get this little app fixed, so that i can use it on my TabletPC for taking notes in class. The line of code that is throwing this error is: Code: var Note = document.getElementById("SketchPage").toDataURL(); here's the full error from the Error Console: Error: uncaught exception: [Exception... "Security error" code: "1000" nsresult: "0x805303e8 (NS_ERROR_DOM_SECURITY_ERR)" location: "file:///C:/SketchBook-Dev/SketchBook.js Line: 236"] here is the JS file: Code: var PenSize = "3"; var PenShape = "Circle"; var PenColor = "Black"; var LoadFile = ""; var UIstatus = "visible"; var CurrentNote = 0; var BGcolor = "#C7C1A3"; var DataPath = "\Data\\"; var ImageExtension = ".img"; var FileList = []; var SystemPath; var UIstatus = "visible"; var Server = "localhost"; var NxtNote = new Image(); document.onkeyup = ToggleUI; function Init() { // Get the System Path GetSystemPath("SketchBook.html"); // Load All Filenames of the DataPath directory into an array GetFileList(SystemPath + DataPath, FileList); //Load the first Note onto the canvas // if there are no notes in the directory, don't try to load anything if(FileList.length > 0) { var Source = LoadFromDisk(FileList[CurrentNote]); NxtNote.src = Source; // Load the image data onto the canvas var canvas = document.getElementById('SketchPage').getContext('2d'); canvas.drawImage(NxtNote , 0, 0); } } function HideOptions() { document.getElementById("Options").style.visibility = "hidden"; } function ToggleUI(e) { var KeyID = (window.event) ? event.keyCode : e.keyCode; var KeyValue = 18; // Use a key to hide the toolbars so that most of the screen is used for the UI if(KeyID == KeyValue) { if(UIstatus == "visible") { UIstatus = "hidden"; document.getElementById("UI").style.visibility = "hidden"; return; } if(UIstatus == "hidden") { UIstatus = "visible"; document.getElementById("UI").style.visibility = "visible"; } } } function ShowOptions() { document.getElementById("Options").style.visibility = "visible"; } function UpdatePenSize() { PenSize = document.getElementById('GetPenSize').value; } function UpdatePenShape() { PenShape = document.getElementById('GetPenShape').value; } function UpdatePenColor() { PenColor = document.getElementById('GetPenColor').value; } function Draw(element, event) { document.addEventListener("mousemove", PenHandler, true); document.addEventListener("mouseup", upHandler, true); event.stopPropagation(); event.preventDefault(); function PenHandler(event) { var x = event.clientX; var y = event.clientY; // mouse event goes here var canvas = document.getElementById("SketchPage"); var ctx = canvas.getContext("2d"); if (PenShape ="Circle") { // This draws a circle ctx.fillStyle = PenColor; ctx.beginPath(); ctx.arc(x, y, PenSize, 0, Math.PI*2, true); ctx.closePath(); ctx.fill(); } event.stopPropagation(); } function upHandler(event) { document.removeEventListener("mouseup", upHandler, true); document.removeEventListener("mousemove", PenHandler, true); event.stopPropagation(); } } function SaveNote() { // Get the current file name var FileName = SystemPath + DataPath + CurrentNote + ImageExtension; // Convert the Canvas Data into a Base64 encoded PNG image var Note = document.getElementById("SketchPage").toDataURL(); // Write the PNG file to the disk SaveToDisk(FileName, Note); } function NextNote(Direction) { if(Direction == "up") { // Display the previoius note CurrentNote--; // Make sure you don't incrimnet to a non-existant note if(CurrentNote <= 0) { CurrentNote = FileList.length; } var Source = LoadFromDisk(FileList[CurrentNote]); NxtNote.src = Source; // Load the image data onto the canvas // Clear the Pre-existing Canvas Data First ClearSketch(); var canvas = document.getElementById('SketchPage').getContext('2d'); canvas.drawImage(NxtNote, 0, 0); return; } if(Direction == "down") { //Display the Next note CurrentNote++; // Make sure you don't incrimnet to a non-existant note if(CurrentNote > FileList.length) { CurrentNote = 0; } var Source = LoadFromDisk(FileList[CurrentNote]); NxtNote.src = Source; // Load the image data onto the canvas // Clear the Pre-existing Canvas Data First ClearSketch(); var canvas = document.getElementById('SketchPage').getContext('2d'); canvas.drawImage(NxtNote, 0, 0); return; } } function DeleteNote() { // Delete The current note DeleteFile(SystemPath + DataPath + FileList[CurrentNote]); // Reload the Directory List // Clear the FileList Array FileList = []; GetFileList(SystemPath + DataPath, FileList); // Load The Previous Note // Display the previoius note CurrentNote--; // Make sure you don't incrimnet to a non-existant note if(CurrentNote <= 0) { CurrentNote = FileList.length; } var Source = LoadFromDisk(FileList[CurrentNote]); NxtNote.src = Source; // Load the image data onto the canvas var canvas = document.getElementById("SketchPage"); var context = canvas.getContext("2d"); canvas.drawImage(NxtNote, 0, 0); return; } function AddNote() { // Add a note to the notebook and at the end of the File List // **** Later this function should be modified to be an INSERT function rather than just an add // Just incase the user needs to go back an edit and add more things to their notebook CurrentNote++; // Add the new Note File name to the end of the FileList Array FileList.push(CurrentNote + ImageExtension); // Clear the Canvas ClearSketch(); // Write a blank image file to the Data directory so that we have the actual file there var FileName = SystemPath + DataPath + CurrentNote + ImageExtension; var Note = document.getElementById("SketchPage").toDataURL(); } function ClearSketch() { // Clear the contents of the Canvas //Draw a rectangle that covers the canvas var canvas = document.getElementById("SketchPage"); var ctx = canvas.getContext("2d"); ctx.fillStyle = BGcolor; ctx.fillRect (0, 0, canvas.width, canvas.height); } function Crypt(method) { // This function will Encrypt or Decrypt All the NoteData if(method == "encrypt") { return; } if(method == "decrypt") { return; } } function Archive(method) { // This function will Restore or Backup all NoteData to a network resource if(method == "restore") { return; } if(method == "backup") { return; } } // ******************** These are the XPCOM Functions ************************ function GetSystemPath(ApplicationName) { // This function should Detect the system directory of the app // and return that string as the SystemPath variable // You must supply the filename of the HTML file that it is being called from // I suppose later i could add the code to detect the HTML's actual file name // It's on the ToDo List... var GetSysPath = self.location; GetSysPath = GetSysPath + ""; Get = GetSysPath.replace("file:///" , ""); Get = Get.replace(/\//g , "\\"); Get = Get.replace(ApplicationName, ""); SystemPath = Get; return SystemPath; } function DeleteFile(FileName) { // Delete a local file netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var aFile = Components.classes["@mozilla.org/file/local;1"].createInstance(); if (aFile instanceof Components.interfaces.nsILocalFile) { aFile.initWithPath(FileName); aFile.remove(false); } } function GetFileList(Directory, FileList) { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var _nsILocalFile = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); // initialize path to work with _nsILocalFile.initWithPath(Directory); // get file interface implemenation // this means that an XPCOM Class can implement multiple interface var lv_oFile = _nsILocalFile.QueryInterface(Components.interfaces.nsIFile); var lv_oEntries = lv_oFile.directoryEntries; while(lv_oEntries.hasMoreElements()) { var lv_cFile = lv_oEntries.getNext() .QueryInterface(Components.interfaces.nsIFile).path; FileList.push(lv_cFile); } } function SaveToDisk(filepath, content) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("Permission to save file was denied."); } var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath( filepath ); if ( file.exists() == false ) { file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 ); } var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"] .createInstance( Components.interfaces.nsIFileOutputStream ); outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 ); var output = content; var result = outputStream.write( output, output.length ); outputStream.close(); } function LoadFromDisk(filePath) { if(window.Components) try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); file.initWithPath(filePath); if (!file.exists()) return(null); var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream); inputStream.init(file, 0x01, 00004, null); var sInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream); sInputStream.init(inputStream); return(sInputStream.read(sInputStream.available())); } catch(e) { //alert("Exception while attempting to load\n\n" + e); return(false); } return(null); } and the HTML UI code: Code: <html><head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <title>Sketch Book v1.0</title> <script src="SketchBook.js" type="text/javascript"></script> <script src="JSxpcom.js" language="text/javascript"></script> </head> <body onLoad="Init();"> <div id="SketchPageView"> <canvas id="SketchPage" width="480" height="640" style="background: #C7C1A3; position: absolute; top: 0px; left: 0px;" onmousedown="Draw(this, event);"></canvas> </div> <div id="Options" style="position: absolute; visibility: hidden; top: 100px; left: 50px;"> <table cellwidth="100" border="0" cellpadding="0" cellspacing="0" height="50"> <tbody><tr><td><img src="./Image/TL-black.PNG" height="19" width="19"></td><td bgcolor="#bce0f8"><center><b>Options</b></center><img src="./Image/delete.png" style="position:absolute; top: 2px; left: 150px; height: 18; width: 18;" onClick="HideOptions();"></td><td><img src="./Image/TR-black.PNG" height="19" width="19"></td></tr> <tr><td bgcolor="#bce0f8"></td> <td bgcolor="#bce0f8"> <div style="border: 1px solid black;"> <table> <tbody><tr> <td><center>Pen Size</center></td><td><center>Color</center></td> </tr> <tr> <td> <select id="GetPenSize" onchange="UpdatePenSize();"> <option value="1">1 px</option> <option value="2">2 px</option> <option value="3">3 px</option> <option value="4">4 px</option> <option value="5">5 px</option> </select> </td> <td> <select id="GetPenColor" onchange="UpdatePenColor();"> <option value="Black">Black</option> <option value="White">White</option> <option value="Red">Red</option> <option value="Blue">Blue</option> <option value="Green">Green</option> <option value="Brown">Brown</option> </select> </td> </tr> <tr> <td><input value="Restore" onclick="RestoreData();" type="button"></td><td><input value="Backup" onclick="BackupData();" type="button"></td> </tr> <tr> <td><input value="Encrypt" onclick="EncryptData();" type="button"></td><td><input value="DeCrypt" onclick="DecryptData();" type="button"></td> </tr> </tbody></table> </div> </td> <td bgcolor="#bce0f8"></td></tr> <tr><td><img src="./Image/BL-black.PNG" height="19" width="19"></td> <td bgcolor="#bce0f8"></td><td align="right"><img src="./Image/BR-black.PNG" height="19" width="19"></td></tr> </tbody></table> </div> <table id="UI" style="position: absolute; top: 0px; left: 412px; visibility: visible;" border="0" cellpadding="0" cellspacing="0" width="40"> <tbody><tr><td><img src="./Image/TL-black.PNG" height="19" width="19"></td><td bgcolor="#bce0f8"></td><td><img src="./Image/TR-black.PNG" height="19" width="19"></td></tr> <tr><td bgcolor="#bce0f8"></td> <td bgcolor="#bce0f8" height="600"> <img src="./Image/up.png" style="width: 30px; height: 30px;" alt="up" onclick="NextNote('up');"><br><br><br><br> <img src="./Image/plus.png" style="width: 30px; height: 30px;" alt="add" onclick="AddNote();"><br><br><br><br> <img src="./Image/save.png" style="width: 30px; height: 30px;" alt="save" onclick="SaveNote();"><br><br><br><br> <img src="./Image/clear.png" style="width: 30px; height: 30px;" alt="clear" onclick="ClearSketch();"><br><br><br><br> <img src="./Image/delete.png" style="width: 30px; height: 30px;" alt="delete" onclick="DeleteNote();"><br><br><br><br> <img src="./Image/gear.png" style="width: 30px; height: 30px;" alt="options" onclick="ShowOptions();"><br><br> <img src="./Image/down.png" style="width: 30px; height: 30px;" alt="down" onclick="NextNote('down');"> </td> <td bgcolor="#bce0f8"></td> </tr> <tr><td><img src="./Image/BL-black.PNG" height="19" width="19"></td> <td bgcolor="#bce0f8"></td> <td align="right"><img src="./Image/BR-black.PNG" height="19" width="19"></td></tr> </tbody></table> </body></html> hello i'm building a search engine and one of the options i'm implementing is this: the user is able to control the scale of the thumbnail, small, medium and large the problem is that when i have 1000 pictures inside a div when i hit resize i get like a 5 sec delay for them to resize here is the javascript code: Code: Code: var factor; function fillImg(imgPath, imgElement){ imageObj = new Image(32,32); imageObj.src = imgPath; if(imgElement.src != imgPath ){ imgElement.src = imgPath; } } function errHandler(err){ alert("Error occured!"); } function resizeImgList(scale){ if(scale == "s"){ factor = 50; }else if(scale == "m"){ factor = 100; }else{ factor = 150; } var lists = document.getElementById("rs_ls").getElementsByTagName("li"); for(var li_index = 0; li_index < lists.length; li_index++){ var canvas = lists[li_index].getElementsByTagName("span"); for(var c_index = 0; c_index < canvas.length; c_index++){ var link = canvas[c_index].getElementsByTagName("a"); for(var a_index = 0; a_index < link.length; a_index++){ var image = link[a_index].getElementsByTagName("img"); for(var i_index = 0; i_index < image.length; i_index++){ var w = $(image[i_index]).attr("width"); var h = $(image[i_index]).attr("height"); var results = resizeItem(w,h,factor,factor); var w = results[0]; var h = results[1]; var m = results[2]; $(image[i_index]).attr("width",w); $(image[i_index]).attr("height",h); $(image[i_index]).attr("style","width:"+w+"px;height:"+h+"px;"); } wa = w+12; ha = h+12; $(link[a_index]).attr("style","width:"+wa+"px;height:"+ha+"px;"); } wc = w+12; hc = h+12; $(canvas[c_index]).attr("style","width:"+wc+"px;height:"+hc+"px;margin-left:"+m+"px;margin-right:"+m+"px;"); } wli = w + 12 + m * 2; hli = h + 12; $(lists[li_index]).attr("style","width:"+wli+"px;height:"+hli+"px;"); } } function resizeItem(eWidth, eHeight, tWidth, tHeight) { percentage = (tHeight / eHeight); newHeight = parseInt(eHeight * percentage); newWidth = parseInt(eWidth * percentage); if (newWidth > tWidth) { percentage = (tWidth / newWidth); newHeight = parseInt(newHeight * percentage); newWidth = parseInt(newWidth * percentage); } margin = (tWidth - newWidth + 12) / 2; results = [newWidth, newHeight, margin]; return results; } each result set of 50 images has this structu HTML Code: Code: <span> <ul> <li>...</li> <li>...</li> <li>...</li> <li>...</li> . . . <li>...</li> <!-- 50 <li> --> </ul> </span> so 50 results are contained inside a span each <li> has this structure inside: HTML Code: Code: <li> <span> <a href...> <img> </a> </span> </li> I altered the resizeImgList function with 1 for loop but even then it didnt seem to improve. i was thinking that i could resize only the results the user is currently seeing inside the div, the current <span> of results but i'm anaware of how to accomplish this please if anyone has any idea I would be gratefull. Thank you. Peter. PS. results (spans) are fetched via AJAX on scrolldown inside the a div (which is the result container). Ooook so this is probably the stupidest question ever. I know in java you can take advantage of a number being an int (not double) and divide by something without getting a remainder. But in javascript you dont declare what kind of variable something is. So my problem is: Given any double or triple digit number, how do i get all but the last digit. Like if i have 13, I need to make an int with 1. If it's 103 i need one with 10. Thanks!! Is it possible to convert the getTime() result into an actual number or text type format where the length function can be used to return only the last 2 digits of the number in a text or number format that is NOT a date format? I have spent quite a bit of time hunting for this and suspect that I am attempting the impossible ?? Thanx Disregard - I believe I have figured it out finally!! Hello all I'm trying to get this function to check for 10 digits only but alert shows regardless of less / more or exactly 10 digits --- what am I missing? any help on sorting this greatly appreciated. Code: function validate(form) { if (document.forms[0].callme.checked) { var phone = document.forms[0].mobile.value; // assign value to var phone = phone.replace( /[^\d]/g, "" ); // zap all non-digit characters if ( document.forms[0].mobile.length != 10 ) // chk for 10 digits{ alert("Enter 10 numbers"); return false; } else { alert("Yahoo"); } } low tech I have a number var number = 1,235.326232 I need to display it like following with the last 4 numbers in red. 1,235.32 6232 I have tried number.slice(0,-4)+"<font color='red'>"+number.substr(number.length-5,4); however it keeps messing up the comma and decimal placement. Hello, I am a hobbyist coder making a basic website for a friend, and I have a small problem. On an image slideshow, there is a counter at the bottom showing what image it is up to (ie 7/15), I'm not entirely sure how to change this into double digits (ie 07/15) I've found this thread (http://www.codingforums.com/showthread.php?t=212321) but am unsure how to integrate it into the slideshow I'm using, which is a different one. Here is the part from my JS I think that needs modifying: Code: if (setting.displaymode.type=="manual" && !setting.displaymode.wraparound){ this.paginatecontrol() } if (setting.$status) //if status container defined setting.$status.html(setting.curimage+1 + " / " + totalimages) Is this the right bit of code? If more of the code is needed to solve this please let me know. Any help is greatly appreciated! Hi I would like to write a parser like the one below except I would like it to take characters with the the digits like 345j, 982p0, what would I change to be able to have characters with numbers? Code: ts.addParser({ id: "digit", is: function (s, table) { var c = table.config; return $.tablesorter.isDigit(s, c); }, format: function (s) { return $.tablesorter.formatFloat(s); }, type: "numeric" }); I have the following string "d3-23-76-546" I'm looking for a regular expression that will match everything in this string before 546 so that I can replace it with an empty string and just be left with 546. The string could be of any length and contain any number of hyphens. I am working on my personal portfolio site, and am using a code that will make each portfolio piece appear in a new div when the name of the piece is clicked on. The problem is, JS does not seem to recognize double digits. I am not familiar with JS at all, I just got comfortable with CSS/HTML a few weeks ago! I am in over my head. It would really, really help if someone could show me how to change the code so that I could make about 15 to 20 divs instead of 9. Here is the code: Code: <script language="JavaScript"> numdivs=9 IE5=NN4=NN6=false if(document.all)IE5=true else if(document.layers)NN4=true else if(document.getElementById)NN6=true function init() { showDiv(0) } function showDiv( which ) { for(i=0;i<numdivs;i++) { if(NN4) eval("document.div"+i+".visibility='hidden'") if(IE5) eval("document.all.div"+i+".style.visibility='hidden'") if(NN6) eval("document.getElementById('div"+i+"').style.visibility='hidden'") } if(NN4) eval("document.div"+which+".visibility='visible'") if(IE5) eval("document.all.div"+which+".style.visibility='visible'") if(NN6) eval("document.getElementById('div"+which+"').style.visibility='visible'") } </script> Thank you for taking the time to read this! Hopefully someone can help. Hello, I've obtained the following code. Code: function makeDate(){ var d = new Date(); var strDate=d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDate() + " "; strDate += d.getHours() + ":" + d.getMinutes() +":"+ d.getSeconds() ; return strDate; and I think I'm going to get the time and date indications in 2 digits. I want to get it like this: 2009/12/07 18:07:33 NOT like: 2009/12/7 18:7:33 How should I alter the code? Can anyone help? Thanks in advance. I am using a great js gallery script from ....http://coffeescripter.com/code/ad-gallery/ they have a counter for the number of images shown, the number changes as user clicks on next bottom. from looking at the script, the counter is anchor to .ad-info and the counter code from the JS is ..... _afterShow: function() { this.gallery_info.html((this.current_index + 1) + ' / '+ this.images.length); if(!this.settings.cycle) { Can anyone help make the number show double digits only for the numbers 1,2,3,4,5,6,7,8,9 (example- 03/07 or 09/28 or 03/58).. etc..etc thanks for looking. If number is more than 24 digits, modulus operator is not giving correct output here attached sample code [code]<script type="text/javascript"> var a=10000000000000000000000.0; var b=10.0; var c=a % b; alert("c"+c); </script>[code] please tel me solution So far I've logged forty hours in total trying to locate and fix the major problems in this code. I've worked with two other forums and a pay-by-minute guru to no avail. I am hopeful that the good folks here at CodingForums will be able to take this code the final distance. I'll try to be verbose without boring anyone. Summary: This code was written in 2005/2007 by "Wonder" at ProBoards. I teach a fourth grade game design and applied mathematics class to home-schoolers on a ProBoards forum. It is placed in the global footer of the forum to allow forum members to roll dice in their posts. The code was incomplete. I worked with "Jordan" at ProBoards to fix the parts that were incomplete. A problem with the code resulted. Primary resolution I'm seeking: Right now the code does everything I could possibly want. However, it is mistakenly reading double-digit numbers (XY) as X = sides of die and Y = a negative modifier. Once this issue is fixed, I can take the roller back to my students and they can game together. Secondary resolutions I'm seeking: (1) I've been told twice that the code should be "tabbed out." Not sure what that means but I guess it makes it less messy. (2) When clicking the "Add Tag" button the code generates, it automatically inserts [dice=6] into a forum post. Would love this to simply be [dice=X] The original code from "Wonder": Code: <style type="text/css"> .dicebg {background-color: FFFFFF;border:solid 2px #000000;} .dicefont {background-color: FFFFFF;color: 000000; font-weight:bold;} </style> <script> //Dice Rolls In Posts v1.1 updated 31 October 2008 //Copyright 4-23-2007 ~Wonder //May be reposted anywhere as long as this header remains in tact //Do you want the dice to line of horizontally(true) or vertically(false) diceAlignment=true; //Enter URL of the image you want to appear as the dice ubbc button UBBCdiceImage="http://img100.imageshack.us/img100/6118/diceicon9rx.gif"; //Enter the default # of sides defaultSides=6; //Enable dice in preview? true or false enablePreview=true; rs="";mainForm=""; if(document.postForm) { mainForm=document.postForm; if(location.href.match(/action\=modifypost/)){enablePreview=true;} mainForm.color.parentNode.innerHTML+="<a href=javascript:add(\"[dice="+defaultSides+"]\",\"\")><img src=\""+UBBCdiceImage+"\" alt=\"Insert Dice Roll\" border=\"0\"></a>"; mainForm.onsubmit=addRand; mainForm.message.value=mainForm.message.value.replace(/(\[rand\=\d+\])/ig,""); rs=RegExp.$1; rs=(/\[rand\=/.test(rs))?rs:""; if(location.href.match(/quote\=\d+/)) { mainForm.message.value=mainForm.message.value.replace(/(\[dice\=\d+\])/ig,""); rs=""; } } else if(location.href.match(/action\=display/)) { ta=document.getElementsByTagName("textarea"); if(ta.length>0 && ta[0].name=="message") { mainForm=ta[0].parentNode; mainForm.onsubmit=addRand; } } /////////////////////// if(location.href.match(/action\=(display|pmview|recent|userrecentposts|gotopost|search|calendarview)/) || (!location.href.match(/action\=/) && document.postForm && enablePreview)) { hr=document.getElementsByTagName("hr"); for(i=0;i<hr.length;i++) { if(typeof(hr[i].parentNode)!="undefined" && hr[i].parentNode.tagName=="TD" && typeof(hr[i].parentNode.lastChild)!="undefined" && typeof(hr[i].parentNode.lastChild.lastChild)!="undefined" && hr[i].parentNode.lastChild.lastChild.nodeType!=1) { n=hr[i].parentNode.lastChild; rand=n.innerHTML.match(/\[rand\=\d+\]/); if(rand!=null) { n.innerHTML=n.innerHTML.replace(rand[0],""); rand=rand[0].replace(/[^\d]/g,""); dice=n.innerHTML.match(/\[dice\=\d+(\+\d+)?\]/ig); if(dice!=null) { for(k=0;k<dice.length;k++) { numb=dice[k].match(/\d+(\+\d+)?/); numb=numb[0].split("+"); addon=numb.length>1?parseInt(numb[1],10):0; numb=parseInt(numb[0],10); roll=Math.round((parseFloat(rand.substring(k,k+2)+"."+rand.substring(k+2,rand.length))/100)*(numb-1))+1+addon; n.innerHTML=n.innerHTML.replace(dice[k],"<table "+(diceAlignment?"style=\"display:inline\"":"")+" border=0 cellpadding=0 cellspacing=0><tr><td><table class=dicebg cellpadding=1 cellspacing=0><tr><td><center><font class=dicefont size=\"+1\"><b>"+roll+"</b><br><font size=\"1\">"+numb+" sides"+(addon>0?"+"+addon:"")+"</font></font></center></td></tr></table></td></tr></table> "); } } } } } } function addRand() { mainForm.message.value=mainForm.message.value.replace(/(\[rand\=\d+\])/ig,""); if((rs.length==0 && mainForm.message.value.match(/(\[dice\=\d+(\+\d+)?\])/)) && (enablePreview==true || (enablePreview==false && mainForm.nextaction.value=="post"))) { mainForm.message.value+="[rand="+(Math.random()+"").replace(/0\./,"")+(Math.random()+"").replace(/0\./,"")+(Math.random()+"").replace(/0\./,"")+( Math.random()+"").replace(/0\./,"")+"]"; } else { mainForm.message.value+=rs; } disable(mainForm); } </script> The altered code from "Jordan": Code: <style type="text/css"> .dicebg {background-color: FFFFFF;border:solid 2px #000000;} .dicefont {background-color: FFFFFF;color: 000000; font-weight:bold;} </style> <script> //Dice Rolls In Posts v1.1 updated by Jordan October 2009 //Copyright 4-23-2007 ~Wonder //May be reposted anywhere as long as this header remains in tact //Do you want the dice to line of horizontally(true) or vertically(false) diceAlignment=true; //Enter URL of the image you want to appear as the dice ubbc button UBBCdiceImage="http://img100.imageshack.us/img100/6118/diceicon9rx.gif"; //Enter the default # of sides defaultSides=6; //Enable dice in preview? true or false enablePreview=true; rs="";mainForm=""; if(document.postForm) { mainForm=document.postForm; if(location.href.match(/action\=modifypost/)){enablePreview=true;} mainForm.color.parentNode.innerHTML+="<a href=javascript:add(\"[dice="+defaultSides+"]\",\"\")><img src=\""+UBBCdiceImage+"\" alt=\"Insert Dice Roll\" border=\"0\"></a>"; mainForm.onsubmit=addRand; mainForm.message.value=mainForm.message.value.replace(/(\[rand\=\d+\])/ig,""); rs=RegExp.$1; rs=(/\[rand\=/.test(rs))?rs:""; if(location.href.match(/quote\=\d+/)) { mainForm.message.value=mainForm.message.value.replace(/(\[dice\=\d+\])/ig,""); rs=""; } } else if(location.href.match(/action\=display/)) { ta=document.getElementsByTagName("textarea"); if(ta.length>0 && ta[0].name=="message") { mainForm=ta[0].parentNode; mainForm.onsubmit=addRand; } } /////////////////////// if(location.href.match(/action\=(display|pmview|recent|userrecentposts|gotopost|search|calendarview)/) || (!location.href.match(/action\=/) && document.postForm && enablePreview)) { hr=document.getElementsByTagName("hr"); for(i=0;i<hr.length;i++) { if(typeof(hr[i].parentNode)!="undefined" && hr[i].parentNode.tagName=="TD" && typeof(hr[i].parentNode.lastChild)!="undefined" && typeof(hr[i].parentNode.lastChild.lastChild)!="undefined" && hr[i].parentNode.lastChild.lastChild.nodeType!=1) { n=hr[i].parentNode.lastChild; rand=n.innerHTML.match(/\[rand\=\d+\]/); if(rand!=null) { n.innerHTML=n.innerHTML.replace(rand[0],""); rand=rand[0].replace(/[^\d]/g,""); dice=n.innerHTML.match(/\[dice\=\d+((\+|\-)\d+)?\]/ig); if(dice!=null) { for(k=0;k<dice.length;k++) { numb=dice[k].match(/\d+((\+|\-)\d+)?/); numb=numb[0].split(RegExp.$2); unsigned = (RegExp.$2 == "+") ? true : false; addon=numb.length>1?parseInt(numb[1],10):0; if(!unsigned)addon = addon - addon * 2; numb=parseInt(numb[0],10); roll=Math.round((parseFloat(rand.substring(k,k+2)+"."+rand.substring(k+2,rand.length))/100)*(numb-1))+1+addon; n.innerHTML=n.innerHTML.replace(dice[k],"<table "+(diceAlignment?"style=\"display:inline\"":"")+" border=0 cellpadding=0 cellspacing=0><tr><td><table class=dicebg cellpadding=1 cellspacing=0><tr><td><center><font class=dicefont size=\"+1\"><b>"+roll+"</b><br><font size=\"1\">"+numb+" sides"+(addon>0?"+"+addon:addon)+"</font></font></center></td></tr></table></td></tr></table> "); } } } } } } function addRand() { mainForm.message.value=mainForm.message.value.replace(/(\[rand\=\d+\])/ig,""); if((rs.length==0 && mainForm.message.value.match(/(\[dice\=\d+((\+|\-)\d+)?\])/)) && (enablePreview==true || (enablePreview==false && mainForm.nextaction.value=="post"))) { mainForm.message.value+="[rand="+(Math.random()+"").replace(/0\./,"")+(Math.random()+"").replace(/0\./,"")+(Math.random()+"").replace(/0\./,"")+( Math.random()+"").replace(/0\./,"")+"]"; } else { mainForm.message.value+=rs; } disable(mainForm); } </script> My incredibly detailed account of my last few weeks with this code: Back in 2005, a user named "Wonder" wrote a nifty piece of code that fits into any ole ProBoard's global footer. Once installed on a forum, it allows users to type the command [dice=X] where X is the number of sides for the single die they want to roll and it gives them a random result that's very attractive (a small white box with a black border and a bold, large result with smaller text below that reads: Xsides) and not "easy" to change/alter/cheat. To roll more than one die, you simply string the command like [dice=X][dice=X][dice=X][dice=X]. The code also allows for positive modifiers (bonuses) such as [dice=X+Y] where the result has the same compact, attractive format and the small text reads: Xsides+Y Wonder posted that his code would also allow negative modifiers (penalties) but, actually, no one seems to have ever tested that part... until September 2009 when along came pesky me. I went over to the ProBoards support forum because Wonder's code is included in their official database. I posted the problem and a user named Jordan tweaked the code several times, each time getting it closer to providing the correct result. The correct result being that when a user types the command [dice=X-Y] the result is the attractive box, the larger number above and the smaller text below that reads Xsides-Y (in addition to continuing to accept [dice=X] and [dice=X+Y] and offer the same format of results). Jordan's version of the code now does all this. But when I started testing it I realized that whenever a user types a command that gives the die double-digit sides (10, 12, 20, etc), the code now reads it like this: [dice=10] results in 1sides-0 or [dice=12] results in 1sides-2. So double-digit numbers are being read as the number of sides and a negative modifier *sigh* Very bad news. Jordan needed to pass on further work on the code because (understandably) it was taking too much time and it was "messy." Since I am not a coder myself, most JavaScript looks messy to me but I believe Jordan. I then took the code to a pay-by-minute help website but was gently told that the code was so messy that it would take too long to debug and it wouldn't be worth the charge since the roller is being used for a non-profit classroom project for my fourth graders. I thought that was very thoughtful... but I'm back at square one, really. I have attached everything I have: The very original code from Wonder (the one that doesn't read negative modifiers at all) and the latest from Jordan (that reads double-digits incorrectly). The only other cute/attractive thing about the code that I'll point out (so you don't see it in the code and wonder, "What the heck is that?" is: When you install the code into a forum, it adds a tiny die-shaped button to the Add Tags menu. Users can click the little thing and the code automatically inserts [dice=6] for them. Personally, this doesn't help my students and I would love it if the button just inserted [dice=X] but that's fine. *deep breath* Whew! That's about it. Thank you for putting up with my blather. I sincerely appreciate any help you can offer. I know your time is valuable and I've taken quite a bit just posting my full report... I just wanted to try to be verbose :) Jennifer Can someone explain what this does? Code: ... <script language=\"Javascript\" type=\"text/javascript\"> function SecCheck(t) { if(t) refresh = setTimeout(\"document.location='index.php';\", t*1000); } </script> </head> <body onLoad=\"SecCheck(30)\"> ... I've noticed that if you declare a variable in one function, then call another function, the variables cannot be accessed in that function. Is there any way to get the value of a variable declared in a different function?
Okay, I have this code, Code: <script type="text/javascript"> function changeText2(){ var userInput = document.getElementById('userInput').value; document.getElementById('boldStuff2').innerHTML = userInput; } </script> <p>Welcome to the site <b id='boldStuff2'>dude</b> </p> <input type='text' id='userInput' value='Enter Text Here' /> <input type='button' onclick='changeText2()' value='Change Text'/> A fairly simple one, and it is great, but I want to change it so that the text you type in stays there! Forever! For example, a person visits the site and types in "Hello" then the option of changing the text again disappears, and every visitor after that sees "Hello" (or whatever the first person types). Is this possible? Can anyone help me out! Hi All, I am opening window using following code : Code: <script>window.open('Results.aspx?sorttype=text&sort=OTName&sortname=Document&sortorder=ascending','Results','top=0,left=0,height=715,width=" & sRsultWindowSize & ",toolbar=no,status=yes,resizable=yes,scrollbars=no,location=no')</script> I want to keep new window top of the parent window. How can i achieve that ? Thanks for your help -John |