CBalazic
CBalazic

Reputation: 21

Changing a div's contents on mouseOver

I have a couple of div's that have a paragraph of text inside as the contents. I want it so that when you hover over each div, it will change the contents from the one text to another. I know this can be accomplished with JavaScript (jquery?), but I have very limited experience with it, so some direction would be appreciated.

I have something like this:

div id="wrapper">
    <div id="div1">
    Here's the original text.
    </div>
</div>

I just want the "Here's the original text" in div1 to change to something else, like "Other text" when the mouse hovers over the wrapper, and to go back to the original text when the mouse leaves.

Upvotes: 1

Views: 67

Answers (2)

Shef
Shef

Reputation: 45589

// store element to avoid overhead on each event
var $div1 = $('#div1');

// keep the current text
$div1.data('old_text', $div1.text());

$('#wrapper')
    .on('mouseenter', function() {
        $div1.text('Another text');
    })
    .on('mouseleave', function() {
        $div1.text($div1.data('old_text'));
    });

Here is a demo.

Upvotes: 2

hennes
hennes

Reputation: 9342

Something like this should get the job done. Not tested for cross-browser compatibility though.

var defaultText = document.getElementById('div1').innerHTML;

document.getElementById('div1').onmouseenter = function() {
    this.innerHTML = "some other text";
};

document.getElementById('div1').onmouseleave = function() {
    this.innerHTML = defaultText;
};

Upvotes: 2

Related Questions