1

I need to get either the X position or the Y position of a mousedown event. So I tried passing a parameter to my getPosition function.

function getPosition(event, param) {
  // expected: var value = event.pageX;
  var value = event.param;
  return value;
}

$('#element').on('mousedown', function(e){
  var myValue = getPosition(e, 'pageX');
}

What am I missing here?

1 Answer 1

2

You need to use bracket notation instead:

function getPosition(event, param) {
  // expected: var value = event.pageX;
  var value = event[param];
  return value;
}

If you use dot notation, the browser will look for a property called param on the event object, which doesn't exist. Using bracket notation, the browser will evaluate param and look for that on the object.

Here is a fiddle which demonstrates the code above.

Sign up to request clarification or add additional context in comments.

2 Comments

This works! Performance-wise, are there any drawbacks to this approach as opposed to using two separate functions getPositionX and getPositionY ?
Performance-wise, bracket notation seems to be slightly slower. But you'd be doing well to even measure the difference between the two without calling it millions of times sequentially. jsperf.com/dot-vs-square-bracket/5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.