'Give a JavaScript function the event parameter

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?



Solution 1:[1]

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.

Solution 2:[2]

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!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rikki
Solution 2 palaѕн