Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay changing innerHTML text using jQuery

So I've got a pretty simple button that basically toggles a form on and off - we'll be using this on our site since we're doing an update and would like feedback available on any page. Here's the jQuery I have so far:

<script>
// Toggle Button Text Change
$('#feedbackLink').hover(
    // Change HTML on mouseover
    function() {
        $(this).html('Send us a quick message!');
    },
    // Change back on mouseout
    function() {
        $(this).html('How can we improve this page?');
    }
);
// Toggle Button and Form
$('#feedbackLink').click(function() {
    // Hide feedback button
    $('#feedbackLink').toggle(500);
    // Display feedback form
    $('#feedbackForm').delay(501).toggle(250);
});
// Feedback Form
$('#cancel').click(function() {
    // Slides form from view when "CANCEL" is clicked
    $('#feedbackForm').toggle(500);
    // Fades original link back into view after a defined delay to allow for previous form to be hidden
    $('#feedbackLink').delay(501).toggle(75);
});
</script>

So my question is, how can I delay or fade in either the .hover call or the .html swap?

Thanks for the help.

P.S. - I know the code can be further optimized, I just like to get the functionality working first - then I go back and condense what I can.

like image 291
William Orazi Avatar asked Feb 25 '26 11:02

William Orazi


1 Answers

You can achieve this by using setTimeout():

var timeout;
$('#feedbackLink').hover(
    function() {
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            $("#feedbackLink").html('Send us a quick message!');
        }, 2000); // change the HTML after 2 seconds
    },
    function() {
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            $("#feedbackLink").html('How can we improve this page?');
        }, 2000); // change the HTML after 2 seconds
    }
);
like image 164
Rory McCrossan Avatar answered Feb 27 '26 00:02

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!