Change text on hover, then return to the previous text

I would use a combination of jQuery .hover() and jQuery .data():

http://jsfiddle.net/5W4Bd/

HTML:

<div id="myDiv">default text</div>

javascript:

$('#myDiv')
    .data('textToggle', 5)
    .hover(function (e) {
        var that = $(this);

        // get the text from data attribute
        var textToSet = that.data('textToggle');

        // save the current text so it can be reverted
        that.data('textToggle', that.text());

        // set the new text
        that.text(textToSet);
    }, function (e) {
        var that = $(this);

        // get the text from data attribute
        var textToSet = that.data('textToggle');

        // save the current text so it can be reverted
        that.data('textToggle', that.text());

        // set the new text
        that.text(textToSet);
    });

edit: feel free to refactor the anonymous function used as the two callbacks to hover, since they are exactly the same :)


Yes, you can use CSS content. To switch between the normal text and "Reply!", put the normal text in a span and hide that when hovering.

button {
  width: 6em
}

button:hover span {
  display: none
}

button:hover:before {
  content: "Reply!"
}
<button><span>3 replies</span></button>

Edit: this works in IE8, but not in its compatibility mode, so I assume IE7 is out. Would that be a problem?


I think this would be a straightforward way to go for it. Use two span inside your button, one with content 'x replies', one with content 'Reply!'. Using CSS and :hover, you just switch which span is shown on hover.

button .comment {
  display: none;
}

button:hover .replies {
  display: none;
}

button:hover .comment {
  display: inline;
}
<button>
    <span class="replies">5 Replies</span>
    <span class="comment">Reply!</span>
</button>

This works just fine in about everything, as it uses very basic things to achieve an equally basic goal.


$('#button_id').hover(
    function(){
        $(this).text('Reply!');
    },
    function(){
        $.ajax({
            url: 'script.php',
            type: 'post',
            data: comment_id,
            success: function(num_replies){
                $('#button_id').text(num_replies + ' replies');
            }
        });
    }
);

I think you could use this kind of function, when you stop hovering, you feed the ajax call your comment id, and it returns the # of replies for that comment. You can decide how you want to store/retrieve your comment ID.