Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating HTML Text Change jQuery

I am attempting to change the text of a HTML element using javascript and jquery. This is my code so far, and I can't seem to get it to work. I have googled it and can't seem to find anything on it.

$("div#title").hover(
    function() {
        $(this).stop().animate({
            $("div#title").html("Hello")
        }, "fast");
    },
    function(){
        $(this).stop.animate({
            $("div#title").html("Good Bye")
        }, "fast");
    }
);

Any help would be greatly apreciated.

like image 357
GoodPie Avatar asked Nov 29 '22 12:11

GoodPie


2 Answers

$("div#title").hover(
    function () {
        $(this).stop().html("Hello").hide(0).fadeIn("fast");
    },
    function () {
        $(this).stop().html("Good Bye").hide(0).fadeIn("fast");
    }
);

jsFiddle example

like image 109
Shaddow Avatar answered Dec 15 '22 11:12

Shaddow


The way you are doing currently the syntax is incorrect, also you cannot animate a text as such instead you would need to animate an element holding the text. Also not clear on what peoprty you want to animate, Here couple of examples:

Animating Opacity:

$("div#title").hover(

function () {
    $(this).stop().css('opacity', '0').html(function (_, oldText) { // Set the opacity of the div to 0 and then change the html (flip it based on last value)
        return oldText == 'Good Bye' ? 'Hello' : 'Good Bye'
    }).animate({
        opacity: 1 // Animate opacity to 1 with a duration of 2 sec
    }, 2000);
});

Fiddle

Animating Width:

$("div#title").hover(

function () {
    $(this).stop().animate({
        'width': '0px'  // Animate the width to 0px from current width
    }, 2000, function () {  // On completion change the text
        $(this).html(function (_, oldText) {
            return oldText == 'Good Bye' ? 'Hello' : 'Good Bye'
        }).animate({          // and animate back to 300px width.
            'width': '300px'
        }, 2000);
    })
});

Fiddle

like image 21
PSL Avatar answered Dec 15 '22 09:12

PSL