Question

I want to be able to choose between .mouseover and .click events based on Modernizr's touch/no-touch output.

if (Modernizr.touch) {
  $(el).click(stuff);
  $(el).click(stuff);
} else {
  $(el).mouseover(stuff);
  $(el).mouseover(stuff);
}

But I don't want to write out all that stuff twice. Is it possible to define something so that I can just call:

if (Modernizr.touch) {correctEvent = click} else {correctEvent = mouseover}
$(el).correctEvent(stuff);
$(el).correctEvent(stuff);
Was it helpful?

Solution

Yes, this is easy with the alternative object access notation []:

var eventName = Modernizr.touch ? 'click' : 'mouseover';
$(el)[eventName](stuff);

The relevant fact here is that, since Javascript functions are first-class objects, they can be accessed in the same way as any other object property. For instance, you can do this:

var foo = { bar: 100 };
console.log(foo.bar);
console.log(foo['bar']);

The two lines are practically identical.

Since click and mouseover are properties of a jQuery selection, you can access them like this. For instance, you could (if you were so inclined) call the click method as $(el)['click'](). There would be no point, but you could do it.

Here, you can take advantage of this alternative syntax to handle the case where the function to call depends on other factors.

Edit: For more documentation on this, see the MDC page on "member operators".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top