Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to set div.style.left and div.style.top css properties via JavaScript

I ran in a very confusing problem today

I have a canvas, and a div, like this

<canvas id="canvas" width="800" height="400"></canvas>
<div id="xy"></div>

I then set the properties of the div via a css file, e.g. position:absolute and display:none Then, i write the X/Y Position in the div via JS and try to set the properties of the div so that the div follows the mouse around, like this

var div = document.getElementById("xy");
var x = e.pageX - this.offsetLeft - 1;
var y = e.pageY - this.offsetTop - y0 - 0.5;
div.style.display = "block";
div.style.left = e.pageX + 25;
div.style.top = e.pageY -10;
div.style.backgroundColor = "#f00";

The funny thing now is: i can set the display and backgroundColor without a problem, but the left and top properties don't work. If i delete my DOCTYPE-declaration in my HTML file though, i can modify the left and top properties without any trouble. Working without doctype is out of the question of course. Am i doing something that shouldn't be done or missing something completely obvious?

like image 820
Ramon Wenger Avatar asked Apr 27 '12 13:04

Ramon Wenger


People also ask

Can JavaScript change CSS properties?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

Can we add styles using JavaScript?

We can use JavaScript to directly set a style on an element, and we can also use JavaScript to add or remove class values on elements which will alter which style rules get applied.

What is style left in JavaScript?

The Style left property is used for specifying the left position of the elements including padding, scrollbar, border, and margin.

What does Top and Left do in CSS?

Types of positioningThe top and bottom properties specify the vertical offset from its normal position; the left and right properties specify the horizontal offset. An absolutely positioned element is an element whose computed position value is absolute or fixed .


1 Answers

You have forgotten "px":

div.style.left = (e.pageX + 25) + 'px';
div.style.top = (e.pageY -10) + 'px';

You might also want to add div.style.position = "absolute";

If you think there's any chance that e.pageX or e.pageY will be strings rather than numbers, throw a parseInt in:

div.style.left = (parseInt(e.pageX, 10) + 25) + 'px';
div.style.top = (parseInt(e.pageY, 10) - 10) + 'px';
like image 121
ke20 Avatar answered Oct 26 '22 08:10

ke20