1

I am trying to apply an event to a element dynamically to my application.

When I used onclick I get an alert to pop:

el.setAttribute('onclick', 'alert("hi")',0);

When I try to use the onkeypress nothing happens:

el.setAttribute('onkeypress', 'alert("Hi");',0); 

I really need to have the onkeypress available. Is there something that I'm doing incorrectly? Is setAttribute not the best way to achieve what I'm doing? If so what are my alternatives to dynamically setting an event on a specific element?

UPDATE:

To answer a few of the questions below when I do:

el.setAttribute('onkeypress','numericOverride(this)',0);

When I look at the source in Firebug I see the following:

<div id="objSCR" class="txtbox" onmousedown="pfocus(this, '', '');" style="color:#0000FF; width:62px; height:12px; top:76px; left:120px; text-align:right; color:#0000FF;" ptmulti="false" pttype="E" ptlayndx="4" ptdisp="false" ppopup="" plength="12" onchange="numericOverride(this)">4000.00</div>

However, when I change the value of the text I get now output from this function:

function numericOverride(val){
        console.log('hello');
}

When I attempt to do the following:

el.onchange = function() { numericOverride(this) } 

Nothing gets added to the div and I get no result from the function.

7
  • 1
    EventListener isn't an option? It does look like this is what you need... Commented Aug 10, 2011 at 20:40
  • You want to set the DOM property, not the attribute. Attributes are set via HTML (as a default state). Commented Aug 10, 2011 at 21:21
  • @Matt - How do you set the DOM property? Commented Aug 10, 2011 at 21:24
  • Is there a reason you want to stick to setAttribute? If not, see my answer below which lets you attach the keypress event correctly for all major browsers. Commented Aug 10, 2011 at 21:34
  • @Mrcheif - I'm looking at ways to use your code. I think there might be an issue with my application and I just need to find where to apply your code. Thank you for yours and everyones efforts. Commented Aug 10, 2011 at 21:38

4 Answers 4

2

Try this (its cross browser):

function keyPressHandler() { alert("Hi"); };

if (el.addEventListener) {
   el.addEventListener("keypress", keyPressHandler, true);
}
else if (el.attachEvent) {
   el.attachEvent("onkeypress", keyPressHandler);
}
else {
   el.onkeypress = keyPressHandler;
}

Demo (note jsfiddle doesn't play well in IE 7): http://jsfiddle.net/mrchief/BQxWp/2/

Tested in Chrome, FF5, IE7 (after retrying couple of times) and IE9.

Sign up to request clarification or add additional context in comments.

Comments

2

What is the type of element that you are trying to attach the event handler to? The onkeypress event is only supported by the following tags:

<a>, <acronym>, <address>, <area>, <b>, <bdo>, <big>, <blockquote>, <body>, <button>,
<caption>, <cite>, <code>, <dd>, <del>, <dfn>, <div>, <dt>, <em>, <fieldset>, <form>,
<h1> to <h6>, <hr>, <i>, <input>, <kbd>, <label>, <legend>, <li>, <map>, <object>, <ol>,
<p>, <pre>, <q>, <samp>, <select>, <small>, <span>, <strong>, <sub>, <sup>, <table>,
<tbody>, <td>, <textarea>, <tfoot>, <th>, <thead>, <tr>, <tt>, <ul>, <var>

http://www.w3schools.com/jsref/event_onkeypress.asp

1 Comment

@Griffin - Although the list looks like pretty much every HTML tag I've ever used...
1

you should set the event listener in the proper manner:

el.onkeypress = function() { alert("HI") }

Comments

1

Have you considered using event listeners ?

target.addEventListener("click", function() { alert("Hi"); })

4 Comments

This doesn't work for Internet Explorer versions before version 9.
@griffin, for the sake of the community, I believe it best to provide the few lines of code to fill that gap, rather than leave your comment as is. As is, it seems like the Dom 0 way of doing things is better (since all those answers were up voted and this one is left with what seems like a bug) which it isn't. This answer provides the Dom 2 much more flexible solution.
@davin, the few lines of code to fill the gap are in the link the poster gives. Not sure what you are talking about for the rest of your comment though.
@griffin, If you read the page that I linked you to it shows you what code you have to add if you want to add compatibility with older version of browser. Here's the link directly: developer.mozilla.org/en/DOM/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.