Reputation: 37
I have a container with n number of div inside it. I need the container to resize according to it children. I know this can be done using jquery library as follows.
JQuery
$(document).ready(function(){
setContainerWidth();
});
$(window).resize(function(){
setContainerWidth();
});
function setContainerWidth()
{
$('.container').css('width', 'auto'); //reset
var windowWidth = $(document).width();
var blockWidth = $('.block').outerWidth(true);
var maxBoxPerRow = Math.floor(windowWidth / blockWidth);
$('.container').width(maxBoxPerRow * blockWidth);
}
This time I need to do this with the pure javascript for some plugin issue. I broke down the code till as follows and stuck in the middle any help would be appreciated.
Javascript
function setContainerWidth(){
var container_width = document.getElementById('container').offsetWidth;
var width = document.body.clientWidth
var block_width = document.getElementsByClassName("block").offsetWidth;
container.style.width = "auto"
var maxBoxPerRow = Math.floor(width / block_width)
container.offsetWidth(maxBoxPerRow * block_width)
}
Upvotes: 1
Views: 2080
Reputation: 1407
You are missing a few things from your pure javascript translation:
function setContainerWidth()
{
var container = document.getElementById('container');
container.style.width = "auto";
var window_width = window.innerWidth;
var block_width = document.getElementsByClassName("block")[0].offsetWidth;
var maxBoxPerRow = Math.floor(window_width / block_width);
container.style.width = (maxBoxPerRow * block_width) + 'px';
}
Upvotes: 2