0

I would like to move to the left a div when pressing left keybord arrow.

function arrowright (event){
    var vaiss= document.getElementById("vaisseau");
    var size= vaiss.style.marginLeft;
    alert(size); //here I get empty message
    if (event.which==39)
        vaiss.style.marginLeft=size+"5px";
    alert (vaiss.style.marginLeft); // here I get 5px not previous left margin + 5px
}

Here CSS:

#vaisseau{
    bottom:0;
    position:absolute;
    margin-left:300px;
    display;block;
}

And HTML:

div id="vaisseau" class="elements"><img src="vaisseau.jpg"></div>

I think The problem is that it don't read the actual value of margin-left.

EDIT: the css style is in an external file

unfoudev
  • 87
  • 1
  • 7

1 Answers1

1

Found an answer here : How to get margin value of a div in plain JavaScript?

T.J. Crowder said :

The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).

To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).

Example:

var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);

display("Current marginTop: " + style.marginTop);

To summarize :

document.getElementById("vaisseau").style.marginLeft only works when the HTML code looks like this : <div id="vaisseau" class="elements" style="margin-left: 300px"></div>

Community
  • 1
  • 1
Pascal Goldbach
  • 977
  • 1
  • 15
  • 34