Blog Archives

JQuery Animation Reference

Can be used without additional parameters
.animate()
Perform a custom animation of a set of CSS properties.

.clearQueue()
Remove from the queue all items that have not yet been run.

.delay()
Set a timer to delay execution of subsequent items in the queue.

.dequeue()
Execute the next function on the queue for the matched elements.

.fadeIn()
Display the matched elements by fading them to opaque.

.fadeOut()
Hide the matched elements by fading them to transparent.

.fadeTo()
Adjust the opacity of the matched elements.

.fadeToggle()
Display or hide the matched elements by animating their opacity.

jQuery.fx.interval
The rate (in milliseconds) at which animations fire.

jQuery.fx.off
Globally disable all animations.

.hide()
Hide the matched elements.

.queue()
Show the queue of functions to be executed on the matched elements.

.show()
Display the matched elements.

.slideDown()
Display the matched elements with a sliding motion.

.slideToggle()
Display or hide the matched elements with a sliding motion.

.slideUp()
Hide the matched elements with a sliding motion.

.stop()
Stop the currently-running animation on the matched elements.

.toggle()

Require additional parameters
Effects that can be used with Show/Hide/Toggle:

* Blind – Blinds the element away or shows it by blinding it in.
* Clip – Clips the element on or off, vertically or horizontally.
* Drop – Drops the element away or shows it by dropping it in.
* Explode – Explodes the element into multiple pieces.
* Fade – Fades the element, by gradually changing its opacity.
* Fold – Folds the element like a piece of paper.
* Puff – Scale and fade out animations create the puff effect.
* Slide – Slides the element out of the viewport.
* Scale – Shrink or grow an element by a percentage factor.

Effects that can be only used stand-alone:

* Bounce – Bounces the element vertically or horizontally n-times.
* Highlight – Highlights the background with a defined color.
* Pulsate – Pulsates the opacity of the element multiple times.
* Shake – Shakes the element vertically or horizontally n-times.
* Size – Resize an element to a specified width and height.
* Transfer – Transfers the outline of an element to another.

    $('#clickme').click(function() {
      $('#book').fadeIn('slow', function() {
        // Animation complete
      });
    });

Pulsate indefinitely:

           function pulsate() {
               $('#icon').fadeOut('slow', function () {
                   $('#icon').fadeIn('slow', function () {
                       pulsate();
                   });
               });
           }

Apply effect to multiple elements:

elements = $('div');

for (var i = 0; i < elements.length; i++) {                   
    elements.eq(i).delay(50 * i).effect("bounce",{times:1});
}​


Note:
Any snippets may have been condensed from their original sources for brevity. See references for original articles.

All server side code examples are in C# .Net.

References:
JQuery UI, http://docs.jquery.com/UI/Effects
Stack Overflow, http://stackoverflow.com/questions/3221442/jquery-animation-help

Get Current URL in Javascript

JS (JQuery):

$(document).ready(function() {
    $(location).attr('href');
});

JS (standard):

function CurrentURL() {
    var currenturl = window.location.pathname;
return currenturl;
}

JQuery Grid Themes

Useful links to JQuery grids utilizing (mostly) standard UI themes and/or very little code.

Google!
http://jquery-ui.googlecode.com/svn/branches/labs/grid/tests/static/grid/default.html

Datatables.Net:
http://www.datatables.net/styling/themes/smoothness

Ke-Cai:
http://www.ke-cai.net/2010/01/theme-your-table-with-jquery-ui.html

Trirand:
http://www.trirand.com/blog/jqgrid/jqgrid.html

Stackoverflow:
http://stackoverflow.com/questions/2613632/jquery-ui-themes-and-html-tables

JQuery and Partial Postbacks

I recently came across an issue where JQuery bindings no longer functioned after a partial postback and stumbled upon some code that was helpful in most cases.

Javascript (JQuery):

Sys.Application.add_load(startJQuery); 

startJQuery() { 
//do JQ here
}

And alternatively..

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(){});

This code will not always work however, as was the case in my particular scenario, so I resolved using an alternate method.

RegisterStartupScript is great functionality, and can be useful for loading javascript dynamically on an as-needed basis.

The example below, based on prior code selects the correct JS file to use, then loads it using the registerstartupscript function. This is all within a code block which calls an update panel

C#:


int scriptnumber = 1;
string FilePath = String.Format("~/Scripts/Script_{0}.js",scriptnumber.ToString());
System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(FilePath));
            jqueryfileoutput = sr.ReadToEnd();

            upnlBodyContent.Update();

            ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptname",
                "<script type=\"text/javascript\">" + jqueryfileoutput.ToString().Trim() + "</script>", false);

JQuery and Frames

Although there is definitely some room for debate in the web development and design community on where the usage of frames is necessary, there are some situations where they cannot be avoided.

