Martinloc Martinloc - 4 months ago 10
HTML Question

Set CSS 'top' property using Javascript depending on mouse position

I am trying to set the

top
CSS property through JavaScript.

If I use an absolute value like 100px it works just fine, but if I try to get the mouse position using
event.clientX
, it does not work.

Please note that I do not want to use jQuery or other libraries.

Code so far:

var el = document.getElementById('hide');

document.getElementById("foo").onmouseover = function() {
el.style.border = "5px solid red";
el.style.display = "block";
el.style.top = '100px'; // This works
el.style.top = event.clientX; // However this does not work
};


HTML:

<div id="foo">
<p>
Hover me
</p>
</div>

#hide {
display:none;
}


See also jsfiddle.

Answer

Make sure to add units to size declarations. Also, not sure if you intentionally used clientX and top, as the x-axis goes left-right and top property sets the up-down distance. The result (using top and clientX as you do) could look like this:

var el = document.getElementById('hide');

document.getElementById("foo").onmouseover = function() {
  el.style.border = "5px solid red";
  el.style.display = "block";
  var position = event.clientX + 'px';
  el.style.top = position;
};
Comments