How to create a fading label in JQuery / ASP.NET after a button press

I think that this should be pretty easy but I’m not quite sure how to wire things up.

I have a page on which the user can define a query. When done, the user enters a name for the query and presses a button. I’d like to process the button click, make a text label (or Span) visible for a few seconds and then have it fade out.

Since it is a postback, I can turn an ASP:Label control to visible – that’s easy. Now how do I get jquery to make the label fade away after a few seconds? In a broader sense, how do you get a postback to trigger a jquery method?

Bonus for the simplest solution!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Start the asp label text as empty.

<asp:Label id="myLabel" runat="server"></asp:Label>

Then you can fade out the label every page load and set the text of the asp label after hitting the button.

Protected Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn.Click
  myLabel.Text = "You hit the button"
End Sub

    $(document).ready(function() {
        $('#myLabel').fadeOut(3000, function() {
            $(this).html(""); //reset the label after fadeout
        });
    });

Method 2

Here’s a low-tech technique that keeps all the script in your page template: add a $(document).ready() function to the page that executes conditionally based on a page-level variable, like this …

// In your button's click handler, set this.UserHasClicked to true
var userHasClicked = '<%= this.UserHasClicked %>' == 'True';
$(document).ready(function() {
    if(userHasClicked) {
        $(labelSelector).delay(2000).fadeOut(1000);
    }
});

Method 3

Call ClientScriptManager.RegisterClientScriptBlock

Method 4

Something like this…

var buttonFade = function() {
  $('#my .label .selector').fadeOut(2000);
}
setTimeout(buttonFade, 2000);

If you post some of your markup, I could also take a stab at putting the setTimeout() into a function triggered when the label appears.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x