Manipulation of data within these frames can be confusing, and dumping frames to page content using ajax or server side code is not always possible. This is especially true if these pages contain their own sub-site navigation.

In these scenarios, JQuery helps us simplify content management within frames using a combination of the “.contents()” method and “find” functionality to locate and update elements.

If “videoframe” is the id of the iframe, the example below changes the background color of a body inside the frame to a specific color.

JS (JQuery):


$('#videoframe').contents().find("body").css("background-color", "#FFFFFF");

References:
JQuery API, http://api.jquery.com/contents

JQuery AJAX Reference

Keep in mind when using code below if requesting a page that requires login/restricted access, users login session is not carried over.

Snippet below is sample code usage illustrating two different methods of achieving similar result. See references for more info and full specifications.

Javscript (JQuery):

$.ajax({
                            url: 'http://www.websitename.com/',
                            dataType: "text",
                            type: "POST",
                            data: { city: "NewYork"},
                            error: function(err) {
                                alert("Error:" + err.toString());
                            },
                            success: function(data) {
                                //$("#JQuery_modal_p").html(data);
                                alert(data);
                            }

                        });

Javscript (JQuery):

$.ajax({
                            url: 'http://www.websitename.com/' + data1+ data2,
                            dataType: "text",
                            type: "GET",
                            data: {},
                            error: function(err) {
                                alert("Error:" + err.toString());
                            },
                            success: function(data) {
                                //$("#JQuery_modal_p").html(data);
                                alert(data);
                            }

                        });

References:
JQuery Ajax, http://api.jquery.com/jQuery.ajax/

JQuery Is Not Defined

This is a common error for users implementing JQuery UI. Usually if you see this message, this could mean a few things:

– There is a syntax issue or bad link referencing the JQuery (min/full) JS. Use your debuggers to make sure the JS is loading.

– Similar to above this could also mean the JS cannot be loaded due to being contained in a folder which the site does not have permission to.

– If you are debugging locally and referencing the JQuery JS on an external site, make sure you have internet access and that the site which you are referencing to is up.

– The arrangement of script references may be in the wrong order. JS loads on runtime, so dependencies are important in placement of the script reference on the page. JQuery UI depends on JQuery(min), so (min) must be declared first or you will encounter the error.

As always, Firebug and other web development debuggers such as the one’s built into Chrome and IE are great tools to help you identify and resolve issues such as these.

Hope this may lighten someone’s day. 🙂

    <script src="../JQuery/js/jquery-1.4.4.min.js" type="text/javascript"></script>

    <link href="../JQuery/css/smoothness/jquery-ui-1.8.7.custom.css" rel="stylesheet"
        type="text/css" />

    <script src="../JQuery/js/jquery-ui-1.8.7.custom.min.js" type="text/javascript"></script>

References:
Firebug, http://getfirebug.com/
JQuery UI, http://jqueryui.com/

Using jQuery and ScriptManager to update dynamic page elements

I recently came across a situation where an element on the page was not updating dynamically after post backs.

It was quick and easy to add an update panel and the necessary logic to use the built in asp .Net ajax callbacks.

I simply added an update panel around the code that needed to be updated, and an invisible button within the update panel to trigger the postback. I then called this button using javascript click() event of the button.

However, this caused some conflicts with some other pre-existing ajax code and modal dialogs, so I turned to another solution.

Rather than re-work these controls and methods which were already functioning correctly and extensively implemented, I added a small snippet of code on page load for the content pages which I wanted to trigger a force reload. This did the trick.

VB:


ScriptManager.RegisterStartupScript(Me, Me.GetType(), "loadminicart", "$('#minicart').load('" & _
strRootSiteURL & "minicartdata.aspx');", False)

C#:


ScriptManager.RegisterStartupScript(this, this.GetType(), "loadminicart", "$('#minicart').load('" + strRootSiteURL + "minicartdata.aspx');", false);

“minicartdata.aspx” is a dynamic page with no masterpage, header, footer or body HTML tags specified – only div’s and content elements.

“minicart” is the id of the div which minicartdata.aspx will be loaded into.

In my specific instance, there were only two pages which I needed to force the minicart content to reload. As a requirement, I needed the reload to occur after an operation on these pages, so since there were only two pages, it was easy to specify this code in both.

In some cases, you may want to be able to easily trigger a refresh from code behind without having to place the above code in every page. For this I recommend simply creating a global function and placing the snippet above, then calling the global function from anywhere needed.

Another, more object oriented approach is to create your own type which inherits page, and use this as the base type for all your content pages. You could then place a function in your new type which contains the snippet above. This effectively has the same end result as using a global function.

Hope this information can be as useful to someone else as I found it to be. 😉