next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
pos = el.style[direction].split('px')[0];
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
I'm using the simple code above to try and move an element. Now when I breakpoint on this, the value of el.style[direction]
is: " "
. So then when i try to do anything with it, it breaks. Why would this be? Isn't style.left
supposed to return an integer?
next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
pos = el.style[direction].split('px')[0];
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
I'm using the simple code above to try and move an element. Now when I breakpoint on this, the value of el.style[direction]
is: " "
. So then when i try to do anything with it, it breaks. Why would this be? Isn't style.left
supposed to return an integer?
- If you want to get such values easily, use jQuery. It has various methods to get the position of an element - as a number in pixels, no matter what units the CSS uses. – ThiefMaster Commented May 15, 2012 at 23:08
5 Answers
Reset to default 5Why would this be?
Presumably because it hasn't been set to anything.
Isn't style.left supposed to return an integer?
No. It is supposed to return a string containing the value of the CSS left property as set directly on the element (either by setting the JS property itself or by using a style attribute). It does not get a value from the cascade and it should only be an integer if the value is 0 (since all other lengths require units).
See How to get puted style of a HTMLElement if you want to get the puted value for the property rather than what I described in the previous paragraph.
style
provides the original style as calculated from the CSS, not the updated and possibly dynamic style. You probably want currentStyle
instead.
next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
var lft = document.defaultView.getComputedStyle(el)[direction];
pos = parseFloat(lft);
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
Note: like Elliot said you'll have to get the currentStyle/putedStyle. Here's a way to make it cross-browser, however when applying styles via JS, this is one good case where some sort of framework (eg Prototype [Scriptaculous], jQuery) would be useful.
Just a ment.
In your code:
> pos = el.style[direction].split('px')[0];
> pos = parseInt(pos, 10) + 10;
The split in the first line is superfluous, in the second line parseInt
will convert (say) 10px
to the number 10
just as effectively (and more efficiently) than what you have.
pos = parseInt(el.style[direction], 10);
This could be helpful.Add an onclick in the button.
function move() {
var 1 = document.getElementById("2");
var count = 1;
var id = setInterval(frame, 100);
function frame() {
width++;
1.style.left = width + '%';
}
}function stop(){
clearInterval(id);
}