javascripthtmlcsssvg

How to get CSS property value from HTML <object> using generalistic JavaScript function


EDITED:

I now have tried this:

var google, finalObject;

function getpositionx() {

    google = document.getElementById('google');
    finalObject = window.getComputedStyle(google);
    return parseFloat(finalObject.style.left);

};

getpositionx();

There isn't a syntax error now, but I get this:

Uncaught TypeError: Cannot read property 'left' of undefined

Why is this happening?

(The JSFiddle link below is updated with this new problem)


I'm trying to get and set the size and the position of an external SVG using JavaScript. I'll have to do this for up to 6 different objects, so I want one single function to get (or set) the value I need for whatever object I'm working on. I've made a sample code to show what I'm trying to do - you can check it out on JSFiddle (link below). Here I have the JavaScript, which is invalid because of the function that should get the values. How can I do this without having a different function for each object?

JavaScript:

var google;

function getelement() {

    google = document.getElementById('google');

};

function this.getpositionx() {

    return parseFloat(this.style.left);

};

I've also tried to do this:

function getpositionx(objectid) {

    return parseFloat(objectid.style.left);

};

JSFiddle here

Thank you for you attention


Solution

  • When you use window.getComputedStyle the method directly return the style attribute calculated of your object. you can access directly the css attribute in the rreturn object.

    So to solve your issue you should use :

    var google, finalObject;
    
    function getpositionx() {
    
        google = document.getElementById('google');
        finalObjectStyle = window.getComputedStyle(google);
        return parseFloat(finalObjectStyle.left);
    
    };
    
    getpositionx();