views:

110

answers:

4

There's this image on a page I'm coding which should be resized and horizontally and vertically centered depending on some variables. I can't use the CSS sheet for this, as the width and height variables are dynamic. Therefore I want to have javascript add two extra arguments (top and left) to the style of this specific image.

I've tried this (which to me looked quite sensible)

function getStyleSheet() {
    for(var i=0; i<document.styleSheets.length; i++) {
        var sheet = document.styleSheets[i];
        if(sheet.title == 'StyleSheet') {
            return sheet;}
    }
}
var rule_sheet = getStyleSheet();
function changeText() {
    rule_sheet.insertRule(".className { top:" (-(.5*newHeight))+ "; left:" +(-(.5*newWidth))+ ";}");
    showRules();
}

I've also tried to add an inline style to the image like so: (in the function where the image was resized)

$(this).style.top= (-(.5*newHeight));
$(this).style.left= (-(.5*newWidth));

Neither solution worked, while to me both methods seemed plausible. What am I missing?

EDIT: I realized I didn't add the suffix 'px' to this, but after doing so, it still doesn't work :(

EDIT II: After NickFitz hints, I rewrote the last bit of code to this:

$(".className").each(function() {
    $(this).css("top", (-(.5*newHeight)), 2);
    $(this).css("left", (-(.5*newWidth)), 2);
});

This actually does change the way it looks. Not the way I want it, but at least I'ma tad closer to a solution.

+3  A: 

If you're using jQuery, you want the CSS-related methods. $(this) returns a jQuery object, and setting the style property of that isn't going to do anything.

NickFitz
Yes, thanks. I hadn't tried that yet. Still no solution though, I edited the first post to reflect this latest change.
Skunk
OH WAIT this does changes something. Thanks!
Skunk
+1  A: 

You should try something like (using val on the end of the variables)

$(this).css({top: topval + "px", left : leftval + "px", width : widthval + "px", height : heightval + "px"});

or you could use:

$(this).width(widthval);

kennyisaheadbanger
Yeah, I realized I forgot the px when I went back to try once more. No avail though, still broken :(I edited the first post with another method.
Skunk
looking at the first block of code you are trying to change all items which are with a class of "className". try using $(".className") instead of $(this)
kennyisaheadbanger
+1  A: 

Can you just get a wrapped set containing the <img> and then use the .css() command to set the appropriate values for it?

$('#img').css({ 'width' : calculatedWidth + 'px', 'height' : calculatedHeight + 'px' });
Russ Cam
Yes, this is what I needed :)
Skunk
+2  A: 

Try this:

$(this).css( 'top', (-(.5*newHeight))+'px' );
$(this).css( 'left', (-(.5*newWidth))+'px' );
warpech
Awesome thanks :)
Skunk