1

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.

2 Answers 2

1

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;
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This worked and yes the clientX, rather than Y, was intentional!
0

You haven't passed the event to your function. Also, you're missing 'px'. Try this:

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

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

1 Comment

I really wonder how exactly the accepted answer worked, since it doesn't contain the event assignment to the function :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.