JavaScript & ASP.NET: Executing on an Event onclick
Posted November 23, 2009 by Chris | Filed under ASP.NET, JavaScript
I've been doing a lot of front-end debugging with ASP.NET and JavaScript lately, and one thing has become very apparent: there's way too many ways to specify that something happens when you click on an link or other element.
First, you could specify what happens when an element is clicked using the classic but naive
<a href="#" onclick="doSomething(); return false;">A</a>
If the element is created by an ASP.NET control, there's the
<asp:Button OnClientClick="doSomething();" />
This simply generates:
<input ... onclick="test();" />
Again—bad idea. Adding on
You're best served by keeping behavior in the behavior layer—in JavaScript. If you're using a framework, forget about
<script type="text/javascript"> // MooTools example window.addEvent("domready", function() { $("element_name").addEvent("click", function() { alert("do something!"); }); }); // Or use $(element).click() with jQuery </script>
Or, JavaScript without a framework:
<script type="text/javascript">
document.getElementById("my_element_id").onclick = doSomething();
</script>Be consistent. Think of the people debugging your mess before you go around being inconsistent with how you wire up your events:
- If you're using a JavaScript framework, select your element then add an Event, and always place the <script> containing this at the end of your page. This will make it easy to find the click events for all your elements:
// jQuery <script type="text/javascript"> $(document).ready(function() { $("#element_name").click(function() { alert("do something!"); }); }); </script> - If you're not using a JavaScript framework, select your element then specify its
onclick , and always place the <script> at the end of your page. This will make it easy to find the click events for all your elements:<script type="text/javascript"> // Not using a framework? Better hope the DOM is ready! document.getElementById("my_element_id").onclick = doSomething(); </script>
- If you're looking to make enemies, specify the event by using an inline
onclick attribute in the tag. This will make it more difficult to find the click events for your elements:<a onclick="doSomething(); return false;">Clickity-click</a>
- If you're a real pain, use the codebehind to access the element and attach an
onclick via one of the dreadful options shown below. This will make it somewhat painful to find the click events for all your elements./* A) */ this.HyperLink1.Attributes["onclick"] = "doSomething();return false"; /* B) */ this.RegisterClientScriptBlock(...); /* C) */ this.RegisterStartupScript(...);
Tags: javascript onclick asp.net