Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery replace text of element on hover

With jQuery, I'm trying to replace the text, including the span, inside these links on hover. Then when the user hover's off, the original text is displayed again.

<a class="btn" href="#">
    <img src="#" alt=""/>
    <span>Replace me</span> please
</a>

<a class="btn" href="#">
    <img src="#" alt=""/>
    <span>Replace me</span> please
</a>

The final output should be

<a class="btn" href="#">
    <img src="#" alt=""/>
    I'm replaced!
</a>

I'm toying around with but not sure how to replace it back. Any ideas?

$('.btn').hover(function(){
    $(this).text("I'm replaced!");
});
like image 419
cusejuice Avatar asked May 22 '12 11:05

cusejuice


2 Answers

$('.btn').hover(
    function() {
        var $this = $(this); // caching $(this)
        $this.data('defaultText', $this.text());
        $this.text("I'm replaced!");
    },
    function() {
        var $this = $(this); // caching $(this)
        $this.text($this.data('defaultText'));
    }
);

you could save the original text in a data-defaultText attribute stored in the node itself so to avoid variables

like image 116
Fabrizio Calderan Avatar answered Oct 11 '22 18:10

Fabrizio Calderan


This should do the trick

$(function(){
  var prev;    

  $('.btn').hover(function(){
  prev = $(this).text();
      $(this).text("I'm replaced!");
  }, function(){
      $(this).text(prev)
  });
})
like image 5
Andrew Willis Avatar answered Oct 11 '22 19:10

Andrew Willis