JavaScript - Passing An Array Into An Event Handler
I'm having trouble passing an array into an event handler.
This does not work: Code: var lightbulb = [1,1,1,0,1,0] var banana = [0,0,1,1,0,1] function changetextimage(arr){ for(var i=0;i<5;i++){ var pixel = document.getElementById("text"+i); if (arr[i]) { pixel.style.color="#000000"; } else { pixel.style.color="#FFFFFF"; } } } $('#lightbulbpicture').mouseover(changetextimage(lightbulb)); $('#bananapicture').mouseover(changetextimage(banana)); This does work: Code: var lightbulb = [1,1,1,0,1,0] var banana = [0,0,1,1,0,1] function changetextimage1(){ for(var i=0;i<5;i++){ var pixel = document.getElementById("text"+i); if (lightbulb[i]) { pixel.style.color="#000000"; } else { pixel.style.color="#FFFFFF"; } } } function changetextimage2(){ for(var i=0;i<5;i++){ var pixel = document.getElementById("text"+i); if (banana[i]) { pixel.style.color="#000000"; } else { pixel.style.color="#FFFFFF"; } } } $('#lightbulbpicture').mouseover(changetextimage1); $('#bananapicture').mouseover(changetextimage2); I have a whole bunch of these arrays (which are much longer) that I want to pass into this function so I just want to pass each as an argument rather than write each function out. I bolded the areas I'm talking about so it's easier to see. Similar TutorialsI have added an event listener to a LI item in the DOM: liNode.addEventListener("mouseover", mouseOn, true); The mouseOn function: function mouseOn(e) { // Test for IE or Firefox var e = (!e)?window.event:e; var yPos; if (e.pageY) { yPos = e.pageY; } else { yPos = e.clientY; } } I would like to pass in another parameter to the mouseOn function in addition to the event that is passed in automatically. Is there a way to do this? Hey Everyone, I would like to let a select menu drop down with the click of a button or image. So, I have: Code: <select> <option>Option1</option> <option>Option2</option> <option>Option3</option> <option>Option4</option> </select> So, how do I trigger this select menu to drop down, except for clicking on the down arrow? Thanx in forward Hi all, I am really stuck on this: I have an iframe on my page <iframe id="displayframe">. I used security="restricted" to create a more 'secure' frame but that means that any forms which submit will be opened in a new window... away from my website. I also have a textbox, called "showurl" which acts as an 'address bar' to the iframe and the accompanying button "go". I read on Stanford's website that: "It is possible to use JavaScript inside the restricted iframe, by attaching event handlers from the outside (unrestricted) window. This allows the outer window to get around the restriction that hyperlinks in a restricted iframe are supposed to open in a new window. " So I would need a function that would detect when a new page has been opened (ie. a form has been submitted) and would be able to take the URL of the new page, copy the new page's URL into the textbox and click the button "Go" and close the new page (the one which just opened) All in all... The event handler needs to get the url of the submitted form page (the opened window) paste it into the textbox "showurl", click the button "go" and then close the opened window. Could anyone help me out on this? It would be greatly appreciated!! I understand that there is an onended event handler that can be used to detect when a media event, such as the playing of am MP3 file or digital video file, is completed. I would like to know 1. how to use code this event handler and 2. how to use detection of the end of the media event to launch another Web page. Thanks for any help, George if it is done like this: Code: anElement.onclick=handleIt; function handleIt() { this. ... //'this' refer to the anElement } However, if you attach an event, quirk happens: Code: anElement.attachEvent("onclick",handleIt); // not sure if anElement.addEventListener("click",handleIt,false) works well function handleIt() { this. ... //'this' refer to an empty object ??????? } why 'this' doesn't refer to the current target? anyone can help? hello everyone, i am new to all this.. i need help regarding.. i am generating text box dynamically(mean it's a multiple select box, depending upon the number you select , it will generate that many text field.) my problem is that i want to assign a calender to the text field generated whenever a user clicks on that text field. i am able to do it for simple text field as onclick="javascript: showCalendar('idname')" but how to do it in this case, where can i declare this ? Hello all, I'm wondering if anyone can offer advice on a simple (or so I thought!) Javascript menu I'm trying to create. I'm creating 5 buttons, using event handlers (onmouseover etc) which exchange 1 image for another. I did the first one fine - it worked perfectly, but as soon as I added the rest they all stopped working properly. The best I have got, is that the last link will do what it's supposed to regardless of which link I hover over! Which is strange. So the browser seems to be actioning the last thing on the list if that makes sense. It seems to me that I need to add an "if" type attribute, so "if" I hover over the home button, the home images change, as opposed to the last one on the list. This is the code I have so far for a single link - the rest are copies of this with adjustments made to the imgname and image sources obviously..... <div style="width:80px; height:20px;margin-top:20px;margin-left:85px;"><a href="about.html" onMouseOver="return changeImage()" onMouseOut= "return changeImageBack()" onMouseDown="return handleMDown()" onMouseUp="return handleMUp()" ><img name="aboutbutton" src="img/aboutn.png" width="80" height="20" border="0" alt="javascript button 1"></a> <script language="JavaScript"> upImage = new Image(); upImage.src = "img/abouth.png"; downImage = new Image(); downImage.src = "img/aboutc.png" normalImage = new Image(); normalImage.src = "img/aboutn.png"; function changeImage() { document.images["aboutbutton"].src= upImage.src; return true; } function changeImageBack() { document.images["aboutbutton"].src = normalImage.src; return true; } function handleMDown() { document.images["aboutbutton"].src = downImage.src; return true; } function handleMUp() { changeImage(); return true; } </script></div> Any suggestions on where I am going wrong would be wonderful. Thanks so much in advance! All the best I have many examples within my page of the form: Code: <a id="L1" href="#" onclick="return showSpan();" onblur="return hideSpan();"><span> ... </span></a> The page is styled so that hovering over the link displays the contents of the hidden <span> as a block without any javascript. I want this to work (that is display the span as a block) when the user tabs onto a link (and presses Return/Enter). When the user tabs away, it should hide the <span>. My starting code looks like: Code: function showSpan() { var linkID = document.getElementById(this.id); var classList = linkID.getElementsByTagName('span'); var divID = classList[0]; divID.style.display = "block"; return false; } // function with a similar function for hideSpan(), Ultimately I would like to add these event handlers in the initialisation phase, which is why I have used a parameterless function. Whenever I try this, I get an error that this.id does not exist. How can I attach these event handlers? John Rostron Hey guys, I know that there are two ways to declare an event in javascript. 1.Inline ie: <a href="#" onclick="function_name(param)">Link</a> 2.Traditional ie: linkelement.onclick = function_name; Now, how can the second method work with functions that have parameters??? Since we can't use parenthesis, how do we pass in the arguments?! Hello, I am working on a project that takes links on a page (Not all, depends on if they are Merchandise links or partner links), and passes some parameters to a tracking js call. The problem is, I don't want to put 'onclicks" on every href as there could be a hundred on a page and many of the links are dynamically generated on the backend. So, I was thinking of creating a function that took in parameters from each of the links that are pressed. But I was told "bind" is a good way to do this, but to be honest - it is very confusing to me. How would I do this? Lets say we have two links (there will be many more, but for an example sake). <a href="somelink.html" id="linka">link a</a> <javascript> var cu = new Linktracker({ dispPrice: 30, dispTitle: 'Manager', dispProduct: 'Red Shoes' }); $('linka').observe('click', cu.updateSomeFunc.bindAsEventListener(cu, 'dispPrice', 'dispTitle', 'dispProduct') ); </script> <a href="somelink.html" id="linkb">link b</a> <javascript> var cu = new Linktracker({ dispPrice: 10, dispTitle: 'casual', dispProduct: 'Blue Shoes' }); $('linkb').observe('click', cu.updateSomeFunc.bindAsEventListener(cu, 'dispPrice', 'dispTitle', 'dispProduct') ); </script> How does any particular click know I am referencing the correct "var cu"? Can something like this be done? <a href="somelink.html" id="linkc">link c</a> <javascript> $('linka').observe('click',( var cu = new Linktracker({ dispPrice: 30, dispTitle: 'Manager', dispProduct: 'Red Shoes' }); ) cu.updateSomeFunc.bindAsEventListener(cu, 'dispPrice', 'dispTitle', 'dispProduct') ); </script> What am I missing here? Should I use just "bind" or "bindAsEventListener"? Since each link on the page is unique and will pass different values, what is the best way to do this without putting "onclicks" on every link? Q1. write a function called countAS that will take a string as input (using a prompt dialog box,prompt the user or the string).the string must contain only a's,b's and c's e.g. "abccbbaa" or "aaabbbccc" if any other letters are present apart from the letters a b c, output an alert dialog box with an error message and prompt the user again to input a valid string.count the number of a's the numbers of b's and the numbers of c's entered and display the count for each as well as a total count of all the characters within the string . for example if the string was abbcc output should be as follows: the total count is 5 characters The Number of a's is 1 The Number of b's is 2 The Number of c's is 2 Q2. write a code that uses an event handler to display an alert dialog box with the message 'hello to you all' when a user clicks a link in a html page which links to the school of computing website. I have a piece of JavaScript code that should validate that a username field is not empty or null and that a telephone field is in the correct format using event handler registration. It seems to be validating fine but if there is an error it still manages to submit. HTML Code: <html> <head> <script type = "text/javascript" src = "js/validator.js" > </script> </head> <body> <form id = "decorForm" action = ""> <table border = "0"> <tr> <th>Username: </th> <td> <input type = "text" id = "myUserName" size = "15" maxlength = "15"/> </td> </tr> <tr> <th>Telephone: </th> <td> <input type = "text" id = "telephone" name = "telephone" size = "15" maxlength = "13"/> <br /> (999)999-9999 </td> </tr> <tr> <td> <input type = "submit" value = "Submit" /> </td> <td> <input type = "reset" value = "Reset" /> </td> </tr> </table> </form> <script type = "text/javascript" src = "js/validatorr.js" > </script> </body> </html> JAVASCRIPT (validator.js) Code: function chkUser() { // Verifies that the UserName field is not empty. var myUserName = document.getElementById("myUserName"); if (myUserName.value == "" || myUserName.value == null) { alert ("Please enter a Username!"); return false; } else { return true; } } function chkTelephone() { // Verifies that the Telephone field value is in the correct format. var tel = document.getElementById("telephone"); var pos = tel.value.search(/^\(\d{3}\)\d{3}-\d{4}$/); if (pos != 0) { alert ("Please enter telephone number in the following format: (999)999-9999"); return false; } else { return true; } } function chkFields() { // Verifes all fields and returns boolean to event handler // The event handler function if (chkUser() && chkTelephone()) { return true; } else { return false; } } JAVASCRIPT (validatorr.js) Code: //Register the event handlers for validator.js document.getElementById("decorForm").onSubmit = chkFields; I am trying to use this as an example. Please help me with this code to determine whether the check box has been checked. I get "Thank you" even if I don't check the check box. <script type="text/javascript"> var uncheck = document.getElementById().checked == false; var accept; function checkAccept() { var uncheck; if (uncheck == false){ alert ("You must accept the terms."); } else (uncheck == true) { alert ("Thank you."); } } </script> <form> <br />Please accept the terms by clicking the box below: <br />Accept terms: <input type="checkbox" id="accept" value="Y" /> <br /><input type="button" name="btn" value="Accept" onclick="checkAccept()" /> </form> </body> </html> Hi I am trying to develop a Qwerty Shifter http://www.cross-browser.com/toys/qwertyshifter.html by handling keyboard events. I want to display a textbox and as user type any text it changes at once means as user types "a" it display "s" "b" changes "n" for internet explorer I have script function InputEventKeyPress(event){ window.event.keyCode = shifter (window.event.keyCode); } //Key press function shifter (keyAscii) { switch (keyAscii){ //CAPITAL LETTERS A - Z case 65 : return 83; break; //A case 66 : return 78; break; //B case 67 : return 86 ; break; //C } } Hello, Is it possible to set an html element's (created through HTML DOM's createElement() method) 'onclick' attribute's value to a Javascript function which requires a parameter, passing a variable to it at the same time? I have the following Javascript code: Code: var parentDiv = document.getElementById("subscribers"); var stubSpan = document.createElement("span"); stubSpan.id = "opentok_subscriber_" + stream.streamId; stubSpan.onclick = showStreamInFullScreenMode(stream); parentDiv.appendChild(stubSpan); 'stream' in the bolded line is a parameter variable of the function that the above code is in, and I'm trying to pass it to another function using an onclick event. Can this be done, or am I crazy to be even trying to do this? Thanks in advance. Hello all, and thank you for your coments, I want to preserve a 16/9 aspect ratio to the window after any resize, making the width a function of the height. As I have a window.resizeTo() inside the window.onresize event function, the infinite loop is served. How may I quit it? Code: <html><head><title>Title</title><script languaje="javascript"> const c_ra=16/9; window.onresize = function WindowReSize() { var myWidth = 0, myHeight = 0; if( typeof( window.innerWidth ) == 'number' ) { //Non-IE // myWidth = window.innerWidth; myHeight = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE 6+ in 'standards compliant mode' // myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight; } myWidth = Math.floor(myHeight*c_ra); window.resizeTo(myWidth,myHeight); // ** CAUTION resize event in a onresize event handler ! }; </script></head><body><p>Hello World</p></body></html> Need help please...new to JS On Form submission, I am trying to pass a variable (var radioValue, which is the RadioButton selection) as Opt Label in the _gaq.push event tracker (google analytics)as follows onclick="_gaq.push(['_trackEvent', 'Visitor', 'Submit', radioValue]);" However radioValue value is not getting passed Code snippets are attached below. Not sure whether the problem is in the JS function or whether i am calling the var incorrectly in the _gaq.push script...Thank you The radioValue is captured in the overall form validation function as below. Hari ------------------------------------------------------------- (in HTML head) /////other overall form functions var radio_choice = false; for (counter = 0; counter < document.form.RadioGroup.length; counter++) { if (document.form.RadioGroup[counter].checked == true){ radio_choice = true; radioValue=(document.form.RadioGroup[counter].value); } } if (!radio_choice) { alert("Please select again."); return (false); } /////other overall form functions ------------------------------------------------------------ RadioButton Input script (in HTML body) <input name="RadioGroup" value="abc1" type="radio" />abc1</td><td> </td></tr> <input name="RadioGroup" value="abc2" type="radio" />abc1</td><td> </td></tr> <input name="RadioGroup" value="abc3" type="radio" />abc1</td><td> </td></tr> HTML CODE BELOW (JAVASCRIPT CODE FOLLOWS); Code: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>Text Object value Property</title> <script type="text/javascript" src="../jsb-global.js"></script> <script type="text/javascript" src="jsb-11-02.js"></script> </head> <body> <h1>Text Object value Property</h1> <form id="UCform" action="make-uppercase.php"> <p> <input type="text" id="converter" name="converter" value="sample"> </p> </form> </body> </html> This program below switches what is entered into the text filed to caps when hitting the enter button or the tab button. Can someone explain to me why it is not working. The answer would be helpful to a newbie who's trying hard to learn the fundamentals... Code: // initialize when the page has loaded window.onload = initialize; var oInput; // (global) input field to make uppercase // apply behaviors when document has loaded function initialize() { // do this only if the browser can handle DOM methods if (document.getElementById) { // apply event handler to the button oInput = document.getElementById('converter'); if (oInput){ var event = oInput.onchange; upperMe(event); } // apply event handler to the form var oForm = document.getElementById('UCform'); if (oForm) { var event = oForm.onsubmit; upperMe(event); } } } // make the text UPPERCASE function upperMe(evt) { // consolidate event handling if (!evt) evt = window.event; // set input field value to the uppercase version of itself var sUpperCaseValue = oInput.value.toUpperCase(); oInput.value = sUpperCaseValue; // cancel default behavior (esp. form submission) // W3C DOM method (hide from IE) if (evt.preventDefault) evt.preventDefault(); // IE method return false; } |