views:

41

answers:

4

Hi,

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.

A: 

try this <div style="width:100px;height=200px;border=1px solid black" >your text</div>

to make your css work

Ayrton
This has nothing to do with the question about changing the text.
bmargulies
@bmargulies - he does also ask why the (unsupported) properties don't work.
tvanfosson
+1  A: 

DIVs don't have the width/height/border attributes. You should use styles instead. Even better use CSS classes to style your DIV.

<style type="text/css">
.message {
    width: 100px;
    height: 200px;
    border: solid 1px #000;
}
</style>

<div id="div1" class="message">test</div>

You might also want to consider using the jQuery hover method rather than mousein/out. While there are times that mousein/out are more appropriate, I've found that the behavior usually desired is a hover effect. This is easiest to handle in a browser-independent way with a JS framework, like jQuery.

 $('#div1').hover( function() {
       $(this).text('mouse in');
   },
   function() {
       $(this).text('mouse out');
   }
 });
tvanfosson
You should mention that this is jQuery and not standard javascript ;)
Tim Schmelter
@Tim - I did. You must have caught it between edits.
tvanfosson
A: 

Simply replace alert(1); with a Javascript function. You could do

this.innerHTML = 'mouse in'

and similarly for onmouseout.


As for your border problem, that is because you must you must do the following:

style="border:1px solid black"

as border is a CSS element.

waiwai933
+2  A: 

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

Jonathan Sampson