jQuery keypress in element?

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

jQuery keypress in element?

Post by alex.barylski »

Is it possible to determine which element an keypress event fired in using jQuery?

I've trapped the keypress/keydown, etc...and it appears the only property exposed to clients is the

Code: Select all

e.which == 32 // SPACE BAR PRESSSED
I was amazed to find that something like:

Code: Select all

e.element
Wasn't provided...that I could tell anyways???

Anyone have any experience or insight as to how I could add this functionality to jQuery or determine the element which triggered the event?

I have hacked on a solution for IE only...but that kind of defeats the purpose of using jQuery :P
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

This may come in handy, or make you want to jump out a window:
http://www.quirksmode.org/js/keys.html
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

I was really hoping to avoid using anything but jQuery to capture events, but I guess I have no choice...
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

Maybe something like this (never tried, but imagine it would work):

Code: Select all

$(document).ready(function(){
   $(document).click(function(event)){
      //event.target now is the element that was clicked
   });
});
Note: The entire line below is the link but phpBB is treating the () weird
http://docs.jquery.com/Events_(Guide)
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post by Kieran Huggins »

I just now understood what you were asking - sorry!

'this' should refer to the object that triggers the event (the context object)

Code: Select all

$(function(){
	$('#test').keyup(function(event){
		alert(this.id); // "test"
		alert(event.type); // "keyup"
	})
})
alex.barylski
DevNet Evangelist
Posts: 6267
Joined: Tue Dec 21, 2004 5:00 pm
Location: Winnipeg

Post by alex.barylski »

Thanks for the foodback guys...I'll try your suggestions shortly hopefully. :)
Post Reply