JavaScript - Arrays And Event Handlers
Hi,
I'm having two issues: First, is there an easier way for my showValue function to display the image file name without running a bunch of if statements? I tried doing something like document.getElementById('imgFile').value = imgArray[n]; but that did not seem to work. Second, I'm trying to have the image file name change in my textbox when I click any button. I've accomplished this with onblur, but that only works if I click on the textbox. I'd like it to just change automatically. Thanks for you help! Code: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" > <head> <title>Asn4CStartup.htm by Heath Parish</title> <style type="text/css" > h1, h2, h3 {font-family: 'arial black';} .controls { font-family: 'arial black'; font-size:10pt;} </style> <script type="text/javascript"> /* <![CDATA[ */ // Note: variables declared inside a function // using the var keyword are all local variables. It means that these // variables are only known inside the function. Other functions cannot see // the values. // On the other hand if a variable is declared outside any function, these are global // variables. The values of global variables are available in all other functions. // Other function can change the values of global variables. // Declare a global var n: var n=0; // we will use this global variable to keep track of exactly which element of the array // is being displayed now. When the user clicks Next button, we will add 1 to n and // then display the image file in the nth element of the array // Declare a global array that will contain the names of image files. var imgArray = new Array(); // The following function will be triggered on the onload event of the page. function fillArray() { // alert ("Hello on load"); imgArray[0]="Bus1.jpg"; imgArray[1]="Bus2.jpg"; imgArray[2]="Fam1.jpg"; imgArray[3]="Fam2.jpg"; imgArray[4]="Honey1.jpg"; imgArray[5]="Honey2.jpg"; imgArray[6]="Map1.png"; // for ( i in imgArray) // alert (imgArray[i]); } function showNext() // This function will be triggered on click of the Next button { // alert ("Hello showNext"); // alert(n); n = n+1; //alert (n); if (n > imgArray.length-1) { alert ('You are already on the last image'); n = n-1; } else document.getElementById('imgPic').src='images/'+imgArray[n]; } // end showNext() function showPrevious() // This function will be triggered on click of the Previous button { // alert("Hello Previous"); // alert(n); n = n-1; // alert (n); if (n < 0) { alert ('You are already at the first image'); n = n+1; } else document.getElementById('imgPic').src='images/'+imgArray[n]; } // end showPrevious() function showFirst() // This function will be triggered on click of the First button { // alert("Hello First"); // alert (n); if (n == 0) { alert ('You are already at the first image'); } else document.getElementById('imgPic').src='images/'+imgArray[0]; n = 0; } // end showFirst() function showLast() // This function will be triggered on click of the Last button { // alert("Hello Last"); // alert(n); // alert (n); if (n >= 6) { alert ('You are already at the last image');} else document.getElementById('imgPic').src='images/'+imgArray[6]; n=6; } // end showLast() function showValue() // This { if (n == 0) { document.getElementById('imgFile').value = "Bus1.jpg"} else if (n == 1) { document.getElementById('imgFile').value = "Bus2.jpg"} else if (n == 2) { document.getElementById('imgFile').value = "Fam1.jpg"} else if (n == 3) { document.getElementById('imgFile').value = "Fam2.jpg"} else if (n == 4) { document.getElementById('imgFile').value = "Honey1.jpg"} else if (n == 5) { document.getElementById('imgFile').value = "Honey2.jpg"} else { document.getElementById('imgFile').value = "Map1.png"} } /* ]]> */ </script> </head> <body onload="fillArray();"> <div> <h1> Asn4CStartup.htm by Mesbah Ahmed </h1> <h2>Windsurf Image Navigation </h2> <h2>Name of the Image file shown below: <input class = "controls" readonly="readonly" type="text" id="imgFile" size ="25" onblur="showValue();"/> </h2> <img id="imgPic" src = "images/Bus1.jpg" alt="picture" width="500px" height="350px" /> <br/> <input type="button" value="Next" class="controls" onclick="showNext();" /> <input type="button" value="Previous" class="controls" onclick="showPrevious();" /> <input type="button" value="First" class="controls" onclick="showFirst();" /> <input type="button" value="Last" class="controls" onclick="showLast();" /> <p> <img src="http://www.w3.org/Icons/valid-xhtml11.png" alt="Valid XHTML 1.1!" height="31px" width="88px" /> <img src="http://jigsaw.w3.org/css-validator/images/vcss-blue.png" alt="Valid CSS!" height="31px" width="88px" /> </p> </div> </body> </html> Similar Tutorialsgood day: I'm using an ajax script that receives a value into an input box and thus performs a function. I need to invoke the function immediately after the input box has a value. Currently the box has to lose focus in order for the function to work. What is the correct event handler for this to work? I have this now PHP Code: onkeyup="showResult2(this.value)" which is obviously not what I need. This is the ajax PHP Code: <script type="text/javascript"> function showResult2(strs) { if (strs.length==0) { document.getElementById("livesearch2").innerHTML=""; document.getElementById("livesearch2").style.border="0px"; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("livesearch2").innerHTML=xmlhttp.responseText; document.getElementById("livesearch2").style.border="1px solid #A5ACB2"; } } xmlhttp.open("GET","getOilChangeDate.php?q="+strs,true); xmlhttp.send(); } </script> Any thoughts on this! Mossa I have tried many conventional methods trying to get my javascript to work without using inline event handlers and for some reason the way my teacher shows us how to do it is not working for me. Any help would be much appreciated. Here is were I left off. The top part of this code is were I was trying to get the event handler to work. Code: function setClock() { document.getElementById('custname').focus(); digitalClock(); } var digital; function stop(){ clearTimeout(digital); } function digitalClock(){ var newDate = new Date(); var hour, minute; var second; var time = " "; hour = newDate.getHours(); minute = newDate.getMinutes(); second = newDate.getSeconds(); if (hour <= 9) hour = "0" + hour; if (minute <= 9) minute = "0" + minute; if (second <= 9) second = "0" + second; time += hour + ":" + minute + ":" + second; document.getElementById('dClock').value = time; digital = setTimeout("digitalClock()", 1000); } var validated=true; function validateForm(f) { validated=isEmpty(f.custname, "customer name"); if (!validated) { return validated; } validated=isEmpty(f.phone, "phone"); if (!validated) { return validated; } validated=isEmpty(f.email, "email"); if (!validated) { return validated; } validated=isEmpty(f.address, "address"); if (!validated) { return validated; } validated=isEmpty(f.city, "city"); if (!validated) { return validated; } validated=isSelect(f.state); if (!validated) { return validated; } validated=isEmpty(f.zip, "zip"); if (!validated) { return validated; } validated=isNumber(f.qty); if (!validated) { return validated; } validated=checkRadio(f.pizza); if (!validated) { return validated; } return validated; } var radPizza = 0; function checkRadio(radiobuttons) { var i=0; while (i<=4 && !radiobuttons[i].checked) { if (i==4) { alert("Please choose a Pizza."); return false; } i++; } return true; } function isEmpty(textbox, textString) { //match null or blank space if (textbox.value.match(/^\s*$/) || textbox.value.match(/^null$/)) { alert("Data is not valid for " + textString); textbox.style.backgroundColor = "#f4f8b4"; textbox.focus(); return false; } else { textbox.style.backgroundColor = "white"; } if (textString=="customer name") { //does not match name format if (!textbox.value.match(/^[\w\.\']{2,}([\s][\w\.\']{2,})+$/)) { alert("Data is not valid for " + textString); textbox.style.backgroundColor = "#f4f8b4"; textbox.focus(); return false; } } if (textString=="email") { //does not match email format if (!textbox.value.match(/^[a-zA-Z]{1}[a-zA-Z0-9]+(\.|\_)?[a-zA-Z]+@[a-zA-Z]{1}[a-zA-Z0-9]{0,62}\.(com|net|org)$/)) { alert("Data is not valid for " + textString); textbox.style.backgroundColor = "#f4f8b4"; textbox.focus(); return false; } } if (textString=="address") { //does not match address format if (!textbox.value.match(/^[a-zA-Z0-9\s,'-]*$/)) { alert("Data is not valid for " + textString); textbox.style.backgroundColor = "#f4f8b4"; textbox.focus(); return false; } } if (textString=="city") { //does not match city format if (!textbox.value.match(/^[A-Za-z. ]+$/)) { alert("Data is not valid for " + textString); textbox.style.backgroundColor = "#f4f8b4"; textbox.focus(); return false; } } if (textString=="phone") { //does not match phone format if (!textbox.value.match(/^\(?(\d{3})\)?[-](\d{3})[-](\d{4})$/) || textbox.value.match(/^xxx-xxx-xxxx$/)) { alert("Please enter a correct phone number."); textbox.style.backgroundColor = "#f4f8b4"; textbox.focus(); return false; } } if (textString=="zip") { //does not match zip format or starting format if (!textbox.value.match(/^(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$/) || textbox.value.match(/^xxxxx or xxxxx-xxxx$/)) { alert("Please enter a correct zip number."); textbox.style.backgroundColor = "#f4f8b4"; textbox.focus(); return false; } } return true; } function isSelect(selected) { if (selected.value=="Select State") { alert("Please select a state."); selected.style.backgroundColor = "#f4f8b4"; selected.focus(); return false; } else { selected.style.backgroundColor = "white"; } return true; } function isNumber(textbox) { //match negative number and not equal to a number if (textbox.value.match(/^-\d*\.{0,1}\d+$/) || !textbox.value.match(/^((\d+(\.\d *)?)|((\d*\.)?\d+))$/)) { alert("Drinks value cannot be negative and has to be a number."); textbox.style.backgroundColor = "#f4f8b4"; textbox.focus(); textbox.value=0; return false; } return true; } function calcPizza() { var rad = document.getElementsByName('pizza'); for (var i=0; i<rad.length;i++) { if (rad[i].checked) { radPizza = parseFloat(rad[i].value); } } if (document.getElementById('cheese').checked) { var extraCheese = parseFloat(document.getElementById('cheese').value); } else { extraCheese = 0; } if (document.getElementById('mushrooms').checked) { var addShrooms = parseFloat(document.getElementById('mushrooms').value); } else { addShrooms = 0; } if (document.getElementById('anchovies').checked) { var addAnchovies = parseFloat(document.getElementById('anchovies').value); } else { addAnchovies = 0; } if (document.getElementById('wings').checked) { var addWings = parseFloat(document.getElementById('wings').value); } else { addWings = 0; } if (document.getElementById('dessert').checked) { var addDessert = parseFloat(document.getElementById('dessert').value); } else { addDessert = 0; } var qtyDrinks = parseFloat(document.getElementById('qty').value * 1.50); if (qtyDrinks<0) { qtyDrinks=0; document.getElementById('qty').value = 0; alert("Drinks amount cannot be negative."); } var total = (radPizza + extraCheese + addShrooms + addAnchovies + addWings + addDessert + qtyDrinks); document.getElementById('pizzaPrice').value = total.toFixed(2); } HTML Code : 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=iso-8859-1" /> <title>Pizza To Go</title> <script type="text/javascript" src="PizzaCookies.js"></script> <script type="text/javascript" src="cookieLib.js"></script> <link rel="stylesheet" href="style1.css" type="text/css" title="style1"/> <link rel="alternate stylesheet" type="text/css" href="style2.css" title="style2" /> <link rel="alternate stylesheet" type="text/css" href="style3.css" title="style3" /> <script type="text/javascript" src="Validation.js"></script> </head> <div class="styleLinks"> <a href="#" id="style1" onclick="setStyleSheets('style1'); return false;">Style 1</a> <a href="#" id="style2" onclick="setStyleSheets('style2'); return false;">Style 2</a> <a href="#" id="style3" onclick="setStyleSheets('style3'); return false;">Style 3</a> </div> <body id="body_main" onload = "setClock(), testCookies();" onunload = "stop()"> <script type="text/javascript" src="DigiClock.js"></script> <h1>Pizza To Go</h1> <form name="pizzaList" id="form1" onsubmit="return validateForm(this)" onreset="return resetForm()" action="#" method="get" > <label for="dClock">Digital Clock:</label><input type="text" name="dClock" id="dClock" /> <fieldset id="customer"><legend>Customer Info</legend> <label for="custname">Customer Name: </label><input type="text" name="custname" id="custname" value="" size = "50" maxlength = "48" /><br/> <label for="phone">Phone: </label><input type="text" name="phone" id="phone" value="xxx-xxx-xxxx" size = "14" maxlength = "12" /><br/> <label for="email">Email: </label><input type="text" name="email" id="email" value="" size = "70" maxlength = "68" /><br/> <label for="address">Address: </label><input type="text" name="address" id="address" value="" size = "50" maxlength = "48" /><br/> <label for="city">City: </label><input type="text" name="city" id="city" value="" size = "30" maxlength = "28" /><br/> <label for="state">State: </label> <select name="state" id="state" > <option value="Select State">Select State</option> <option value="AL">AL</option> <option value="AK">AK</option> <option value="AZ">AZ</option> <option value="AR">AR</option> <option value="CA">CA</option> <option value="CO">CO</option> <option value="CT">CT</option> <option value="DE">DE</option> <option value="DC">DC</option> <option value="FL">FL</option> <option value="GA">GA</option> <option value="HI">HI</option> <option value="ID">ID</option> <option value="IL">IL</option> <option value="IN">IN</option> <option value="IA">IA</option> <option value="KS">KS</option> <option value="KY">KY</option> <option value="LA">LA</option> <option value="ME">ME</option> <option value="MD">MD</option> <option value="MA">MA</option> <option value="MI">MI</option> <option value="MN">MN</option> <option value="MS">MS</option> <option value="MO">MO</option> <option value="MT">MT</option> <option value="NE">NE</option> <option value="NV">NV</option> <option value="NH">NH</option> <option value="NJ">NJ</option> <option value="NM">NM</option> <option value="NY">NY</option> <option value="NC">NC</option> <option value="ND">ND</option> <option value="OH">OH</option> <option value="OK">OK</option> <option value="OR">OR</option> <option value="PA">PA</option> <option value="RI">RI</option> <option value="SC">SC</option> <option value="SD">SD</option> <option value="TN">TN</option> <option value="TX">TX</option> <option value="UT">UT</option> <option value="VT">VT</option> <option value="VA">VA</option> <option value="WA">WA</option> <option value="WV">WV</option> <option value="WI">WI</option> <option value="WY">WY</option> </select> <br/> <label for="zip">Zip: </label><input type="text" name="zip" id="zip" value="xxxxx or xxxxx-xxxx" size = "14" maxlength = "12" /> </fieldset> <fieldset><legend>Pizza</legend> <input type="radio" name="pizza" id="veggie" value="12.95" onclick="calcPizza()"/>Vegetarian ($12.95)<br /> <input type="radio" name="pizza" id="hawaiian" value="14.95" onclick="calcPizza()"/>Hawaiian ($14.95)<br /> <input type="radio" name="pizza" id="meatlovers" value="16.95" onclick="calcPizza()"/>Meat Lovers ($16.95)<br /> <input type="radio" name="pizza" id="works" value="18.95" onclick="calcPizza()"/>The Works ($18.95)<br /> <input type="radio" name="pizza" id="fourcheese" value="15.95" onclick="calcPizza()"/>Four Cheese ($15.95) </fieldset> <fieldset><legend>Extras</legend> <input type="checkbox" name="cheese" id="cheese" value="2" onclick="calcPizza()"/>Extra cheese ($2.00) <input type="checkbox" name="mushrooms" id="mushrooms" value="2.5" onclick="calcPizza()"/>Mushrooms ($2.50) <input type="checkbox" name="anchovies" id="anchovies" value="3" onclick="calcPizza()"/>Anchovies ($3.00) </fieldset> <fieldset><legend>Sides</legend> <input type="checkbox" name="wings" id="wings" value="2.75" onclick="calcPizza()"/>Wings ($2.75) <input type="checkbox" name="dessert" id="dessert" value="6.95" onclick="calcPizza()"/>Dessert pizza ($6.95) </fieldset> <fieldset><legend>Drinks ($1.50)</legend> <label for="qty">Quantity: </label><input type="text" name="qty" id="qty" size="5" value="0" onkeyup = "calcPizza()"/> </fieldset> <p><label for="pizzaPrice">Order total: $</label><input type="text" name="pizzaPrice" id="pizzaPrice" value="0" /></p> <input type="submit" value="Place Order" /><input type="reset" value="Clear Form" /> </form> </body> </html> hi, i need to be able to take the values from two text boxes and change the location of a sprite on my canvas, i've searched the internet and it doesnt really explain how to do it for me. here is my code: x: <input type="text" name="x" id="x"/><br /> y: <input type="text" name:"y" id="y"/><br /> <input type="submit" value="Submit" onClick="ChangeCo()" /><br /> function ChangeCo() { } and i need the function to take the x and y values from the text boxes and change the values of my variables: var block_x; var block_y; block_x = 290; block_y = 70; Thankyou in advance can someone please explain the code in this link. Just this small bit since i seen it in a few different places. it starts off with if (!e) ... please explain wth that means thank you so much heres the link - http://www.w3schools.com/js/tryit.as...ent_srcelement Today I have been embedding some Google Maps on my website. When I got around to putting in event handlers for markers on the map I ran into some trouble with how to declare them in the way I have the map setup. The issue is that I have an array, label, and want to indicate a single element from that array to the event handling function. But the declaration of this seems tricky. The code in question are the two lines like this one in the script below: GEvent.addListener(marker[i], 'mouseover', function() { map.addOverlay(label[i]); }); Specifically, the problem is with function() { map.addOverlay(label[i]); because I don't want label[i] to be used, but whatever value i has should be substituded in there. But since this is a function being declared and not actually executed the value for i does not get used. I've been able to get it to work by using eval() to force the actual value of i into the code, like so: eval('GEvent.addListener(marker[i], \'mouseout\', function() { map.removeOverlay(label['+i+']); });'); but am wondering if there is a better solution? Here's a section of my script showing the issue in context. You can see that i is incremented with a loop and used as the index of a few arrays. Code: for (i = 0; i < buildings.length; i++) { icon[i] = new GIcon(); icon[i].image = 'http://labs.google.com/ridefinder/images/mm_20_red.png'; icon[i].iconSize = new GSize(12, 20); icon[i].iconAnchor = new GPoint(6, 20); map.addOverlay(marker[i] = new GMarker(new GLatLng(buildings[i][1], buildings[i][2]), {icon:icon[i]})); label[i] = new ELabel(new GLatLng(buildings[i][1], buildings[i][2]), '<nobr>'+buildings[i][3]+'<\/nobr>', 'maplabel'); GEvent.addListener(marker[i], 'mouseover', function() { map.addOverlay(label[i]); }); GEvent.addListener(marker[i], 'mouseout', function() { map.removeOverlay(label[i]); }); } I'm trying to figure out a way to put this in all js code with the onclick event handlers and the parameters. I have 3 links that switch the style of my page. Right now I have them working with inline event handlers. Here are my code snippets below. HTML: Code: <head> <link rel="stylesheet" href="style1.css" type="text/css" title="style1"/> <link rel="alternate stylesheet" type="text/css" href="style2.css" title="style2" /> <link rel="alternate stylesheet" type="text/css" href="style3.css" title="style3" /> </head> <div class="styleLinks"> <a href="#" id="style1" onclick="setStyleSheets('style1'); return false;">Style 1</a> <a href="#" id="style2" onclick="setStyleSheets('style2'); return false;">Style 2</a> <a href="#" id="style3" onclick="setStyleSheets('style3'); return false;">Style 3</a> </div> JS: Code: function setStyleSheets(title) { //set styles and set cookie var i; var attribute; var today = new Date(); var expDate = new Date(today.getTime() + 7*24*60*60*1000); var styleSelected = ""; if (title=="style2"){ styleSelected = "style2"; } else if (title=="style3"){ styleSelected = "style3"; } for(i=0; (attribute = document.getElementsByTagName("link")[i]); i++) { if(attribute.getAttribute("rel").indexOf("style") != -1 && attribute.getAttribute("title")) { attribute.disabled = true; if(attribute.getAttribute("title") == title) attribute.disabled = false; SetCookie ('style', styleSelected, expDate, "/"); } } } Well just came to notice this lack of tools on javascript to manage uploads or downloads while working on my new project. I've been trying different ways to get the upload progress, stimated time left, upload speed average, but everything I have done was somehow dirty. I have spent the last two days trying to get a flash file do this for me, and there is always an issue and you have to get a tricky solution to get something that should be a native javascript support at this age of the web. What do you think guys, isn't the web mature enought to get a decent upload / download progress functions? What are big guys doing, youtube, google, flickr? I know this maybe sounds "newbie", perhaps I am still one. I have 3 divs, all of them in a group "name", there are h1 tags inside them with names too. Well actually I have many many divs like this in several pages so I must use a JS sheet (.js). Code: <div name="area"> <h1 name="stringRed"> Mercury </h1> </div> <div name="area"> <h1 name="stringRed"> Venus </h1> </div> <div name="area"> <h1 name="stringRed"> Earth </h1> </div> The idea is to create an event for the divs, a mouseover event to a div in order to change the color of the words inside the h1 tags. When the mouse is over one particular div the word inside it must change to red. I was trying this Java Script script: (a cross-browser event handler present) Code: function initialize ( ) { aArea=document.getElementsByName("area"); aStringRed=document.getElementsByName("stringRed"); for (var i=0; i < aArea.length; i++) { addEvent (aArea[i], 'mouseover', changeColor); addEvent (aArea[i], 'mouseout', changeOutColor); } } function changeColor() { ???? } function changeOutColor() { ???? } Thank you in advanced for any help. Actually I was trying to use this imagesearch code for one of my blog posts about cars, I want to embed the below codes one for BMW and one for Toyota in the blog post, individually if I place one of these codes they work fine but if I want to place them both together in 2 different blocks separately it doesn't work. Is there a way to achieve this, basically giving 2 different handlers. This will help me a lot - TIA. <script type="text/javascript" src="http://www.google.com/jsapi? key=ABQIAAAA1XbMiDxx_BTCY2_FkPh06RRaGTYH6UMl8mADNa0YKuWNNa8VNxQEerTAUcfkyrr 6OwBovxn7TDAH5Q"></ script><div id="TOYOTA">Loading...</div><script type="text/ javascript">google.load('search', '1');var imageSearch;function OnLoadSneha() { imageSearch = new google.search.ImageSearch(); imageSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET); imageSearch.setRestriction (google.search.ImageSearch.RESTRICT_IMAGESIZE, google.search.ImageSearch.IMAGESIZE_MEDIUM); imageSearch.setSearchCompleteCallback(this, function(){ if (imageSearch.results && imageSearch.results.length > 0) {var contentDiv = document.getElementById('TOYOTA'); contentDiv.innerHTML = ''; var results = imageSearch.results; for (var i = 0; i < results.length; i++) { var result = results[i]; var imgContainer = document.createElement('div'); var title = document.createElement ('div'); var newImg = document.createElement('img'); newImg.src = result.tbUrl; var titleLink=document.createElement('a'); title.className=titleLink.className='gs-title'; titleLink.setAttribute ('href',result.url); titleLink.appendChild(document.createTextNode (result.titleNoFormatting)); title.appendChild(titleLink); imgContainer.appendChild(title); imgContainer.appendChild(newImg); contentDiv.appendChild(imgContainer); } function (imageSearch) { var cursor = imageSearch.cursor; var curPage = cursor.currentPageIndex; var pagesDiv = document.createElement('div'); for (var i = 0; i < cursor.pages.length; i++) { var page = cursor.pages[i]; if (curPage == i) { var label = document.createTextNode(' ' + page.label + ' '); pagesDiv.appendChild (label);} else {var link = document.createElement('a');link.href = 'javascript:imageSearch.gotoPage('+i+');';link.innerHTML = page.label; link.style.marginRight = '2px';pagesDiv.appendChild (link);}} var contentDiv = document.getElementById('TOYOTA'); contentDiv.appendChild(pagesDiv);} }}, null); imageSearch.execute ("TOYOTA");} google.setOnLoadCallback(OnLoadSneha);</script> <script type="text/javascript" src="http://www.google.com/jsapi? key=ABQIAAAA1XbMiDxx_BTCY2_FkPh06RRaGTYH6UMl8mADNa0YKuWNNa8VNxQEerTAUcfkyrr 6OwBovxn7TDAH5Q"></ script><div id="TOYOTA">Loading...</div><script type="text/ javascript">google.load('search', '1');var imageSearch;function OnLoadSneha() { imageSearch = new google.search.ImageSearch(); imageSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET); imageSearch.setRestriction (google.search.ImageSearch.RESTRICT_IMAGESIZE, google.search.ImageSearch.IMAGESIZE_MEDIUM); imageSearch.setSearchCompleteCallback(this, function(){ if (imageSearch.results && imageSearch.results.length > 0) {var contentDiv = document.getElementById('TOYOTA'); contentDiv.innerHTML = ''; var results = imageSearch.results; for (var i = 0; i < results.length; i++) { var result = results[i]; var imgContainer = document.createElement('div'); var title = document.createElement ('div'); var newImg = document.createElement('img'); newImg.src = result.tbUrl; var titleLink=document.createElement('a'); title.className=titleLink.className='gs-title'; titleLink.setAttribute ('href',result.url); titleLink.appendChild(document.createTextNode (result.titleNoFormatting)); title.appendChild(titleLink); imgContainer.appendChild(title); imgContainer.appendChild(newImg); contentDiv.appendChild(imgContainer); } function (imageSearch) { var cursor = imageSearch.cursor; var curPage = cursor.currentPageIndex; var pagesDiv = document.createElement('div'); for (var i = 0; i < cursor.pages.length; i++) { var page = cursor.pages[i]; if (curPage == i) { var label = document.createTextNode(' ' + page.label + ' '); pagesDiv.appendChild (label);} else {var link = document.createElement('a');link.href = 'javascript:imageSearch.gotoPage('+i+');';link.innerHTML = page.label; link.style.marginRight = '2px';pagesDiv.appendChild (link);}} var contentDiv = document.getElementById('TOYOTA'); contentDiv.appendChild(pagesDiv);} }}, null); imageSearch.execute ("TOYOTA");} google.setOnLoadCallback(OnLoadSneha);</script> Hi All, I'd like to create a custom logo (don't know what yet) that represents the pieces of my project so that a user can click on a piece of the logo and have that associated panel brought forth. I'm not sure how to go about doing this so could someone point me in the right direction? Thanks! Hi forum, I am trying to attach an event to a dynamically produced button, and then use stopPropagation and preventDefault. Code: function chapter12_nodeOne() { //create an element var element = document.createElement('input'); //set some attributes element.setAttribute('type', 'button'); element.setAttribute('value', 'submit'); element.setAttribute('id', 'myBtn'); //appendd the element into a DIV document.getElementById('myDiv').appendChild(element); //uses EventUtil to attach an event listener EventUtil.addHandler(element, 'click', function() { alert('event attached'); }); var flag = confirm('prevent default behavior of button?'); if (flag) { var el = document.getElementById('myBtn');/////////////////////////(1) var ev = el.onclick; } } var EventUtil = { addHandler: function(element, type, handler) { //check if the element and the browser support DOM Level 2 event attachment //if the user is not browsing with IE if (element.addEventListener) { element.addEventListener(type, handler, false); } //if user is browsing with IE else if (element.attachEvent) { element.attachEvent("on" + type, handler); } //if user is using a browser that only supports DOM Level 0 event attachment else { element["on" + type] = handler; } }, removeHandler: function(element, type, handler) { //check if the element and the browser support DOM Level 2 event attachment //if the user is not browsing with IE if (element.removeEventListener) { element.removeEventListener(type, handler, false); } //if user is browsing with IE else if (element.detachEvent) { element.detachEvent("on" + type, handler); } //if user is using a browser that only supports DOM Level 0 event attachment else { element["on" + type] = null; } } }; But when debugging I see under el on the line marked with (1) that the onclick event is null. What am I doing wrong?! PS:the event is attached, when I click on the button I get an alert message I need to loop the alphabet and numbers 0-9 to initialize a few thousand arrays. This is for my site and is truly needed. http://www.thefreemenu.com I currently have every array written out and it takes up to much space in my .js file. The majority of my variables are empty but necessary and need to be there (including empty) for my site to work properly. Question is the last part Here's where I'm at. Code: var NewVarLetterOrNum = "a"; eval("_oneofseveralnames_" + NewVarLetterOrNum + "='this part works';"); alert(_oneofseveralnames_a); This creates the variable _oneofseveralnames_a='this part works' Code: var newArrayLetterOrNum = "a"; eval("_oneofseveralnames_" + newArrayLetterOrNum + "= new Array();"); alert(_oneofseveralnames_a) This creates the Array _oneofseveralnames_a=new Array(); and all the values in the array are null, but, now a variable like _nl_a[1]='something' can be used elsewhere because the array exists. This is all that is necessary for now because I can probably set all the variables to be blank with something like Code: i=1 while(i<=20){ _oneofseveralnames_a[i]="1-20"; i++ } alert(_oneofseveralnames_[20]); So now you have what I came to understand in the first few hours. Now to the hard part : ( I can't make multiple array's dynamically. I dont' know if its because I don't understand loops or arrays or what and its very fustrating. As for any answer you might be so kind as to provide, if you could dumb it down that would be greatly appreciated. Code: var newArray =new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z') i=1 while(i<=26){ eval("_nl_" + newArray[i] + "= new Array();"); i++ } alert(newArray[1]) // Is b, but alert(_nl_b) //I can't get _nl_b to exist, I tried everything including taking away the quotes around the letters in every test */ var _nl_a =new Array() var _img_a =new Array() var _h_a =new Array() var _r_a =new Array() var _m_a =new Array() var _yt_a =new Array() var _i_a =new Array() The above arrays are all the array _name_ parts I need but for example, a has 10 parts, a,p2_a,p3_a,.. p10_a. I need 10 pages for each letter of the alphabet and numbers 0-9 and a special all1, p2_all1 ... p10_all1. Overall 2200 arrays that need to be declared. Currently they are all written out. /* is it possible to capture the control.event or element.event that was fired to invoke the onbeforeunload event. for example, if a button is clicked and it causes the onbeforeunload event to fire can i determine which button was clicked. thanks I have a ondrag event handler and in that I am trying to retrieve e.ClientX but it always return 0 in Mozilla. Works fine in IE though. How can retrieve the clientX and clientY in ondrag event? Hey guys, I had a client ask me to frankenstein two HTML5 themes together to achieve having both a countdown clock and snow effect on a "coming soon" page. You can see it he EXSAPIEN - A New Graphic Novel The problem I'm having now is that the social media buttons are not clickable (The links work on my iPhone, but not on my laptop.) I have been able to EITHER display the snow, OR make the links work, but not both at the same time. This code seems to be the piece that is making the difference (specifically, the Code: event.preventDefault(); toward the end): Code: function init() { container = document.createElement('div'); document.body.appendChild(container); camera = new THREE.PerspectiveCamera( 75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); camera.position.z = 1000; scene = new THREE.Scene(); scene.add(camera); renderer = new THREE.CanvasRenderer(); renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT); var material = new THREE.ParticleBasicMaterial( { map: new THREE.Texture(particleImage) } ); for (var i = 0; i < 500; i++) { particle = new Particle3D( material); particle.position.x = Math.random() * 2000 - 1000; particle.position.y = Math.random() * 2000 - 1000; particle.position.z = Math.random() * 2000 - 1000; particle.scale.x = particle.scale.y = 1; scene.add( particle ); particles.push(particle); } container.appendChild( renderer.domElement ); var userAgent = navigator.userAgent || navigator.vendor || window.opera; if( userAgent.match( /iPad/i ) || userAgent.match( /iPhone/i ) || userAgent.match( /iPod/i ) ) { document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); document.removeEventListener( 'touchstart', onDocumentTouchStart, false ); document.removeEventListener( 'touchmove', onDocumentTouchMove, false ); } else if( userAgent.match( /Android/i ) ) { document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); document.removeEventListener( 'touchstart', onDocumentTouchStart, false ); document.removeEventListener( 'touchmove', onDocumentTouchMove, false ); } else { document.addEventListener( 'mousemove', onDocumentMouseMove, false ); document.addEventListener( 'touchstart', onDocumentTouchStart, false ); document.addEventListener( 'touchmove', onDocumentTouchMove, false ); } setInterval( loop, 1000 / 60 ); $('canvas').parent().addClass('snow'); } function onDocumentMouseMove( event ) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; } function onDocumentTouchStart( event ) { if ( event.touches.length == 1 ) { event.preventDefault(); mouseX = event.touches[ 0 ].pageX - windowHalfX; mouseY = event.touches[ 0 ].pageY - windowHalfY; } } function onDocumentTouchMove( event ) { if ( event.touches.length == 1 ) { event.preventDefault(); mouseX = event.touches[ 0 ].pageX - windowHalfX; mouseY = event.touches[ 0 ].pageY - windowHalfY; } } I learned jscript back in 1999, so with all the new technology, multi-touch etc, that has come about in the meantime, I am effectively a n00b again. :/ Please help! What can I do here that will allow the snow effect to run while still keeping the social media links clickable?? Is there any other code I can provide that would be useful in solving the problem? Thank you!! I have a asp:textbox where I'd like to capture when the user hits Enter, and then instead of doing whatever it normally would, then it should call a javascript function. I'm not sure how to do that, other than I suppose I should use the OnTextChanged event. But I'm not sure which parameters are sent with the event... Thanks in advance Hi I'm a newbie. Please help me. I'm using Joomla. I've got a dropdown which reads the filename from the database. When the user selects it I want an onchange event to open the pdf. I've been at it for 2 days now. Code: <?php $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("metnet", $con); $sql="SELECT * FROM newsletter"; $result = mysql_query($sql); echo "<form method='post'>"; $dropdown = "<select name='sname' onChange='location(this.form.sname)' >"; while($row = mysql_fetch_assoc($result)) { $dropdown .= "\r\n<option value='{$row['fpath']}'>{$row['fpath']}</option>"; } $dropdown .= "\r\n</select>"; echo $dropdown; ?> I am looking to add a calendar to my website in order to list events for each day on the calendar you click on. For example, the link below shows a calendar on the left, that when you click on a day it lists all the events that day. I have done a few searches, but am not sure if I can find a calendar that acts like this... Calendar Example Any help would be greatly appreciated! Hi, I am trying to copy the value of one textbox to another using onchange event. For some reason, my code does not work, please let me know where I went wrong. here is my code: Code: <html> <head> <script type="text/javascript"> function copyText() { document.getElementById("field2").value=document.getElementById("field1").value; } </script> </head> <body> Field1: <input type="text" id="field1"/><br /> Field2: <input type="text" id="field2" onchange="copyText()"/> </body> </html> Thank you. |