10

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!");
});
3
  • This would be much easier if all the content to be replaced was inside some element. Commented May 22, 2012 at 11:30
  • Do you need it to be done with jQuery or is it static text? Commented May 22, 2012 at 11:30
  • api.jquery.com/mouseover/#example-0 should show you Commented May 22, 2012 at 11:31

5 Answers 5

25
$('.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

Sign up to request clarification or add additional context in comments.

3 Comments

you posted this 43 seconds before me, but the funny thing is, my internet went down for a split second when I clicked send and I had to input a captcha when I sent it
Personally, this replace it, but then when the mouse goes out, it still keeps the new text!
Note that the key in the html node must be kebab-cased, in this example: <div class="btn" data-default-text="foobar">
5

This should do the trick

$(function(){
  var prev;    

  $('.btn').hover(function(){
  prev = $(this).text();
      $(this).text("I'm replaced!");
  }, function(){
      $(this).text(prev)
  });
})

Comments

1

add another function to the hover event like this:

$('.btn').hover(function(){
    $(this).text("I'm replaced!");
}, function() {
    $(this).text("Replace me please");
});

Link for demo

1 Comment

wow now i realize how slow i am... and a jsfiddle link was a bad idea here :'(
1
$('.btn').hover(function() {
    // store $(this).text() in a variable     
    $(this).text("I'm replaced!");
},
function() {
    // assign it back here
});

Comments

0

You'd need to store it in a variable in order to set it back to what it was, try:

var text;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.