...

View Full Version : addEventListener not passing function variable correctly



KevinJohnson
12-11-2010, 08:16 AM
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:



<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>

Philip M
12-11-2010, 08:53 AM
Key_Table[x] = document.getElementById(Key_Table[x]);
That seems meaningless to me. :)

I expect you know that addEventListener is not supported in IE.

KevinJohnson
12-11-2010, 09:02 AM
Key_Table[x] = document.getElementById(Key_Table[x]);
That seems meaningless to me. :)

I expect you know that addEventListener is not supported in IE.

i'm only supporting FireFox and Chrome.

:)

it's going to be used as an Offline DHTML app.


I'm actually writing a Text Editor, which has the look and feel of the Android 1.6 UI. This function is for the onscreen keyboard.

KevinJohnson
12-11-2010, 09:17 AM
i'm only supporting FireFox and Chrome.

:)

it's going to be used as an Offline DHTML app.


I'm actually writing a Text Editor, which has the look and feel of the Android 1.6 UI. This function is for the onscreen keyboard.



I'm trying to create all of my event listeners inside of a for-next loop. each ID has a very simple naming convention.

each key's ID is the name of that key

for example:

<id="a" class="mykeyclass">a</div>


that's the element and DIV for the lowercase 'a' key.

eventually i will also need to write a File-Picker Dialogue as well. So i will need a similar for-next loop for clicking on file names.

Dormilich
12-11-2010, 11:15 AM
then it's probably better to get the "keys" by their class name. and since you don't need to be backward compatible, you can use some of the advanced features as well.

function insertChar()
{
alert("Char is:" + this.id);
document.getElementById('TextData').value += this.id;
}
function loadListeners()
{
var key_table = document.getElementsByClassName("mykeyclass");
Array.prototype.forEach.call(key_table, function (item) {
item.addEventListener("click", insertChar, false);
});
}

PS. you are aware the IDs must not start with numbers?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum