I'm trying to make a responsive website that has a grid of squares. So I need the height of each div (with a class of 'main') to be the same as the div width when it resizes. I'm quite new to jQuery so I was hoping somebody could tell me what I'm doing wrong here.
var divWidth = $('.main').width();
$(window).resize(function(){
$('.main').height() = divWidth;
});
Many thanks!
You should not declare the divWidth
outside the scope of the resize() function, because the value will not be updated when the resize event is fired. Also, there is a risk that there may be multiple .main
elements. Either use an ID, or loop through all classes (if there are multiple instances).
Try this:
$(window).resize(function(){
// If there are multiple elements with the same class, "main"
$('.main').each(function() {
$(this).height($(this).width());
});
// Or you can switch to using an ID
$('#main').height($('#main').width());
}).resize();
You fire the resize() event again to ensure that the size is set upon loading.
You can do:
var divWidth = $('.main').width();
$(window).resize(function(){
$('.main').height(divWidth);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With