Javascript – How to change the text of a div tag

htmljavascript

I have a simple div tag. Can you please tell me how can I change the text to 'mouse in' in my onmouseover handler? and 'mouse out' in my onmouseout handler?

<div id="div1" onmouseover="alert(1);" width="100px" height="200px" border="1">
test
</div>

and why the width/height and border attributes do not work? I want to set the border to be 1 pixel with width = 100 pixels and height = 200 pixels.

Thank you.

Best Answer

For your CSS, add the following:

/* Using inline-block so we can set w/h while letting elements
   flow around our div */
#div1 { display:inline-block; 
        width:100px; height:200px; 
        border:1px solid #000; }

For your Javascript:

/* We start wit a reference to the element via its ID */
var myDiv = document.getElementById("div1");
/* Then we add functions for our events */
myDiv.onmouseover = function() { this.innerHTML = 'mouse over'; }
myDiv.onmouseout  = function() { this.innerHTML = 'mouse out'; }

Which leaves us with very clean and minimalistic markup:

<div id="div1">Hover Me!</div>

Online Demonstration