Achieve text fading effects with JavaScript for a dynamic user experience in an ASP.Net C# application

In my WebForm ASP.Net application, I have implemented a feature where I change the text on the web page. To draw user attention to this change, I want to fade out the old text completely, replace it with new text, and then fade in the new text.

Currently, I have partially achieved this functionality using JavaScript. Here are the codes I am using for fading out and fading in text:

JavaScript

<script type="text/javascript">
    function toHex(d) {
        return ("0" + (Number(d).toString(16))).slice(-2).toUpperCase()
    }

    var direction = 1;
    var timer_is_on = 0;
    var rgb = 0;

    function timedCount() {
        var lab = document.getElementById('lblMessage');
        if (direction == 1) {
            rgb = rgb + 15;
        }
        if (direction == -1) {
            rgb = rgb - 15;
        }
        lab.style.color = "#" + toHex(rgb) + toHex(rgb) + toHex(rgb);;
        if (rgb >= 255 || rgb <= 0) {
            if (direction == 1) {
                direction = -1;
            }
            else {
                timer_is_on = 0;
                return;
            }
        }
        setTimeout(timedCount, 50);
    }

    function startEffect() {
        if (!timer_is_on) {
            timer_is_on = 1;
            direction = 1;
            rgb = 0;
            timedCount();
        }
    }
</script>

ASPX

<form id="frm" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="pnlMain" runat="server">
        <ContentTemplate>
            <div style="width: 400px; margin: 0 auto; text-align: center; font-size: x-large">
                <span id="lblMessage">No Record is Selected</span>
            </div>
            <button onclick="startEffect()">Start!</button>
        </ContentTemplate>
    </asp:UpdatePanel>
</form>

The Challenge

I still need to figure out two things:

  1. How to change the text after the fade-out animation completes
  2. How to accomplish all of this from code-behind in C# without relying on jQuery or any other JavaScript library.

Answer №1

There may be some CSS tricks to simplify and shorten this code, but I prefer to stick with your current approach to ensure compatibility across all browsers.

In order to update the message dynamically, you will need to pass the new message to your JavaScript function. I have also modified the JavaScript to allow for multiple elements on the page by passing the ID of the control.

<script type="text/javascript">
    function toHex(d) {
        return ("0" + (Number(d).toString(16))).slice(-2).toUpperCase()
    }

    var direction = 1;
    var timer_is_on = 0;
    var rgb = 0;

    function timedCount(controlId, newMsg) {
        var lab = document.getElementById(controlId);
        if (direction == 1) {
            rgb = rgb + 15;
        }
        if (direction == -1) {
            rgb = rgb - 15;
        }
        lab.style.color = "#" + toHex(rgb) + toHex(rgb) + toHex(rgb);
        if (rgb >= 255 || rgb <= 0) {
            if (direction == 1) {
                direction = -1;
                lab.innerText = newMsg;
            }
            else {
                timer_is_on = 0;
                return;
            }
        }
        setTimeout(timedCount.bind(null, controlId, newMsg), 50);
    }

    function startEffect(controlId, newMsg) {
        if (!timer_is_on) {
            timer_is_on = 1;
            direction = 1;
            rgb = 0;
            timedCount(controlId, newMsg);
        }
    }
</script>

To address post-back issues, a hidden field can be used as a workaround. This is crucial to prevent your text from being reset upon post-back.

<form id="frm" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="pnlMain" runat="server">
        <ContentTemplate>
            <asp:HiddenField ID="hfMessage" runat="server" />
            <div style="width: 400px; margin: 0 auto; text-align: center; font-size: x-large">
                <asp:Label ID="lblMessage" runat="server" Text="No Record is Selected"></asp:Label>
            </div>
            <asp:Button ID="btnFlash" runat="server" Text="Change Text" OnClick="btnFlash_Click" />
        </ContentTemplate>
    </asp:UpdatePanel>
</form>

Below is the corresponding code-behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        hfMessage.Value = lblMessage.Text;
    }

    if (Page.IsPostBack)
    {
        lblMessage.Text = hfMessage.Value;
    }
}

protected void btnFlash_Click(object sender, EventArgs e)
{
    string newMessage = DateTime.Now.Second.ToString() + " Records Selected";

    hfMessage.Value = newMessage;

    ScriptManager.RegisterStartupScript(this, GetType(), "flash", "startEffect('lblMessage', '" + newMessage + "');", true);
}

This was definitely an interesting challenge :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Scrollbar becomes inactive following the loading of AJAX content

Having an issue with loading a div using Ajax. The div loads, however the scrollbar within it stops working afterwards. In Main.html, I load content from other HTML files like so: <div id="content1" > </div> The content is loaded as follows: ...

Is there a way to dynamically apply the "active" class to a Vue component when it is clicked?

