0

I'm using $.data() function to set the size of a div:

function init() {
    comp = $("#center");
    comp.data('image', {
        dimensions : {
            width : comp.width(),
            height : comp.height(),
            x0 : comp.position().left,
            y0 : comp.position().top,           
        }
    });
}

I'm retrieving the value like:

var image = comp.data('image');
alert(image.dimensions.x1);

The code is fine and it's working too. I would like to know if it is possible to do via $.attr() function and which way would be better.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Nikhil
  • 2,857
  • 9
  • 34
  • 58

3 Answers3

1

you can handle this easily like that:

var values = {width: '100px', height: '100px'};
$('#id-of-your-img').css(values);
Daniel Faria
  • 1,476
  • 5
  • 24
  • 45
0

You can try a attr("style", ""), but I would prefer to use css() for CSS manipulation. See here: http://api.jquery.com/css/

mvw
  • 5,075
  • 1
  • 28
  • 34
0

Here is a example where someone added a function to create a similar behaviour with some extra features.

FIDDLE

// dispatch to data() and attr()
$.fn.dataAttr = function(key, value) {
    var $this = this,
        ret = this.data(key, value);

    if (typeof key == "object") {
        $.each(key, function(key, value) {
            $this.attr("data-" + jQuery.uncamelCase(key), typeof value in {string:1, number:1} ? value : '~defined~');
        });
    } else if (value !== undefined) {
        $this.attr("data-" + jQuery.uncamelCase(key), typeof value in {string:1, number:1} ? value : '~defined~');
    }

    return ret;
};
Mx.
  • 3,588
  • 2
  • 25
  • 33