0

I've got an object generator. It works properly.

'use strict';
function Div(isim) {
    this.loc = document.getElementById(isim);
    var style = window.getComputedStyle(this.loc);
    this.width = style.getPropertyValue('width');
    this.height = style.getPropertyValue('height');
    this.left = style.getPropertyValue('left');
    this.top = style.getPropertyValue('top');
}

But later I am updating the properties of the element

var d = new Div("d");
d.loc.style.left = getRandomInt(0, window.innerWidth - 50) + "px";
d.loc.style.top = getRandomInt(0, window.innerHeight - 50) + "px";
console.log(d.left); //gives auto
console.log(d.width); //gives the right value

and console.log(d.left) is wrong. I have already found a way to fix it but it is a bit dirty, I think:

var d = new Div("d");
d.loc.style.left = getRandomInt(0, window.innerWidth - 50) + "px";
d.loc.style.top = getRandomInt(0, window.innerHeight - 50) + "px";
d = new Div("d");
console.log(d.left); //gives the right value
console.log(d.width); //gives the right value

Is there an another way(one line I prefer)? And Unfortunately, I am not good at English and if there are mistakes in question, title, please edit them.

DifferentPseudonym
  • 1,004
  • 1
  • 12
  • 28

2 Answers2

1

In your function change this.left to

this.left = function () {
    return window.getComputedStyle(this.loc).getPropertyValue('left');
}

then in your call change it to

console.log(d.left());
potatopeelings
  • 40,709
  • 7
  • 95
  • 119
1

The value is cached so you need to recompute.

function Div(isim) {
    this.loc = document.getElementById(isim);
    var style = window.getComputedStyle(this.loc);
    this.width = style.getPropertyValue('width');
    this.height = style.getPropertyValue('height');
    this.left = style.getPropertyValue('left');
    this.top = style.getPropertyValue('top');
    this.getStyle = function (prop) {
        return style.getPropertyValue(prop);
    }.bind(this);
}

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var d = new Div("d");
d.loc.style.left = getRandomInt(0, window.innerWidth - 50) + "px";
d.loc.style.top = getRandomInt(0, window.innerHeight - 50) + "px";
console.log(d.getStyle('left'));
console.log(d.getStyle('width'));

http://jsfiddle.net/s72vg53z/1/

Miguel Mota
  • 20,135
  • 5
  • 45
  • 64