erichynds

Hi, I'm Eric Hynds, a front-end website developer living outside of Boston, Massachusetts. I'm passionate about developing functional, standard-compliant, and user-friendly websites.

Executing jQuery Methods Using Array Notation

I was refactoring some code this morning for a plugin I’m writing and ran into a case where I needed to dynamically execute a jQuery method. I had a variable that holds the value of a jQuery function I wanted to execute based on which key code was pressed; prev() for the up arrow, and next() for the down arrow. As it turns out you can do this with array notation.

These two examples accomplish the same thing:

// HTML:  <p><a href="">Click me</a></p>
 
// vanilla jQuery
$('p').find('a').click(function(e){
	alert('hello!');
	e.preventDefault();
});
 
// dynamically calling a method
var theMethod = 'find';
$('p')[theMethod]('a')['click'](function(e){
	alert('hello!');
	e.preventDefault();
});

Good to know.

  • http://www.bennadel.com/ Ben Nadel

    I wish ColdFusion could do that.

  • http://www.bennadel.com Ben Nadel

    I wish ColdFusion could do that.

  • http://lewayotte.com/2009/12/13/notable-tech-posts-2009-12-13/ Notable Tech Posts – 2009.12.13 | The Life of Lew Ayotte

    [...] Accessing jQuery methods using array syntax var addthis_pub = 'lewayotte'; var addthis_language = 'en';var addthis_options = 'email, favorites, digg, delicious, myspace, google, facebook, reddit, live, more'; [...]