Add/subtract Fixed Value To Elements Left Property Set In Vh With Jquery
I have the following code: HTML: CSS: #my-div{ display: none; position: absolute; left: 150vh; bottom: -150px; } jQuery: $.fn.vhLeft = functio
Solution 1:
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
Post a Comment for "Add/subtract Fixed Value To Elements Left Property Set In Vh With Jquery"