JavaScript - Using Addeventlistener To Attatch Dynamic Functions
Hi, I have the following code:
Code: function addHandlers() { var elementList = new Array(); elementList.push(new Element("newhomesdiv", "images/newhomes.png", "images/newhomes-over.png")); elementList.push(new Element("additionsdiv", "images/additions.png", "images/additions-over.png")); elementList.push(new Element("homeimprovdiv", "images/homeimprove.png", "images/homeimprove-over.png")); elementList.push(new Element("aboutusdiv", "images/aboutus1.png", "images/aboutus-over1.png")); for(var i = 0; i < elementList.length; i++) { var curNode = document.getElementById(elementList[i].parentId).firstChild; var item = elementList[i]; if(curNode) { /*if(curNode.addEventListener) { curNode.addEventListener("mouseover", function(){makeCallback(item.parentId, item.hoverImage)}, false); curNode.addEventListener("mouseout", function(){makeCallback(item.parentId, item.regImage)}, false); } else if(curNode.attchEvent) { curNode.attachEvent("onmouseover", function(){makeCallback(item.parentId, item.hoverImage)}); curNode.attachEvent("onmouseout", function(){makeCallback(item.parentId, item.regImage)}); } else { curNode["onmouseover"] = makeCallback(item.parentId, item.hoverImage); curNode["onmouseout"] = makeCallback(item.parentId, item.regImage); }*/ curNode.onmouseover = makeCallback(item.parentId, item.hoverImage); curNode.onmouseout = makeCallback(item.parentId, item.regImage); } } } function makeCallback(parId, image) { return function() { changeImage(parId, image); }; } function changeImage(parId, image) { document.getElementById(parId).firstChild.src = image; } The curNode.onmouseover = makeCallback(item.parentId, item.hoverImage); works, but I want to use addEventListener and fallback to the other methods. I don't understand why the addEventListener and attachEvent parts doesn't work. Any ideas? Similar TutorialsHi folks, I'm having problem setting up event handling using member functions. Consider the following code snippet: Code: function Widget() { ... this.register = function() { ... document.getElementById(this.id).addEventListener('click', this.default_click_handler, false); } this.default_click_handler = function(event) { this.do_something_useful(); //<--??? } this.do_something_useful = function() {...} } However I don't manage to call do_something_useful(), I get a this.do_something_useful() is not a function error. What am I doing wrong? Any help is appreciated, Thanks, A. Hi all, I am a relatively new to javacript and need some help. I have several arrays already defined: array_1 array_2 array_3 etc. I also have a few divs with ids and classes: <div id="1" class="sample"></div> <div id="2" class="sample"></div> <div id="3" class="sample"></div> etc. I am trying to use the class (sample) to run a function: (1) first I get the ID: current_id = $(this).attr("id"); (2) based on the id I want to display the array: alert('array_'+current_id); The problem is I get an alert box with the array name ("array_1") and not the CONTENT of the array. How do i solve this? Thanks!! Okay, I'm really am not getting this. So I came here hopefully for some help. I'm just trying to register a simple click event onto a input element with addEventListener and attachEvent... My code: Code: function addEvent(type, func, elem) { var netscape = document.getElementById && !document.all; var ie = document.all; if(netscape) { elem.addEventListener(type, func, true); } else if(ie) { elem.attachEvent('on'+type, func); } } //Which is then call by addEvent('click', someFunction, theElementObject); So say I had the following code like so: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en"> <head> <title>Example</title> <link rel="stylesheet" type="text/css" href="./css/global.css" /> <script type="text/javascript"> function addEvent(type, func, elem) { var netscape = document.getElementById && !document.all; var ie = document.all; if(netscape) { elem.addEventListener(type, func, true); } else if(ie) { elem.attachEvent('on'+type, func); } } function clearTxt() { var username = document.getElementById('username'); if(username.value == 'Screen Name') { username.value = ''; } } addEvent('click', clearTxt, document.getElementById('username')); </script> </head> <body> <label for="username">Username:</label> <input name="username" type="text" value="Screen Name" id="username" maxlength="20" /> </body> </html> From what I can see and what I understand it should just on event of a click on the username input it should clear the username field. But instead I get a error message from IE saying, "null is null or not a object"???? Like that was any help. So could someone please help me figure out my misunderstanding of this method? Thanks, Jon W I'm trying to add an event handler for to my body, and for some reason which I can't figure out, it only works on Google Chrome. I wouldn't expect it to work in IE, but am wondering why it's not working in Firefox. Here's the relevant parts of the code: Javascript (in an external file) Code: var body = document.body; body.addEventListener("load", Foo(), false); function Foo(){ addEventListener(document.getElementsByName("start"),"click", alert("hello"), false); } HTML Code: <html> <head> <title>BREAKOUT!</title> <script src="breakout.js" type="text/Javascript" > </script> <LINK REL="stylesheet" HREF="breakout.css" TYPE="text/css"> </head> <body id="body"> <!-- etc.... --> Is it possible to add events using addEventListener to multiple radio buttons with same id ? <input id="radId" type="radio" value="0" name="radioname">No <input id="radId" type="radio" value="1" name="radioname">Yes I tried to attach event using document.getelementByID BUT it always picks the first radio button. Is there a way around this, any help would be highly appreciated. Thanks I have created this statement and it does its job but not very efficient. How can I put this in a loop and populate the information that I want anonymously? I do not want to copy and paste this for every (id) there is on this page. Locate id get value and use same value to change the bgColor of the page Code: <input id="red" value="red">red <input id="green" value="green">green <script> document.getElementById('red').addEventListener('click', function (e) { inputColor = e.target.getAttribute('value'); document.bgColor = inputColor; }, true); <script> Your help will be much appreciated! Thanks! I'm trying to understand how a custom object can call a function within itself. Say I have something like this: Code: function functiontest() { this.prop1 = '', this.prop2 = '', this.options = {initiallevels:0}, this.prop3 = '/blah', this.prop4 = true, this.function4 = function(x) { console.log(x) }, this.init = function(options) { this.uid=options.uid this.t=options.target document.getElementById(this.t).addEventListener('click',function(){this.uid.function4(this.t)},false) } } myfun1=new functiontest myfun1.init({uid:'myfun1',target:'target1'}) myfun2=new functiontest myfun2.init({uid:'myfun2',target:'target2'}) And the html: Code: <html> <head></head> <body> <div id="target1">T1</div> <br> <div id="target2">T2</div> </body> </html> I don't know what to put in the part in bold to set the click event listener and have it call function4 within the functiontest object. I've tried a bunch of different things and nothing worked. Please help, thanks! Code: function offPar(){ alert(this.offsetParent.id); } function init(){ var mine = document.getElementById("mid"); var other = document.getElementById("inner"); mine.addEventListener("click", offPar, false); other.addEventlistener("click", offPar, false); } window.addEventListener('load', init, false); HTML : <div id = "content"> <div id = "mid"> <div id = "inner"> <p class = "par"> </p> </div> </div> </div> I can add an event listener to the #mid div but I can't to the #inner div. Anyone now why this is? Sorry I can't provide more info. That's all I Know! TTFN John On my site we have image galleries that pop up over top of the page in a higher z-index and position:fixed, and another div between the gallery and background with opacity set to about 85%. The image gallery div has a close button, and I was asked to make the gallery also close by pressing ESC, so I added this: igevt=function(evt){checkclosegal(evt)} window.addEventListener('keypress',igevt, false) and checkclosegal: function checkclosegal(evt) { if(evt.keyCode==27) { closebgeagal() window.removeEventListener('keypress',igevt, false) } } This works perfectly in Firefox and Opera, but Chrome and Safari don't fire the event (not worried about ie right now - I know it uses attachEvent). Could it have something to do with the gallery being in a higher z-index? Please help, thanks! Every time i click on one of the said elements, it puts "undefined" into the textbox each time i click on an element. it seems to me that the Key_Table[x] is not getting passed correctly. How do i make sure that this is getting passed correctly? Here's my Code: Code: <script type='text/javascript'> // Startup Script if (document.addEventListener) { document.addEventListener("DOMContentLoaded", LoadEventListeners, false); } function LoadEventListeners() { var Key_Table = ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"]; // Create event Listeners for the alphabetic keys for(var x = 0; x < Key_Table.length; x++) { Key_Table[x] = document.getElementById(Key_Table[x]); Key_Table[x].addEventListener("click", function(){ InsertChar(Key_Table[x]); }, false); } } function InsertChar(Char) { alert("Char is:" + Char); // Textbox data document.getElementById('TextData').value = document.getElementById('TextData').value + Char; } </script> Good day! Here is the problem, setting the slider to the site, here's an example: http://wowslider.com/best-jquery-sli...near-demo.html and do not connect different effects on this slider, such as buttons on the sides and smooth shifting slides. When you see the code generates this error: Uncaught TypeError: Cannot read property addEventListener' of undefined I do not know what this error, help, error on this site: http://uh219381.ukrdomen.com/ Or here's the code: http://uh219381.ukrdomen.com/themes/...1/wowslider.js sorry for my English Hi there Im trying to create a function where i pass two element id's and my script populates it with events and anything else it may need to run but what i am finding is that i cant use this so that the instance of the object is kept what ends up happening is nothing at all what i would like to have happen is the code to work somthing like this... Code: <div id="iAmTheTargetId"> </div> <div id="iWillHoverOverYouId"> </div> <script type="text/javascript"> var element = new hoverBox('iAmTheTargetId','iWillHoverOverYouId'); </script> and simply running that would then create the equivalent of doing Code: <div id="iAmTheTargetId" onmouseover="element.activate()" onmouseout="element.deactivate()" onmousemove="element.update(event)> </div> <div id="iWillHoverOverYouId"> </div> <script type="text/javascript"> var element = new hoverBox('iAmTheTargetId','iWillHoverOverYouId'); </script> But of course the code above won't actual add onmouseover and etc it just so you can see what i'm trying to achieve Code: /* * triggerId * the element in which the attributes will be applied to * * hoverBoxid * the element in which will hover around the triggerId */ function hoverBox(triggerId,hoverBoxid){ this.triggerElement = document.getElementById(triggerId); this.hoverBoxElement = document.getElementById(hoverBoxid); if(this.triggerElement == null || this.hoverBoxElement){ return null; } self = this; alert(this.triggerElement); this.triggerElement.addEventListener('mouseover',function(){self.activate();},false); this.triggerElement.addEventListener('mouseout',function(){self.deactivate();},false); this.triggerElement.addEventListener('mousemove',function(){self.update(event);},false); } hoverBox.prototype = { triggerElement : null, hoverBoxElement : null, state : false }; hoverBox.prototype.activate = function(){ this.state = true; }; hoverBox.prototype.deactivate = function(){ if(this.state != false){ this.hoverBoxElement.style.display = "none"; this.state = false; } }; hoverBox.prototype.update = function(evt){ if(this.state != false){ this.hoverBoxElement.style.display = "block"; this.hoverBoxElement.style.position = "absolute"; this.hoverBoxElement.style.top = (evt.clientY + 5)+ "px"; this.hoverBoxElement.style.left = (evt.clientX + 10)+ "px"; } }; A quick note theses function will work by them selfs if you just do Code: <div id="target" onmouseover="aHoverBox.activate()" onmouseout="aHoverBox.deactivate()" onmousemove="aHoverBox.update(event)"> </div> <div id="hover"> </div> <script type="text/javascript"> var aHoverBox = new hoverBox('iAmTheTargetId','iWillHoverOverYouId'); </script> But not quite what I'm after i would like not to have to enter in Code: onmouseover="aHoverBox.activate()" onmouseout="aHoverBox.deactivate()" onmousemove="aHoverBox.update(event)" and have that done by the JavaScript Well i hope every thing makes scene sorry if i repeated my self just making sure you understand me Hi, I have written a number of functions designed to return frequency data on 1000 randomly chosen numbers using different math functions for the rounding. I would like to include all of these functions within the wrapper of another function so that only one call is needed to get returns from all of the 'inner' functions. However, while each of the functions works in isolation, the moment I wrap them in another function they stop working. The following code is one of the functions 'frequencyWrapperOne' that has been wrapped in the function 'testWrapper'. A call to testWrapper does nothing. Can anyone see what I'm doing wrong? Code: function testWrapper() { function frequencyWrapperOne() { var numberArrayOne = new Array(0,0,0); for (var i = 0; i < 1000; i = i + 1) { var chosenNumber = Math.floor(Math.random() * 3); if (chosenNumber == 0) { numberArrayOne[0] = numberArrayOne[0] + 1; } if (chosenNumber == 1) { numberArrayOne[1] = numberArrayOne[1] + 1; } if (chosenNumber == 2) { numberArrayOne[2] = numberArrayOne[2] + 1; } } return window.alert(numberArrayOne.join(',')); } } testWrapper(); Thanks. Ok here is what I have so far, my ending part of my Call Function I think is ok. for my main function. I think I misplaced the { and } I will show you all the codes I have for my main function this is what I have I think I did misplace something but I can not pin point where that one small things should be Code: unction showResults(race,name,party,votes) { // script element to display the results of a particular race var totalV = totalVotes(votes); document.write("<h2>" + race + "</h2>"); document.write("<table cellspacing='0'>"); document.write("<tr>"); document.write("<th>Candidate</th>"); document.write("<th class ='num'>Votes</th>"); document.write("<th class='num'>%</th>"); document.write("</tr>"); } for (var i=0; i < name.length; i++) { document.write("<tr>"); document.write("<td>" name[i] + "(" + party[i] + ")</td>"); document.write("td class='num'>" + votes[i] + "</td>"); var percent=calcPercent(votes[i], totalV) document.write("<td class='num'>(" + percent +"%)</td>"); createBar(party[i],percent) document.write("</tr>"); } document.write("</table>"); } </script> Just wondering if i misplaced any ; or { or } anywhere suggestions? Here is my call function Code: <script type="text/javascript"> showResults(race[0],name1,party1,votes1); showResults(race[1],name2,party2,votes2); showResults(race[2],name3,party3,votes3); showResults(race[3],name4,party4,votes4); showResults(race[4],name5,party5,votes5); </script> I been going over this, I can not seem to figure out what { i might be missing? Thanks Is there a way to activate a function from another function? It has to be in the script tag, it can't be in the HTML section. Can I use something similar to this following code? If not, can anyone give me some help? I have tried to do it various ways, and have looked it up a few times, but to no avail. Can I use something similar to this following code? If not, can anyone give me some help? if (condition) {activate functionname();} Any help I can get would be appreciated. Thanks a lot to anyone who can help. Hi All, i know how to create a dynamic form or DIv ..but what i do not know is how to create a dynamic form/ or div into a previous dynamic one.. i need basically to see 5 dynamic forms / DIV in cascade where each one trigger the one coming after.. For what i need that : i have my user inserting information on the level 1. let say Copagny info 2- then he will be asked if he wants to add a sub level information ( subform) for that compagny or even many subforms at the same level .. and so on... 3- those sub level ( subforms ) can also call their respective subforms.. Any idea how to design this ? thanks I have made a script where you can add extra fields, and next to the row is a span that automatically displays the outcome from a calculation of three fields in that row. i.e. Q x (B - A) = total. Here is the bit that does the calculation: Code: function advCalc(selected) { var result = Number(document.formmain.elements["quantity"+selected].value) * (Number(document.formmain.elements["provideamount"+selected].value) - Number(document.formmain.elements["supplyamount"+selected].value)) ; result = result.toFixed(2) ; result = addCommas(result) ; document.getElementById("total"+selected).innerHTML = result ; } The bit that adds a new row of fields is: Code: function addPart(divName){ var newdiv = document.createElement('div') ; newdiv.setAttribute('id', 'partrow' + counter) ; newdiv.setAttribute('style', 'clear:both;') ; newdiv.innerHTML = "<div style='float:left;width:40px;text-align:center;margin:5px 5px 0px 0px;'>\r<input onkeyup=\"advCalc('" + counter + "')\" id=' quantity " + counter + "' type='text' value='1' size='1'/>\r</div>\r<div style='float:left;width:100px;text-align:left;margin:5px 0px 0px 0px;'>\r<input id='manufacturer" + counter + "'type='text' value='' size='9'/>\r</div>\r<div style='float:left;width:95px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='partnumber" + counter + "'type='text' value='' size='9'/>\r</div>\r<div style='float:left;width:80px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='supplier" + counter + "'type='text' value='' size='4'/>\r</div>\r<div style='float:left;width:100px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='type" + counter + "'type='text' value='' size='6'/>\r</div>\r<div style='float:left;width:85px;text-align:left;margin:5px 5px 0px 0px;'>\r<input id='deliverytime" + counter + "'type='text' value='' size='13'/>\r</div>\r<div style='float:left;width:40px;text-align:left;margin:5px 0px 0px 45px;'>\r<select id='supplyCurrency" + counter + "'>\r<option value='pound' selected='selected'>£</option><option value='dol'>$</option><option value='euro'>€</option></select>\r</div>\r<div style='float:left;width:15px;text-align:left;margin:5px 5px 0px 0px;'>\r<input onkeyup=\"advCalc(\'" + counter + "\')\" id=' supplyamount " + counter + "'type='text' value='' size='3'/>\r</div>\r<div style='float:left;width:40px;text-align:left;margin:5px 0px 0px 45px;'>\r<select name='provideCurrency" + counter + "'><option value='pound' selected='selected'>£</option><option value='dol'>$</option><option value='euro'>€</option></select>\r</div>\r<div style='float:left;width:15px;text-align:left;margin:5px 5px 0px 0px;'>\r<input onkeyup=\"advCalc(\'" + counter + "\') id=' provideamount " + counter + "' type='text' value='' size='3'/>\r</div>\r<div style='float:left;width:20px;text-align:left;margin:5px 0px 0px 45px;'>\r<strong>£</strong>\r</div>\r<div style='float:left;width:40px;text-align:left;margin:5px 5px 0px 0px;'><span id=' total " + counter + "'></span></div> \r" ; document.getElementById(divName).appendChild(newdiv) ; counter++ ; } The problem I am having is that it works fine for the first row which is hardcoded as e.g. id="provideamount0" etc. It isn't working for any other fields added but I can't see what is wrong In my discovering more about OOP with javascript, I ran into the following oddity: The following doesn't work as expected inside an object constructor: Code: var MyClass = function() { this.myvalue = "abc"; document.getElementById('clickable').addEventListener('click', this.clickHandler, false); } MyClass.prototype.clickHandler = function(evt) { alert(this.myvalue); // "undefined" - even though I set it to "abc" in the constructor??!!!???!!!! } But this works as I would expect: Code: var MyClass = function() { this.myvalue = "abc"; var self = this; document.getElementById('clickable').addEventListener('click', function(evt) { self.clickHandler(evt); }, false); //Lamda function. } MyClass.prototype.clickHandler = function(evt) { alert(this.myvalue); // "abc" - as expected. } So, why does the second example work as expected and the first does not? My (assumed) logic tells me that the object pointed to by "this" in the first example already exists at the point where addEventListener is called, therefore this.clickHandler is a valid reference ... but it doesn't seem to work unless I use the intermediate lamda function, as per the second example. I don't get it. . Why do we have functions without parentheses at times? Ex 1) http://www.youtube.com/watch?v=OHYFNDzlDTE (On 2:18) Ex 2) At the bottom: Code: var panel, flag; function mousemoveResponse(e) { var x, y; if( window.event ) { x= event.x; y=event.y; } else if(e) { x=e.pageX; y=e.pageY; } if(flag) { panel.innerHTML = "Mouse is at X: " + x + ", Y: " + y ; } } function mouseoverResponse() { flag = false; panel.innerHTML = "Mouse is Over"; } function mouseoutResponse() { flag = true ; } function init() { panel=document.getElementById("panel"); flag = true; panel.innerHTML="Move the mouse..." ; document.onmousemove=mousemoveResponse; panel.onmouseover=mouseoverResponse; panel.onmouseout=mouseoutResponse; } onload=init; |