0
votes

I have the following code:

HTML:

<div id="my-div"></div>

CSS:

#my-div{
display: none;
position: absolute;
left: 150vh;
bottom: -150px;
}

jQuery:

$.fn.vhLeft = function(property,unit){
var wpx = this.css(property).replace(/[^0-9]+/g,"");
var temp = $('<div />').css({
    left:'1'+unit, 
    position: 'absolute'
});
$('body').append(temp);
var oneEm = temp.css(property).replace(/[^0-9]+/g,"");
temp.remove();
var value = wpx/oneEm;
return (Math.round(value*100))+unit;
};
// You could now get your value like
alert($('#my-div').parseInt(vhLeft)('left','vh'));

With credits to @Zword.

First off it seems theres something wrong with the function. With some values it works, with some values it doesnt return the right value.

Example with 150vh, working correct.

Example with 140vh, not working correct.

Basically what i need is to be able to add or subtract 12 to/off the current vh value for the left property of #my-div on click of an element.

1
..what? you are only reading the vh value in your example, do you need to set it? why are you generating a temp div? - Alex
and why is 150v => 2vh correct but 140vh => 2vh not? - Alex
@Alex I need to set it according to the current value, so therefor i need that to get working correct first. Also i dont really know how to go at setting it, thats why im asking here. So your right, thats not in there yet, but id like to know how to do so. - Jeroen
Looks to me like you're doing it wrong, this should work better -> jsfiddle.net/57e2m/27 - adeneo
Just add a setter, give me a second. - adeneo

1 Answers

4
votes

Change the plugin a little to use getComputedStyle, but note that you'll have to polyfill that for IE8 and below, but it will do a better job of returning the correct styles than jQuery seems to do here.

Also, to add a setter, just add another argument and a condition

$.fn.vhLeft = function(property , unit, adder){
    var el1 = this.get(0), el2 = document.createElement('div');

    $('body').append(el2);
    el2.style[property] = 1 + unit;

    var px1 = parseFloat(window.getComputedStyle(el1).getPropertyValue(property).replace(/[^0-9\,\.\-]/g, '')),
        px2 = parseFloat(window.getComputedStyle(el2).getPropertyValue(property).replace(/[^0-9\,\.\-]/g, '')),
        tot = Math.round( px1 / px2 );

    if (adder) {
        tot = tot + (adder);
        el1.style[property] = tot + unit;
    }

    $(el2).remove();

    return tot;
};

To just get the value you can do

var vh = $('#my-div').vhLeft('left','vh');

and to add / subtract to the value (this also returns the new value)

$('#my-div').vhLeft('left','vh', 12); // adds 12, returns 162

$('#my-div').vhLeft('left','vh', -12); // subtracts 12, returns 138

FIDDLE