JavaScript - Addeventlistener Issue
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.... --> Similar TutorialsOkay, 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 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! 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! Hi 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. 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 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 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? 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> 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 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 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. Freaking IE. Must die. Really it must. Unfortunately, I have to code for it, and I can't figure out what went wrong he http://wyqued-design.com/dev/skyview/index.html The navigation, and layout, breaks in IE 7. Any ideas? -Emilie I have the following sample html file (attached). I am trying to display the calculated field using javascript and I created a function (I am a newbie) to do so. However, it persistently shows NaN instead of the required number. I have tried my best over a coupla hours racking my brains and the internet as to why it shows as not a number. I will appreciate any help. Thanks, Hello, The code below assigns a value to the Latitude and to the Longitude table cells when the submit button is pressed. I would like to have these values appear in text boxes instead. Obviously I need to amend onclick="javascript:usePointFromPostcode(document.getElementById('postcode').value, placeMarkerAtPoint)" to make this work but I can't seem to. Assuming two text boxes with names lng and lat, how would I amend the line? Thanks Code: <p align="left"> <table bgcolor="#FFFFCC" width="300"> <tr> <td width="100"> <b>Latitude</b></td> <td id="lat"> </td> </tr> <tr> <td width="100"> <b>Longitude</b></td> <td id="lng"> </td> </tr> </table> </p> <p> Postcode: <input type="text" id="postcode" size="10" value="IG3 8PY" /><br /> <input type="submit" value="Find" onclick="javascript:usePointFromPostcode(document.getElementById('postcode').value, placeMarkerAtPoint)" /><br /> <div id="map" style="width: 500px; height: 500px"> </div> <p> <script src="http://maps.google.com/maps?file=api&v=2.x&key=ABQIAAAA43oi4HUU6ay_KI5aLlgqqxRs1CMn3rnBr6PSR_9LSokba_k_xRRX9T_bJ1PRZQ_1n4nF3EOK" type="text/javascript"></script> <br /> <script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=ABQIAAAA43oi4HUU6ay_KI5aLlgqqxRs1CMn3rnBr6PSR_9LSokba_k_xRRX9T_bJ1PRZQ_1n4nF3EOK" type="text/javascript"></script> <br /> <script src="gmap.js" type="text/javascript"></script> </p> </body> </html> Alright,ill go straight to the problem. I want to get all the elements with a certain tag.However i can only get the first one. my code: Code: function getTags(tag) { var x = document.getElementsByTagName(tag); var y = x.length; for(var i = 0; i <= y;i++) { return x[i]; } } Hi Experimenting. Trying to add a simple onclick event via onload, but I can't get it right? This works: Code: function checkStatus(box){ if(box.checked != box.defaultChecked){ alert("box status has changed"); } } HTML <input type="checkbox" name="mycheckbox" id="mycheckbox" value="&cost=free" onclick="checkStatus(this)" /> This does not: Code: <input type="checkbox" name="mycheckbox" id="mycheckbox" value="&cost=free" /> window.onload = function (){ var mybox = document.getElementById('mycheckbox'); mybox.onclick = checkStatus ; //how to get this to work?? //none of the following work //mybox.onclick = checkStatus; //this calls the function but I don't have a box ref //mybox.onclick = checkStatus(); //mybox.onclick = checkStatus(this); //mybox.onclick = checkStatus(mybox); } LT hi, i have a problem with innerHTML if i wrote document.getElementById('someid').innerHTML = "ok"; then it wroks but when i wrote document.getElementById('someid').innerHTML = "<sometext> ok"; it does not work. i.e. <sometext> is not visible if check on firebug / dom it display.. <sometext> ok </sometext> please help.. how do i print / display above string as it as. you may download file or check below link.. please click here I am very new to coding, I am currently working on this design as my very first: http://img822.imageshack.us/img822/6533/unled1pd.jpg. I am currently working on the Image slider which is on the left side next to the login bar and headlines. I don't know where to start with this. If someone could walk me through or help me in anyway i would greatly appreciate it. Here is my current project LIVE: http://visionarycreativegrp.com/Demos/ForSale%20RED/# So I have a search function that searches through an XML file depending on which criteria the user wants to search. It works great so far in Firefox, OK in IE and not at all in Chrome. There's only one problem I have with IE which is you have to click submit, you cant hit the enter key to search. Is this fixable? Ive tried writing a function where if it detects the enter key press, it "clicks" submit, but that didn't work. In chrome, I search for something but it says there's nothing to be found. My code is below and any help or a point in the right direction would be greatly appreciated. Code: <script type="text/javascript"> if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } function getType() { for (var i=0; i < 3; i++) { if (document.frmMain.criteria[i].checked) { var rad_val = document.frmMain.criteria[i].value; } } return rad_val; } window.onload = loadIndex; function loadIndex() { // load indexfile // most current browsers support document.implementation if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument("", "", null); xmlDoc.load("wdparts.xml"); } // MSIE uses ActiveX else if (window.ActiveXObject) { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.load("wdparts.xml"); } } function searchIndex() { // search the index (duh!) if (!xmlDoc) { loadIndex(); } // get the search term from a form field with id 'searchme' var searchterm = document.getElementById("searchme").value; var searchtype = getType(); var allitems = xmlDoc.getElementsByTagName("item"); results = new Array; if (searchterm.length < 3) { alert("Enter at least three characters"); } else { // see if the XML entry matches the search term, // and (if so) store it in an array \ for (var i=0;i<allitems.length;i++) { var name = allitems[i].getAttribute(searchtype); var exp = new RegExp(searchterm,"i"); if ( name.match(exp) != null) { results.push(allitems[i]); } } // send the results to another function that displays them to the user showResults(results, searchterm); } } // Write search results to a table function showResults(results, searchterm) { if (results.length > 0) { // if there are any results, write them to a table var reout = 'You searched for <b><i>'+searchterm+'</i></b><br><br>'; reout += '<table border="1" style="width: 100%;">'; reout += '<tr><th>Manufacturer</th><th>Product Number</th><th>Description</th><th>Link</th></tr>'; for(var i=0; i<results.length; i++) { reout += '<tr>'; reout += '<td>' + results[i].getAttribute("line") + '</td>'; reout += '<td>' + results[i].getAttribute("pnum") + '</td>'; reout += '<td>' + results[i].getAttribute("description") + '</td>'; reout += '<td>' + results[i].getAttribute("link") + '</td>'; reout += '</tr>'; } reout += '<table>'; document.getElementById('test').innerHTML = reout; } else { // else tell the user no matches were found alert('No results found for '+searchterm+'!'); } } </script> Code: <p><form name="frmMain" id="frmMain" action=""> <b>Search by: </b> <input type="radio" name="criteria" value="line" checked="checked">Manufacturer <input type="radio" name="criteria" value="pnum">Product Number <input type="radio" name="criteria" value="description">Description <br><br> <input id="searchme" type="text" size="20"> <input value="Search" id="btnSearch" onclick="searchIndex(); return false;" type="submit"> </form></p> <p id = "test"></p> </div> EDIT: I also noticed that if i have a description like "Aluminum painted brush", I can search single words("aluminum" or "brush"), or words next to each other ("aluminum painted" or "painted brush") but I cant search separate words like "aluminum brush" and have it return the item because their is another word between the two. How would I edit it so that I can return the item? |