1

I have the following method I want to run on a onclick event:

function dostuff(evt) {
       var currentTarget = evt.currentTarget;
       // do more stuff
    }

On my link, I add the onclick event the following way:

 link.Attributes.Add("onclick", "dostuff()");

However, then the evt parameter is null in my above example. I want to parse the click event to the JavaScript function, so I can get the currentTarget, srcElement etc.

How do I add that on my onclick event?

3 Answers 3

2

Make your onclick attribute like this:

link.Attributes.Add("onclick", "dostuff.call(this, event)");

  • this in the function will be the bound element,

  • the event object will be passed along

  • it works both in standards browsers as well as IE8 and lower (including the event object being passed)

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

Comments

0

Parantheses are extra:

link.Attributes.Add("onclick", "dostuff");

You are assigning the return value of "dostuff" to the `"onclick" event instead of assigning the pointer to the function.

Also instead of using "evt" use "event" keyword as it should be. Use the "srcElement" property to access the element.

function dostuff() {

    var currentElement = event.srcElement;
}

Hope it helps.

Comments

0

Try this:

Code-behind:

HyperLink1.Attributes.Add("onclick", "return handleHyperLinkClick(this);");

Aspx:

<script type="text/javascript" language="javascript">

        function handleHyperLinkClick(hyperlink) {

            return confirm("Do you want to navigate to " + hyperlink.href + " ?");
        }
</script>

Hope this helps!

Comments

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.