Click here to Skip to main content
11,641,971 members (59,623 online)
Click here to Skip to main content

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

, 11 Sep 2007 CPOL 65.9K 1.2K 54
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 over 10 years experience.

Check out my latest project, True Novelist

You may also be interested in...

Comments and Discussions

 
QuestionC# version (again) Pin
Plantigros28-Jul-14 1:27
memberPlantigros28-Jul-14 1:27 
QuestionConsulting Pin
edusabrz7-Mar-09 14:34
memberedusabrz7-Mar-09 14:34 
QuestionVersion in C# Pin
edusabrz7-Mar-09 12:09
memberedusabrz7-Mar-09 12:09 
AnswerRe: Version in C# Pin
Neil Meredith8-Mar-09 4:25
memberNeil Meredith8-Mar-09 4:25 
GeneralRe: Version in C# Pin
edusabrz8-Mar-09 6:40
memberedusabrz8-Mar-09 6:40 
GeneralThanks! Pin
mobyspy24-Mar-08 22:30
membermobyspy24-Mar-08 22:30 
GeneralExcellent Pin
ASX_118-Oct-07 23:13
memberASX_118-Oct-07 23:13 
GeneralThanks! Pin
mpowrie22-Sep-07 23:59
membermpowrie22-Sep-07 23:59 
GeneralWell done Pin
monsaint19-Sep-07 6:06
membermonsaint19-Sep-07 6:06 
GeneralNice, but consider Scriptaculous as well Pin
jroughgarden18-Sep-07 6:05
memberjroughgarden18-Sep-07 6:05 
GeneralRe: Nice, but consider Scriptaculous as well Pin
NeilCM19-Sep-07 7:02
memberNeilCM19-Sep-07 7:02 
GeneralVery Nice Pin
merlin98113-Sep-07 6:12
membermerlin98113-Sep-07 6:12 
GeneralError Pin
vcfgvcfg12-Sep-07 19:51
membervcfgvcfg12-Sep-07 19:51 
GeneralRe: Error Pin
NeilCM13-Sep-07 1:40
memberNeilCM13-Sep-07 1:40 
GeneralRe: Error Pin
Oakman24-Mar-09 3:03
memberOakman24-Mar-09 3: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
Web01 | 2.8.150731.1 | Last Updated 11 Sep 2007
Article Copyright 2007 by Neil Meredith
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid