Search code examples
jquerymouseeventmouseovermouseout

JQuery change text on mouse over and return to original on mouseout


I have this code, it works on mouseover but when mouse out off the a element it does not show the original text in p

$("a.brieflink").bind("mouseover", function() {
    $("div#brieftext").text($(this).data("text"));
});
$("a.brieflink").bind("mouseout", function() {
    $("brieftext").hide($(this).data("text"));
});

<a href="1.html" class="brieflink" data-src="article.jpg" data-text="text1">Brief 1</a>
<a href="2.html" class="brieflink" data-src="article.jpg" data-text="text2">Brief 2</a>
<a href="3.html" class="brieflink" data-src="article.jpg" data-text="text3">Brief 3</a>

<div id="brieftext"><p>Original text</p></div>

Can anyone help please?


Solution

  • The reason is that when you use $("div#brieftext").text($(this).data("text")) to set the text of brieftext,you have clear its original content,so if you want to show the original content again,you need to invoke html() to set it manually

    $("a.brieflink").bind("mouseover", function() {
        $("#brieftext").text($(this).data("text"));
    });
    $("a.brieflink").bind("mouseout", function() {
        $("#brieftext").html("<p>Original text</p>");//set the content manaully
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <a href="1.html" class="brieflink" data-src="article.jpg" data-text="text1">Brief 1</a>
    <a href="2.html" class="brieflink" data-src="article.jpg" data-text="text2">Brief 2</a>
    <a href="3.html" class="brieflink" data-src="article.jpg" data-text="text3">Brief 3</a>
    
    <div id="brieftext"><p>Original text</p></div>