Max Power
Max Power

Reputation: 153

Setting div height to equal width ( javascript )

I'm aware this is a popular question. I've read solutions to this including setting padding-bottom to equal width. As well as assigning this to the pseudo element so it's easier to insert content. (Plus other css solutions). css height same as width

These do work but it's giving me trouble with some of the content I insert and it's not worth the hassle (since my whole site is construction from these squares).

I'm a novice when it comes to javascript but would there be an easy solution to enable a divs height to equal width. ( Sorry I'm too novice to even show an attempt :/ )

I try not to ask too many "write code for me" questions so references or explanations would be equally appreciated.

Answer: Thanks Jacob just to add onto your code this now works on resize incase anyone else has this same problem https://jsfiddle.net/pekqh5z1/4/

function updateSize(){
var box = $(".test");
box.css("height", box.width());
}

$( window ).resize(updateSize);
$(document).ready(function(){
updateSize();
})

Upvotes: 2

Views: 3144

Answers (1)

Jacob G
Jacob G

Reputation: 14172

This is super easy to do.

To edit set the style of an element with JS, you set the desired property of the style method.

var test = document.querySelector(".test");
test.style.height = getComputedStyle(test).width;
.test {
  background: red;
}
<div class="test">Super uber goober</div>

With the JS, we first select the first appearance of .test, and assign it to a variable(var test = document.querySelector(".test");)

We then get the computed width of the element, and set that as its height(test.style.height = getComputedStyle(test).width;)

For the sake of completeness, here's a jQuery solution as well:

var test = $(".test");
test.css("height", test.width());
.test {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="test">Super uber goober</div>

Upvotes: 2

Related Questions