Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

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

4.24/5 (7 votes)
11 Sep 2007CPOL2 min read 1   1.5K  
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.

ASP.NET
<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.

VB
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.

JavaScript
<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.NET
<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.

VB
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)