JavaScript - Adding Event Listener As Attribute Breaks
Hello;
I am testing some code that finds and element and attempts to add an event handler attribute to it as 'onclick' (test case in Firefox 3.5.9) /* The actual code is: window.onload = function() { //<irrelevant code> var test = document.getElementById('tstEl'); test.setAttributeNode('onclick'); test.setAttribute('onclick', "alert(\"Don\'t get testy\")"); } */ The error per the js console in Firefox is: Error: uncaught exception: [Exception... "Could not convert JavaScript argument arg 0 [nsIDOMHTMLInputElement.setAttributeNode]" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://192.168.1.6/<pathInfo>/SC_branch2_dev.php :: anonymous :: line 35" data: no] I am trying to do this because Element.addEventListener or Element.attachEvent won't allow for arguments to be passed to the event handler code/function. What is going on here? The only line referenced, line35, in the document text containing javascript code is irrelevant to the problem. Thank you for time, interest and attention; WhoEverIReallyAm Similar Tutorialshello, I am trying to add a window event listener on some links in a loop instead of doing them one by one. I've tried Code: function setListeners (){ for (var i = 0; i < document.links.length; i++) { src=document.links[i].href; document.links[i].onmousemove=changeIframeSrc(src, 'solid',1, event); document.links[i].onmouseout=changeIframeSrc(null,'none',0,event); } } and Code: function setListeners (){ for (var i = 0; i < document.links.length; i++) { src=document.links[i].href; document.links[i].onmousemove=function(a1,a2,a3,a4){ return function(){changeIframeSrc(a1,a2,a3,a4);} }(src, 'solid',1, event); } } but the event keeps coming up undefined. Any ideas on how to do this? Dammit, for some reason this script has stopped working :/ When I click the links with the ID's of "login_dialog" and "register_dialog" a div should be shown... I'm using an event listener to do this. Code: function listener_items() { //Text field background addEvent(document.getElementById('input_username'), "click", add_username_password); addEvent(document.getElementById('input_username'), "blur", remove_username_password); addEvent(document.getElementById('input_password'), "click", add_username_password); addEvent(document.getElementById('input_password'), "blur", remove_username_password); //Switch between forms addEvent(document.getElementById('dialog_login'), "click", login_dialog_login); addEvent(document.getElementById('dialog_register'), "click", login_dialog_register); addEvent(document.getElementById('dialog_recovery'), "click", login_dialog_recovery); //Display Dialog addEvent(document.getElementById('login_dialog'), "click", navbar_login); addEvent(document.getElementById('register_dialog'), "click", navbar_register); //Close Dialog addEvent(document.getElementById('close_dialog'), "click", login_dialog_close); } //Login dialog, login form input fields background text var add_username_password = function() { add_input_text(this); }; var remove_username_password = function() { remove_input_text(this); }; //Login dialog buttons var login_dialog_login = function() { display_form('login'); }; var login_dialog_register = function() { display_form('register'); }; var login_dialog_recovery = function() { display_form('recovery'); }; //Close dialog var login_dialog_close = function() { display_dialog('login', 'hidden'); }; //Navigation bar buttons var navbar_login = function() { display_dialog('login', 'visible'); }; var navbar_register = function() { display_dialog('register', 'visible'); }; //This function attaches events to elements. var addEvent = function( elm, evt, fun ) { if ( elm.addEventListener ) { elm.addEventListener( evt, fun, false ); } else if ( elm.attachEvent ) { elm.attachEvent( 'on' + evt, fun ); } else { elm [ 'on' + evt ] = fun; } }; addEvent ( window, "load", listener_items ); //Display/Hide login dialog function display_dialog(dialog, fun) { //Define the active menu item style var active_style = "border-right-width:3px; width:113px; border-right-color:#33CCFF; color:#FFFFFF;"; //Creat array with all forms var formsHide = Array("login","register","recovery"); var i = 0; document.getElementById('wrapper').setAttribute('style', 'visibility:' + fun); for ( i = 0; i < formsHide.length; i++ ) { if ( formsHide[i] == dialog && fun == 'visible' ); document.getElementById("dialog_" + dialog).setAttribute('style', active_style); document.getElementById(formsHide[i] + "_form").setAttribute('style', 'visibility:visible'); formsHide.splice(i, 1); } document.getElementById(formsHide[i] + "_form").setAttribute('style', 'visibility:hidden'); } } //Put text in fields if there is not data, also switch text field to password field //when focused on. Switch back to text field if no text is entered. function add_input_text(obj) { var id = obj.id.split("input_"); document.getElementById(id[1]).innerHTML = ''; } function remove_input_text(obj) { if (obj.value.length == 0) { var id = obj.id.split("input_"); var id2 = id[1].substr(0, 1).toUpperCase() + id[1].substr(1); document.getElementById(id[1]).innerHTML = id2; } } function display_form(form) { //Define the active menu item style var active_style = "border-right-width:3px; width:113px; border-right-color:#33CCFF; color:#FFFFFF;"; var forms = Array("login", "register", "recovery"); for ( c = 0; c < forms.length; c++ ) { if ( forms[c] == form ) { document.getElementById( forms[c] + "_form" ).style.visibility = "visible"; document.getElementById("dialog_" + forms[c]).setAttribute('style', active_style); document.getElementById("dialog_" + forms[c]).setAttribute('class', 'overlay_table' + ' ' + forms[c] + ' active'); forms.splice(c, 1); } } for ( c = 0; c < forms.length; c++ ) { document.getElementById("dialog_" + forms[c]).setAttribute('style', '') document.getElementById( forms[c] + "_form" ).style.visibility = "hidden"; document.getElementById("dialog_" + forms[c]).setAttribute('class', 'overlay_table' + ' ' + forms[c]); } } HTML: Code: <span><a href="#" id="login_dialog" style="color:#33CCFF;">Login</a></span> <span><a href="#" id="register_dialog" >Register</a></span> I can't seem to get the event listener to run an event when I focus on the text field with the ID username. JavaScript: Code: function listener_loginForm() { var fields = Array("username","password"); for ( j = 0; j < fields.length; j++ ) { var objs = document.getElementById(fields[j]); for ( var i = 0; i < objs.length; ++i ) { var elm = objs [ i ]; elm.onblur = function() { display_text_bg(this); }; if (elm.Id = "password") { elm.onfocus = function() { switch_field(this); }; } } } } //This function attaches events to elements. var addEvent = function( elm, evt, fun ) { if ( elm.addEventListener ) { elm.addEventListener( evt, fun, false ); } else if ( elm.attachEvent ) { elm.attachEvent( 'on' + evt, fun ); } else { elm [ 'on' + evt ] = fun; } }; addEvent ( window, "load", listener_loginForm ); //Put text in fields if there is not data, also switch text field to password field //when focused on. Switch back to text field if no text is entered. function display_text_bg(obj) { alert("remove text"); } function switch_field(obj) { alert("switch"); } HTML: Code: <form name="login" class="login"> <label for="username">Username: </label><br /> <input type="text" name="username" id="username" /> <br /><br /> <label for="password">Password: </label><br /> <input type="text" name="password" id="password" /> <br /><br /> <label for="remember">Remember Me? </label><br /> <br /> <span class="remember"> <span class="text">Never</span> <input type="hidden" value="never" name="rememberme" /> <ul> <li>Never</li> <li>24 Hours</li> <li>1 Week</li> <li>Always</li> </ul> </span> </form> Please can someone explain to me in simple terms which this actually does. From what I understand it will check all events until a defined event happens, such as rollover of a certain image, and then it activates a function? What I want to do is use this so that when I rollover a element such as below: Code: <img src="img url" alt="this is a tooltip" tooltip="true" /> I want it to pass the obj to a function which then runs, and then once the mouse of not over that element it will activate another function passing the previous object to this function. Although an element such as the example below would not activate these functions: Code: <img src="img url" alt="this is a tooltip"/> As the tooltip tag does not exist or has the value of false... Also, wouldn't this use a lot of resources as it checks every event which the mouse passes over? here the deal ,,I've solved all but this problem in my script i have my page setup with 1 iframe and the main html the code below is exactly how the page will show up in the iframe, you can copy and paste the whole thing and save it as a htm file to view if needed.. I need a way to catch the clicks that happen within the iframe but from the main section of the page..heres why! this is inserted at the top of the page if(top.location==self.location){top.location="RefESI_search.asp";} just above top.document.reset.RefCat.value= I can get the page to load even with this in the iframes ..but for the purposes of this i left it out so the page would load ok for anyone thats gonna try and help . theres only 2 links in the code.. hopefully whatever will hopefully solve this problem will be able to tell which links were clicked,and i can can point them to the apropriate links. I've looked thru alot of the threads so i know there are some extremely brite ppl in here that can knock this problem out of the ball park very easily.. you can grab the styles sheet from here https://www.docs.sony.com/reflib/Style_esi.css Code: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Ref_Lib_Results</title> <link rel="stylesheet" type="text/css" href="home.css"/> <script language="javascript"> top.document.reset.RefCat.value="Home Receiver"; top.document.reset.NarrowRef.value="Good"; top.document.reset.criteria.value="stra"; top.document.reset.searchscope.value="model"; top.document.reset.companyscope.value="SONY"; top.document.reset.company.value="SONY"; if(""==""){top.reset();} function popUp(URL,Name) { var day = new Date(); var id = "page" + Name; window.open(URL, id, "toolbar=1,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=600,height=600"); } function launchjsmanuals(flag, x, y, z, id) { //var myTypeLib = new ActiveXObject("Scriptlet.Typelib"); //var GUID = new String(myTypeLib.guid).substr(1,8); //var endguid = new String(myTypeLib.GUID).substr(25,10); if((x.indexOf("CHM")!=-1) || (x.indexOf("chm")!=-1)){ alert("You will be prompted to download a file\n\nClick Open - Do NOT click Save"); } var whnd = "page" + id; //+ GUID + endguid; var URL = '_manualusage.asp?flag='+flag+'&manual=' + x + '&user=' + y + z + '&manualid=' + id; if(flag!=""){ whnd = window.open(URL,whnd, "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=560,height=600"); }else{ whnd = window.open(URL,"Loader", "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=560,height=600"); } } function emailit(id, url,name,type,filesize,model,email,custname,cs3event,user){ var namestring = name; var re = new RegExp('&','gi'); namestring = namestring.replace(re,'and'); name = namestring; var xurl = "/srvs/common/email.asp?id="+id+"&emailurl="+url+"&title=" + name + "&type="+type+"&model=" + model + "&filesize=" + filesize + "&email=" + email + "&custname=" + custname + "&convid=" +cs3event + "&user=" + user; popUp(xurl,id); } function NarrowSearch(what,value,cat){ switch(what){ case "Category": parent.document.SearchForm.RefCat.value=value; parent.document.SearchForm.NarrowRef.value="Good"; parent.document.SearchForm.submit() break; case "Model": if("Home Receiver"!=""){ parent.document.SearchForm.RefCat.value="Home Receiver"; } parent.document.SearchForm.criteria.value=value; parent.document.SearchForm.searchscope.value="model"; parent.document.SearchForm.NarrowRef.value="Good"; parent.document.SearchForm.submit() break; case "ONLY": parent.document.SearchForm.criteria.value=value; parent.document.SearchForm.searchscope.value="model"; parent.document.SearchForm.RefCat.value=cat; parent.document.SearchForm.NarrowRef.value="Only"; parent.document.SearchForm.submit() break; case "ALL": parent.document.SearchForm.criteria.value=value; parent.document.SearchForm.RefCat.value=cat; parent.document.SearchForm.NarrowRef.value="ALL"; parent.document.SearchForm.submit() break; } } </script> </head> <body> <div id="results"> <div style="height: 400px;border-bottom:1px solid black;" class="modelblock"> <div style="margin-left:20px; margin-right:15px; margin-top:10px; font-size:10pt"> <span style="float:Right;margin-top:10px;text-align:right"> <table border=0 cellpadding=0 cellspacing=0><tr><td> <div style="background:silver;color:black;font-size:10px;padding:2px;border:1px solid gray;cursor:pointer" onclick="javascript:NarrowSearch('ALL','stra','Home Receiver')">Display All Models</div> </td><td> </td><td><div style="width:40px;background:silver;color:black;font-size:10px;padding:2px;border:1px solid gray;cursor:pointer;text-align:center" onclick="javascript:history.go(-1)">Back</div></td></tr></table></span><b>Your search of "<font color=green>stra</font>" matches 66 Models in the Home Receiver category.</b><br><br>Please select the specific model to continue:<table border=0 cellpadding=0 cellspacing=2><tr><td><a class="modellink" onMouseOver="this.className='modellinkhover'" onMouseOut="this.className='modellink'" onclick="javascript:NarrowSearch('ONLY','STRAV1000','Home Receiver')"><b>STRA</b>V1000</a></td><td width=15px></td><td><a class="modellink" onMouseOver="this.className='modellinkhover'" onMouseOut="this.className='modellink'" onclick="javascript:NarrowSearch('ONLY','STRAV1010','Home Receiver')"><b>STRA</b>V1010</a></td><td width=15px></td></tr></table</div></div></div> <iframe name="Loader" id="Loader" src="blank.htm" style="display:none;height:150px;width:100%;border:1px solid silver"></iframe> <a onclick="document.getElementById('Loader').style.display='';">*</a> <script language="javascript"> //alert(parent.IQ.location.href); </script> </body> </html> I'm trying to simulate a textfield on a canvas; that is when clicking on the text box a cursor appears and blink. My problem here is when I create more than one object, the event listener will work only on the last object created. Here is my code: Javascript Code: var canvas; var ctx; var MousePosX; var MousePosY; var Cursor_Width = 1; var Cursor_Height = 21; var Height = 27; var LapseTime = 800; function init(CanvasName) { canvas = document.getElementById(CanvasName); ctx = canvas.getContext("2d"); } /* Create Textfiled */ function Textfield(x, y, w) { Textfield.prototype.x = x; Textfield.prototype.y = y; Textfield.prototype.w = w; Textfield.prototype.Cursor_PosX = x + 3; Textfield.prototype.Cursor_PosY = y + 3; // draw rectangle ctx.beginPath(); ctx.rect(this.x, this.y, this.w, Height); ctx.closePath(); ctx.stroke(); // listen for mouse click event canvas.addEventListener("mousedown", function(evt) { // calculate mouse coordination on canvas MousePosX = evt.clientX - canvas.offsetLeft; MousePosY = evt.clientY - canvas.offsetTop; // if mouse coordination is within texfield display cursor if((MousePosX > Textfield.prototype.x && MousePosX < (Textfield.prototype.x + Textfield.prototype.w)) && (MousePosY > Textfield.prototype.y && MousePosY < (Textfield.prototype.y + Height))) { Textfield.prototype.cursor(); } }); } /* Cursor for textfield */ Textfield.prototype.cursor = function() { // alert("good"); ctx.beginPath(); ctx.strokeStyle = "black"; ctx.rect(this.Cursor_PosX, this.Cursor_PosY, Cursor_Width, Cursor_Height); ctx.closePath(); ctx.stroke(); setTimeout("Textfield.prototype.animate_cursor()", LapseTime); }; /* Change color of cursor to white to make blinking effect */ Textfield.prototype.animate_cursor = function() { ctx.strokeStyle = "white"; ctx.stroke(); setTimeout("Textfield.prototype.cursor()", LapseTime); }; HTML Code: <!DOCTYPE HTML> <html> <head> <style> #MyCanvas { border: 1px solid #000000; } </style> <script src="widgets1.js"></script> <script> window.onload = function () { init('MyCanvas'); var tf1 = new Textfield(10.5, 10.5, 150); var tf2 = new Textfield(10.5, 50.5, 150); }; </script> </head> <body> <br /><br /><br /> <center> <canvas id="MyCanvas" width="700" height="500"> </canvas> </center> </body> </html> What i want to achieve here is have my event listener on any textfield created on the canvas. Hi Everyone, How would i add an avent listener to change the source of an image? I have added the image to a canvas element through javascript using the code below. Code: var start = new Image(); start.src = "start.jpg"; ctx.drawImage(start, 50, 50); Thanks! Hello! I'm working with nested functions and trying to pass a 'this' value to an anonymous being used in an assignment for an event listener. Here's the basics of my code: Code: <div id='abc'></div> <script type='text/javascript'> var abc = function () { this.myFunction = function() { var myObj myObj = document.createElement("input"); myObj.setAttribute("type", "button"); myObj.setAttribute("value", "Click Me"); myObj.addEventListener("click", function () { this.doDing(); }, false); document.getElementById('abc').appendChild(myObj); } this.doDing = function () { alert('ding'); } } var myInstance = new abc(); myInstance.myFunction(); </script> So, this should plop a button inside our DIV and when clicked I'd like it to run the alert-ding; unfortunately it seems to want to run the function as defined under the buttons object which doesn't work out too well. Any suggestions? Thanks! Hey Guys, Im a PHP developer and am quite new with javascript. I wanted some help on the hyperlink onclick event. Bascially I output a list of a href hyperlinks on a html page that goes all the way to the bottom of the screen. I wanted to add a onclick event to the a href tag that would pust the user right to the top of the page. I want to achieve this using javascript onclick event. Can someone plz point me in the right direction! Thanks, Ket Hi all, I can't seem to add an onclick event to an image. I'm sure I am doing something wrong as I am very new to Javascript. This is a part of my javascript code that is in the head and body of my HTML file: Code: <head> <script language="JavaScript"> ..... ..... var redLocation0 = redArray[0]+".jpg"; .... .... function redClick( buttonLocation ) { window.location = "http://www.yahoo.com/" } .... .... </script> </head> <body> <table> <tr> <td> <script language="javascript">document.write('<IMG SRC="'+ redLocation0 +'">'); onclick="redClick('0')";</script> </td> </tr> </table> </body> The image that is displayed is not clickable, and therefore the function redClick cannot be called. Can someone please help me and tell me where I am going wrong here. I am kinda new to JavaScript. Thanks! Hey, im having another problem with my JavaScript. I wanted to call 2 functions inline, but I can't seem to do it. So I have added the function (add_event_listeners) to the function (load_doc) that is usually called. JavaScript debugger is saying: Code: Uncaught TypeError: Cannot read property 'addEventListener' of null JavaScript: PHP Code: //Get httpobject function getHTTPObject() { var http = false; if (window.XMLHttpRequest) { http = new XMLHttpRequest(); } else if (window.ActiveXObject) { http = new ActiveXObject("Microsoft.XMLHTTP"); } return http; } //This function attaches events to elements. var addEvent = function( elm, evt, fun ) { if ( elm.addEventListener ) { elm.addEventListener( evt, fun, false ); } else if ( elm.attachEvent ) { elm.attachEvent( 'on' + evt, fun ); } else { elm [ 'on' + evt ] = fun; } }; function load_doc(doc, parent) { add_event_listeners(); document.getElementById(parent).innerHTML = "Fetching data..."; var http = getHTTPObject(); if (http != undefined) { http.onreadystatechange = function() { req_doc(doc, parent, http); }; http.open("GET", doc, true); http.send(""); } } function req_doc(doc, parent, req) { if (req.readyState == 4) {//only if req is loaded if (req.status == 200) {//And if its okay document.getElementById(parent).innerHTML = req.responseText; } else { document.getElementById(parent).innerHTML = "Error fetching data: " + req.status + "\n" + req.statusText; } } } //Script used to hide elements. Usage: expand(element id) function expand(elm) { var ex = document.getElementById(elm).style.display; if (ex == "none") { var obj = document.getElementById(elm); obj.style.display = "inline"; } else if (ex == "inline") { var obj = document.getElementById(elm); obj.style.display = "none"; } } function add_event_listeners() { addEvent(document.getElementById('username'), "click", check_database); addEvent(document.getElementById('email'), "click", check_database); addEvent(document.getElementById('password_2'), "blur", check_password); } var check_database = function() { check_database_existing(this); }; var check_password = function() { compare_fields(this); }; function check_database_existing(obj) { } function compare_fields(obj) { var field2 = obj.id.split("_"); field2 = document.getElementById(field2[0]).value; if (obj.value == field2) { if (obj.value.length >= 4) { document.getElementById("pass_status").style.color = "#00CC00"; document.getElementById("pass_status").innerHTML = "OK!"; } else { document.getElementById("pass_status").innerHTML = "Please must be between 5 - 14 characters long! "; document.getElementById("pass_status").style.color = "#FF0000"; } } else { document.getElementById("pass_status").innerHTML = "Passwords do not match!"; document.getElementById("pass_status").style.color = "#FF0000"; } } HTML: Code: <div style="border-color:#090; border-width:1px; border-style:solid;"> <div class="login_button register_button" onClick="load_doc('pages/forms/login_form.php', 'login_form')">Back to login</div> <h1>Register</h1> <h3>DrawSomething - WordGuesser</h3> <br /> <form id="register" action="php/register.php" method="post"> Username<br /><h4 id="username_status">(waiting)</h4><br /><input type="text" name="username" id="username" class="text login_field"><br /> Email<br /><h4 id="email_status">(waiting)</h4><br /><input type="email" name="email" id="email" class="text login_field"><br /> --<br /> Password<br /><input type="password" name="password" id="password" class="text login_field"><br /> Retype<br /><h4 id="pass_status">(waiting)</h4><br /><input type="r_password" id="password2" name="password" class="text login_field"> <br /> <input type="submit" value="Register" class="button green" /> </form> </div> I have the following javascript function: [ function addNewWindowEvent(evType, fn) { if (window.addEventListener) { this.addEventListener("load", fn, false); return true; } else if (window.attachEvent) { var onload = "onload" this.attachEvent(onload, fn); return true; } else { return false; } } ] which is giving me a an exception every time a page on our site loads. The actual exception in firefox is this: uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: https://cms-dev.stchas.edu/global/js/hdvscripts.js :: addNewWindowEvent :: line 5" data: no] and I'm not sure exactly what it's complaining about. I'm relatively new to javascript so diagnosing and fixing this problem has me quite puzzled, and so far I have been unable to find anything helpful when I try and google for information on this. I would appreciate any help or suggestions. Thanks. henryv I am in the process of designing a simple game where the player flies a ship around using the arrow keys. I currently use a series of switch statements to execute certain actions dependant upon which key(s) is(are) pressed. Here is the code I use: Code: window.addEventListener('keydown', function (event) { switch (event.keyCode) { case arrowLeft: //left player.moveLeft = true; player.vr = -1; break; case arrowRight: //right player.moveRight = true; player.vr = 1; break; case arrowUp: //up player.moveUp = true; player.thrust = thrust; break; case arrowLeft && arrowUp: player.moveLeft = true; player.vr = -1; player.moveUp = true; player.thrust = thrust; break; case arrowRight && arrowUp: player.moveRight = true; player.vr = 1; player.moveUp = true; player.thrust = thrust; break; case arrowRight && arrowLeft && arrowUp: player.moveUp = true; player.thrust = thrust; break; } }, false); // Keyup input listeners window.addEventListener('keyup', function (event) { switch (event.keyCode) { case arrowLeft: //left player.vr = 0; player.moveLeft = false; break; case arrowRight: //right player.vr = 0; player.moveRight = false; break; case arrowUp: //up player.thrust = 0; player.moveUp = false; break; } }, false); The problem I am having is that the key presses don't always seem to register. For example, the player cannot always smoothly switch from a right turn quickly to a left turn. Sometimes he can, but oftentimes it seems like the key press is not always registered and the player must mash the key a second time to finally get it to register. Is there a more reliable method for listening for and registering key presses vs. using a switch statement or a bunch of if statements (which gave me the same result)? Hi I have some code but have no skills so need a lot of help here is what I have Code: <script type="text/javascript"><!-- alert(window.clipboardData.getData ('Text' )) {if (1,2,3,4) //repeats 4 times { //open 1.exe } else if (5,6,7,8) //repeats 4 times { // open 2.exe }else if (9,10,11,12) //repeats 4 times { // open 3.exe } else { // } //--></script> I need to get it to listn for sertan words and numbers and make a decision on what file to open the .exe files. It needs to recognise when the info has changed in the clipboard Please help <- thats me 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 have more than 30 addEvent listeners i need to add to my WebApp. But the Code to dynamically add them is not working, unless change: Code: AddItemEvtAry[x].addEventListener('click', function (e) {document.getElementById("text" + x).value ++}, false); to Code: AddItemEvtAry[x].addEventListener('click', function (e) {document.getElementById("text0").value ++}, false); but obviously hardcoding all of those DIV IDs would defeat the purpose of the code. Code in Question: Code: // Event Listeners for Incrimenting Quantities var AddItemEvtAry = [40]; for(var x = 0; x < 39; x++) { AddItemEvtAry[x] = document.getElementById("AddItem" + x); } for(var x = 0; x < 39; x++) { AddItemEvtAry[x].addEventListener('click', function (e) {document.getElementById("text0").value ++}, false); } Hi, I am very new to javascript, but have been a programmer in different languages for a while now. I am having trouble with this particular line: Code: <a href="<%# PageBase.UpdateQueryString(Request.RawUrl, PageBase.Tuple("tab","learn")) %>" data-ajaxurl="<%# PageBase.UpdateQueryString(Request.RawUrl, PageBase.Tuple("tab","learn"), PageBase.Tuple("targetId","ajax-search-list"), PageBase.Tuple("controlName","ListSearchResults")) %>">Video Suites</a> When this is a on a particular page on the site, it works perfectly, but copied to another page, the listener doesn't appear to create itself. I include exactly the same javascript files and there's no extra code in the page itself that would set listeners up. Could anyone please point me in a direction to check howto get the listener to attach. I think the listener is set from the data-ajaxurl attribute, but I could be wrong. THanks/ 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 |