Here is the structure of my Vue component: Vue.component('list-category', { template: "#lc", props: ['data', 'category', 'search'], data() { return { open: false, categoryId: this.category ...

Enhance your React project by incorporating Material-UI card media elements with the ability to add

I am trying to figure out how to create an opaque colored overlay on top of an image using Material-UI. While it is possible with plain HTML, CSS, and JavaScript, I am facing some challenges with Material-UI. <Card> <CardMedia> <im ...

The image being displayed is significantly wider than the corresponding HTML element

I'm attempting to display this webpage in PNG format using npm's wkhtmltox: <!doctype html> <html> <head> <meta charset="utf-8"> <style> html, body { padding: 0; width: 340px; } ...

Choosing elements in jQuery

Having some trouble with the subnav on my current website project. I think the issue lies in how I am selecting items in my jquery code. It seems like a small fix that needs to be made, but I'm unsure of the correct approach. http://jsfiddle.net/ZDEr ...

The attribute "value" for Material-UI autocomplete cannot be used in conjunction with the "getOptionLabel" attribute

<Autocomplete id="license-select" options={licReqList} value = {licReqList[0] ? licReqList[0].licReqStr : null} getOptionLabel={(option) => option.licReqStr} onChange={ha ...

Using fetch, axios, or similar methods, if the error is not captured, the application crashes instead of being handled by the `catch` block

Before sending our request, it is crucial to ensure a stable internet connection. This is typically done using the following code: NetInfo.isConnected.fetch().then(async isConnected=> { if(isConnected){ try { let result = await fetch(MY_RE ...

VUE- the GetElementByClassName function is malfunctioning

I attempted to utilize 'getelementbyclassname' within VUE methods. My reason for doing so is that instead of applying information using :style, I would like to adjust the width of the div where I applied my class named 'classon'. I ...

Having trouble with the JQuery scrollTop animation? Getting the error message "Cannot read property 'top' of undefined"?

I am having trouble with my jquery animation scrollTop function. Whenever I click on <a>, it takes me to the anchor without any animation. Can someone please provide a solution for this issue? Upon running the webpage, I encountered an error message ...

When utilizing Selenium, the Chromium-based browser fails to navigate to a new URL

I have developed a basic WFA chromium-based browser. While connecting it with Selenium, the browser opens but fails to navigate to a new URL. The command window displays the following. How can I manipulate the chromium-based browser similar to using the ch ...

Tips for enabling autoplay for videos in Owl Carousel

I am facing an issue with implementing autoplay functionality for videos in an owl carousel. Despite trying different solutions found online, including this Owl Carousel VIDEO Autoplay doesn’t work, I haven't been able to make it work. Additionally, ...

Is it possible to employ a method to eliminate a specific valuable element 'this' from an array?

I am working on a task management app that allows users to create a To-Do list and remove specific items from the list. Currently, I am facing an issue with using 'localStorage' to save the list when the page is refreshed. The problem arises when ...

What could be causing this code to stop my app from shutting down properly?

Create a WinForms application using Visual Studio 2010 and .NET 4.0. Next, generate a user control by selecting Project/Add User Control... and implement the following code: public partial class UserControl1 : UserControl { private string _SelectedTab ...

Assign a new value to a controller scope variable without relying on angular.element in AngularJS

I have the following div: <div ng-controller="MyController as MC" id="div1"> <a href="#" id="1" ng-init="MC.EntityId = 1 , MC. ...

Make sure the div is positioned at the center of the screen with a set width, and ensure that

Is there a way to have three divs align next to each other, with the side divs filling up the remaining space equally? <div class="second_bar"> <div class="status_border_left"> </div><div class="nav_bar"> ...

Increase the value of $index within the ng-repeat loop

Is there a way to increment the value of $index in ng-repeat by a specific amount? For example, if I want to display two values at a time, how can I ensure that the next iteration starts with the third value instead of the second value? <div ng-contr ...

saving user settings

When my pages load, the initial action I take is querying a table named user preferences. I find myself doing this for each page, and I am curious about the possibilities to prevent repeating this query as the user navigates within my application. Thank y ...

What are some creative ways to design drop-down menus within an email?

The snippet of code I am currently using lacks the ability to format text, and it does not allow content below dropdown items to shift down properly in an email. <select> <option value="first">First-time users of the Vanguard Events app:&l ...

I haven't quite reached success yet, but I am working on getting my slideshow to display on my local server

My homepage is fully loading, but the slideshow feature is not functioning correctly. I have a file called slide.js in my /lib directory that I am trying to integrate into my homepage. The images are referenced properly and working, but they are not displa ...

Steps for repairing a button positioned at the top of a nested container within a form

My search form includes side filters to help users narrow down their search, with the results appearing on the right. This is just a basic example, as my actual setup involves more filters. However, there is one issue – users have to scroll down the pag ...