erichynds

Me!

Welcome to my online development portfolio and blog. I'm Eric Hynds, a 23 year old website developer living outside of Boston, Massachusetts, and 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.

2 Responses to “Executing jQuery Methods Using Array Notation”

  1. Ben Nadel says:

    I wish ColdFusion could do that.

  2. [...] 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'; [...]

Leave a Comment