2

I have code <a href="javascript:someFunction(this);" tabindex="0">Some text</a>

Is it possible to pass element into someFunction(link) {...} and use it later.

In debug mode I see the object but all properties are undefined.

When I was using onClick attribute like <a onClick="javascript:someFunction(this); it worked fine.

I am aware that this is probably not the best solution and I have seen the other questions, but it is really not my issue right now. I just need to do it this way for many reasons.

Thanks a lot

15
  • Have you tried that? Go ahead and try it and see if it works. It looks correct to me. Commented Feb 9, 2012 at 16:44
  • 1
    don't do inline javascript! no excuses, just don't do it. Commented Feb 9, 2012 at 16:44
  • 3
    onclick has a this parameter because it triggers an event. href does not. Commented Feb 9, 2012 at 16:44
  • @Blender:can I pass this with href? Commented Feb 9, 2012 at 16:45
  • @Mathletics: How can I achieve that action is happened on press Enter if <a> element has focus, and still this to be passed in javascript method? Commented Feb 9, 2012 at 16:48

2 Answers 2

2

If you don't mind using jQuery (disregard this answer if you don't), you can attach an event to your link:

$('#id_of_your_link').on('click', function(event) {
  event.preventDefault();
  someFunction(this);
});

This code works for both keyboard navigation and mouse clicking: http://jsbin.com/ufapor. You can see the source code here: http://jsbin.com/ufapor/edit#javascript,html

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

1 Comment

it seems that his is my answer, I was not aware that I can do it this way jsbin.com/ufapor/4/edit#javascript,html Very helpful.
2

Ok... I see what has happened here. The problem is that when you trigger an onclick event, there is an element involved. Thus you can pass this and reference it in the function. But when you use href, you are setting the current location to whatever is in that href. It's the same as if you typed it in the address bar and hit enter. Therefore, if you pass that function this, it's actually referring to the DOMWindow object. The only way around it that I can see, is to instead pass the node's id to the function as plain text. Then grab it with getElementById.

I would highly recommend reconsidering how you are doing this though.

1 Comment

Thanks I this I have found the solution.

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.