Tuesday, 24 December 2013

Using JQuery Draggable on ASP Panel & DOM Objects

Technology: 

ASP.Net (.NET Framework 4.0)
jQuery UI - v1.10.3
jQuery - v1.8.0

The .draggable() Jquery function allows DOM objects to be moved around the screen. After some failed attempts at creating my own Javascript to do this within my ASP.Net project, I stumbled upon this simple function, to both my relief and frustration that I had wasted so much time!

Firstly I had to download the jQuery 1.8.0 and JQuery UI 1.10.3 libraries and add these to my ASP.Net project. I then added reference to them in the scripts section of my Master page.

For my scenario, I needed to drag a panel which existed on a child page. I created the panel as follows:

<asp:Panel ID="contentPanel" CssClass="draggable" runat="server" Style="z-index: 125; left: 300px; position: absolute; top: 200px;">

Note the 'draggable' class. I then needed to link this panel to the JQuery method from the J Query UI library so it could be draggable; I created a javascript file for my ASP page and added it as reference at the top of my ASP page:

    <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
    </asp:ScriptManagerProxy>
    <script src="../../Scripts/CustomPage.js" type="text/javascript"></script>

Within the CustomPage.js file, I added the following code:

function pageLoad() {
    $('.draggable').draggable();
}

Provided all is set up properly, the draggable() method will be applied to all objects that have a class of 'draggable.' JQuery takes care of the rest.

Note that originally I had used $(document).ready() instead of pageLoad() to contain my JQuery call. This caused problems as I had so many Ajax Update Panels and partial postbacks happening - PageLoad() fires when the page is loaded (like  $(document).ready()),
but also for partial postbacks via update panels. I had been seeing problems with $(document).ready() because when a partial postback occurred, my JQuery association got dropped and it would only be recreated next time a full page load occurred i.e. in $(document).ready().


No comments:

Post a Comment