Reputation: 1262
i would like to know if there's a way to convert pixel to percent... I have a code which i get the value of full width successfully, but the only thing to keep the object in center, i must need to use percent.
Here's what i use on getting the value of width which i need to convert after to percent.
$(document).ready(function(){
var sp = $('.slide'),
winWidth = $('#slides').width();
console.log(winWidth);
sp.css('width', winWidth);
});
Thanks for the help.
Here's the updated fiddle link. *note: what i wanted here was to set the ".slide" container become fluid to make the object still in center spot. Feel free to modify my fiddle. Right now im using my given jQuery code to get the exact width of the "#slide" in percent to pixel ('.slide'). Then as of that, try to resize your browser to see the output of the slide frame. Im using SlidesJS plugin FYI.
Upvotes: 4
Views: 17245
Reputation: 10887
Use simple formula to calculate pixel to percent
for jquery users
var w=$("#container").width();
var h=$("#container").height();
for javascript users
var w=element.getBoundingClientRect().width;
var h=element.getBoundingClientRect().height;
x axis percentage
var xPercent=Math.round(x/w*100); //x is your pixal value
y axis percentage
var yPercent=Math.round(y/h*100); // y is your pixal value
for drag users ,use inside move function
function pixelToPercent(x,y)
{
var xPercent=Math.round(x/w*100); //x is your pixal value
var yPercent=Math.round(y/h*100); // y is your pixal value
return {
xPercent,
yPercent}
}
Upvotes: 0
Reputation: 7596
percent = ($("#your_element").width() / $("#some_parent_id").width()) * 100
Where $("#your_element")
is element you want to count width in %
, where $("#some_parent_id")
is element relative to which you want to count width.
Upvotes: 8
Reputation: 268
Try This:
$(document).ready(function(){
var sp = $('.slide'),
winWidth = $('#slides').width(),
wWidth = $(window).width();
sp.width(((winWidth / wWidth) * 100)+'%');
});
Upvotes: 1
Reputation: 1262
Ok, i figured out that "#slides" is not the correct element that i need to get the width value, since it was also part of the slides frame instead i get the value of event browser screen-size where i have to pass the value each time the browser screen was resizing.
Please check this link to see the updated fiddle. updated fiddle source
Here's the code that i found useful to correct my problem.
$(window).resize(function() {
var sp = $('#slides .slide');
console.log(document.body.clientWidth);
winWidth = document.body.clientWidth;
sp.css('width', winWidth);
});
At the case, i can fully resize my width and auto-adjust my class element width without having my center object stuck at the same place. :)
Upvotes: 0
Reputation: 191729
The percentage would be the actual value in pixels (acquired by .width
) divided by the value of the width in pixels of the block (possibly acquired via $("#slides").parent().width()
) multiplied by 100.
Upvotes: 3