Click here to Skip to main content
Click here to Skip to main content

Fade in/fade out a user confirmation message to the screen

, 11 Sep 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
Fade in/fade out a user confirmation message (or any other type) to the screen, all done through a server side user control.

Introduction

I often find myself writing some sort of user confirmation to the screen - a comment has been posted, a record was deleted, etc. The problem is, the confirmation often stays on the screen until the user clicks some other button or link on the site. To solve this, I created a user control that fades into view, stays on the screen for a configurable amount of time, and then fades away. That way, a user can be flashed a confirmation message, and the developer doesn't have to worry about it staying on the screen for too long.

Background

The basic idea behind the code is simple. Put a label on the page, then trigger JavaScript from the code-behind that displays the label for a set amount of time and then hides it.

Using the code

Register the user control on the page, then put the user control in an UpdatePanel. In this case, I'm clicking a button and accessing the user control in the click event of the button.

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <asp:UpdatePanel ID="up1" runat="server">
        <ContentTemplate>
            <asp:Button ID="btnShowMessage" runat="server" 
                   Text="Show Message" OnClick="btnShowMessage_Click" />
            <uc1:FlashMessage ID="FlashMessage1" runat="server" />
        </ContentTemplate>
    </asp:UpdatePanel>
</form>

In order to flash a message, all you have to do is set the message text and call the Display() method. There are other properties you can set, such as the speed of the fading and the amount of time the message stays on the screen, but they are optional.

Protected Sub btnShowMessage_Click(ByVal sender As Object, ByVal e As System.EventArgs)

    ''Optional properties
    'FlashMessage1.Interval = 4000
    'FlashMessage1.FadeInDuration = 300
    'FlashMessage1.FadeOutDuration = 2000
    'FlashMessage1.CssClass = "SomeClass"
    'FlashMessage1.FadeInSteps = 20
    'FlashMessage1.FadeOutSteps = 50

    'This is all that's needed to display a message

    FlashMessage1.Message = "Test message..."
    FlashMessage1.Display()

End Sub

The section above is all that is needed to use the control. Everything from this point on is code in the user control itself, and a brief explanation of how it works.

The User Control

To fade the message in and out, I used JavaScript from www.sunburnt.com and modified it slightly.

<script language="javascript" type="text/javascript">    
//The original javascript came from 
//http://www.sunburnt.com.au/publications/design/javascript-fade-effects
//I modified it to work with my code

//set the opacity of the element (between 0.0 and 1.0)       

function setOpacity(id, level) {
    var element = document.getElementById(id); 
    element.style.display = 'inline';
    element.style.zoom = 1;
    element.style.opacity = level;
    element.style.MozOpacity = level;
    element.style.KhtmlOpacity = level;
    element.style.filter = "alpha(opacity=" + (level * 100) + ");";
}

function fadeIn(id, steps, duration, interval, fadeOutSteps, fadeOutDuration){  
    var fadeInComplete;
    for (i = 0; i <= 1; i += (1 / steps)) {
      setTimeout("setOpacity('" + id + "', " + i + ")", i * duration); 
      fadeInComplete = i * duration;             
    }
    //set the timeout to start after the fade in time and the interval to display the 
    //message on the screen have both completed

    setTimeout("fadeOut('" + id + "', " + fadeOutSteps + 
               ", " + fadeOutDuration + ")", fadeInComplete + interval);
}

function fadeOut(id, steps, duration) {
    var fadeOutComplete;       
    for (i = 0; i <= 1; i += (1 / steps)) {
      setTimeout("setOpacity('" + id + "', "  + 
                (1 - i) + ")", i * duration);
      fadeOutComplete = i * duration;
    }      
    //completely hide the displayed message after the fade effect is complete
    setTimeout("hide('" + id + "')", fadeOutComplete);
}   

function hide(id){
    document.getElementById(id).style.display = 'none';
}
</script>

The only other item on the ASPX part of the user control is the label that the JavaScript shows and hides.

<asp:Label ID="lblMessage" runat="server" style="display:none" />

To display the message, all we need to do is call the FadeIn() method from the code-behind.

The tricky part was figuring out how to execute the JavaScript after an asynchronous postback. To do that, you have to get a reference to the script manager, then register the code with the UpdatePanel that the user control is nested in.

If the UpdatePanel is not in a user control, you can use the usual RegisterStartupScript method to register the script with the page and not the UpdatePanel.

Public Sub Display()

    'Set the duration, steps, etc. for the javascript fade in and fade out   

    Dim js As String = "fadeIn('" & lblMessage.ClientID & _
        "', " & FadeInSteps & _
        ", " & FadeInDuration & _
        ", " & Interval & _
        ", " & FadeOutSteps & _
        ", " & FadeOutDuration & ");"


    'Find the script manager on the page, and the update panel 
    'the FlashMessage control is nested in

    Dim sm As ScriptManager = ScriptManager.GetCurrent(Page)
    Dim up As UpdatePanel = GetParentOfType(lblMessage, GetType(UpdatePanel))


    If Not IsNothing(sm) And Not IsNothing(up) Then
        'The user control is nested in an update panel, 
        'register the javascript with the script manager and

        'attach it to the update panel in order to fire it after the async postback

        If sm.IsInAsyncPostBack = True Then
            ScriptManager.RegisterClientScriptBlock(up, GetType(UpdatePanel), _
                                                    "jscript1", js, True)
        End If
    Else
        'The user control is not in an update panel 
        '(or there is no script manager on the page), 

        'so register the javascript for a normal postback

        Page.ClientScript.RegisterStartupScript(Me.GetType(), "jscript1", js, True)
    End If

End Sub

The JavaScript then handles calling the fade out function once the elapsed display time has passed. This has come in very handy for me, I hope it helps you out too!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Neil Meredith
Software Developer (Senior)
United States United States
I am a .Net developer with 8 years of professional development experience. After 4 years in Florida, I made my way up to the frozen north and am currently living in Chicago.
 
For more development tips and tricks (focusing on game development with Unity), check out my blog at IPhoneTopApp.com.
 
Google Plus Profile
Follow on   Twitter

Comments and Discussions

 
QuestionC# version (again) PinmemberPlantigros28-Jul-14 2:27 
QuestionConsulting Pinmemberedusabrz7-Mar-09 15:34 
QuestionVersion in C# Pinmemberedusabrz7-Mar-09 13:09 
AnswerRe: Version in C# PinmemberNeil Meredith8-Mar-09 5:25 
GeneralRe: Version in C# Pinmemberedusabrz8-Mar-09 7:40 
GeneralThanks! Pinmembermobyspy24-Mar-08 23:30 
GeneralExcellent PinmemberASX_119-Oct-07 0:13 
GeneralThanks! Pinmembermpowrie23-Sep-07 0:59 
GeneralWell done Pinmembermonsaint19-Sep-07 7:06 
GeneralNice, but consider Scriptaculous as well Pinmemberjroughgarden18-Sep-07 7:05 
GeneralRe: Nice, but consider Scriptaculous as well PinmemberNeilCM19-Sep-07 8:02 
GeneralVery Nice Pinmembermerlin98113-Sep-07 7:12 
GeneralError Pinmembervcfgvcfg12-Sep-07 20:51 
GeneralRe: Error PinmemberNeilCM13-Sep-07 2:40 
GeneralRe: Error PinmemberOakman24-Mar-09 4:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150129.1 | Last Updated 11 Sep 2007
Article Copyright 2007 by Neil Meredith
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid