by Edward
08 March 2009 18:59
Adding JQuery Reference to ASP.NET pages
Quick How to...
Firstly create your website project, or select a page on your current website where you want to add JQuery functionality.
Get the latest jQuery javascript file from here.
Add the file to the root of your website, or a specified folder. Add a reference the the js file from the page you want to use it. You can also add the Script Reference to the JQuery file in ASP.NET’s AJAX Script Manager Control.
Instead of writing the script element directly, the script can be added to the set of scripts that the ScriptManager controls using a ScriptReference element. By including it this way, we are assured that it will be loaded at a point when the ASP.NET AJAX Library is available.
<asp:ScriptManager runat="server" ID="ScriptManager1">
<Scripts>
<asp:ScriptReference Path="jQuery.js" />
</Scripts>
</asp:ScriptManager>
You can now add jQuery functionality to your page. Make sure you add your logic to JQuery’s "ready event" as below:
$(document).ready(function(){
// Your code here
});
It makes sure that all the object(s) you reference are available and safe to manipulate the DOM.
If you want to manipulate all the links element <a>, take a look at the following snippet.
$("a").click(function(event){
alert("Hello World!");
});
Above code snippet will get all the <a> elements to be worked on and execute when you click the link(s) available on ASP.NET page which shows an alert box.
Next, we need to create a CSS Class. Add the CSS class in your page like this.
<style type="text/css">
a.mylink
{
font-weight: bold;
}
</style>
then add the CSS class as below:
$("a").addClass("mylink");
all your <a..> elements would now be bold. To remove the CSS class you’d use
$("a").removeClass("mylink");
Special Effects [Animation]
In JQuery, some basic effects are provided, to test how it works take a look at following snippet.
$("a").click(function(event){
event.preventDefault();
$(this).hide("slow");
});
Now, if you click any link, it should make itself slowly disappear.
For more help on JQuery, please visit the tutorials page on the JQuery Documentation website.