Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - set div height equal to div width

Tags:

jquery

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!

like image 861
user2277377 Avatar asked Apr 13 '13 12:04

user2277377


2 Answers

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.

like image 196
Terry Avatar answered Sep 28 '22 07:09

Terry


You can do:

var divWidth = $('.main').width(); 

$(window).resize(function(){
    $('.main').height(divWidth);
});
like image 24
Eli Avatar answered Sep 28 '22 06:09

Eli