1

I have a div with the text 'one' inside of it. When you hover over it, I want to change the text to 'two', and when you stop hovering over it, I want to change the text back to 'one'. I tried to do this using jQuery, but after it change into 'two', it doesn't change back to 'one' once you stop hovering over it. What am I doing wrong?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").hover(function(){
        $(this).replaceWith("two");
        }, function(){
        $(this).replaceWith("one");
    });
});
</script>

<p>one</p>
1

2 Answers 2

3

Use text(), since replaceWith() will replace the whole element, and you are replacing it with a text and not an element so the selection of the element is being lost the next time.

$(document).ready(function(){
    $("p").hover(function(){
        $(this).text("two");
        }, function(){
        $(this).text("one");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>


<p>one</p>

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

3 Comments

How come this doesn't work? $(this).text("two").fadeIn(3000);
because it is already visible ! maybe fadeOut() ? or try $(this).text("two").hide().fadeIn(777);
@Anonymous0day Ha! So, hide it, and then make it fadeIn! Smart!
0

$(document).ready(function(){
    $("p").hover(function(){
        $(this).html("two");
        }, function(){
        $(this).html("one");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>


<p>one</p>

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.