David Johns
David Johns

Reputation: 1714

Unable to get Div width by jQuery

I have HTML Div with several sub Divs. When I'm trying to get the main Div's width, it is getting a wrong width different from the width that showing in the inspect element. What I exactly want is the visible width which is the width that showing when inspecting the element. I tried with outerWidth() and offsetWidth but didn't work. offsetWidth gave me "Undefined". How can I get this?

var x = $(".main").width();

$("button").on("click", function() {
	alert(x + " (Inspect element has width 571)");
});
.main{
  display: flex;
  overflow: hidden;
}

.sub{
  padding: 10px;
  margin: 10px;
  width: 50px;
  height: 50px;
  background-color: #faa;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
  <div class="sub">One</div>
  <div class="sub">Two</div>
  <div class="sub">Three</div>
  <div class="sub">Four</div>
</div>
<button>
GET MAIN DIV WIDTH
</button>

enter image description here

Upvotes: 0

Views: 1310

Answers (2)

MrMaavin
MrMaavin

Reputation: 1741

You have to watch out, when you get the width of the div. If it is before the page loads or before you resize the window, your solution won't work.

When i get the width in the click event i always get the right one. You could also just do it once after the page loaded with:

$(function() {
  // your code
});

in same as:

$('document').ready(function(){
  // your code
});

var x = 0;

//alternativ
$(function() {
  //this will only happen once and won't react to resize
  x = $(".main").width();
  console.log("div width: " + x);
});

$("button").on("click", function() {
  // resizing is no problem
  x = $(".main").width();
	alert("div width: " + x);
});
.main{
  display: flex;
  overflow: hidden;
}

.sub{
  padding: 10px;
  margin: 10px;
  width: 50px;
  height: 50px;
  background-color: #faa;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
  <div class="sub">One</div>
  <div class="sub">Two</div>
  <div class="sub">Three</div>
  <div class="sub">Four</div>
</div>
<button>
GET MAIN DIV WIDTH
</button>

Result:

enter image description here

Upvotes: 1

Lalji Tadhani
Lalji Tadhani

Reputation: 14149

use inline Flex

var x = $(".main").width();

$("button").on("click", function() {
	alert(x);
});
.main{
  display: inline-flex;
  overflow: hidden;
}

.sub{
  padding: 10px;
  margin: 10px;
  width: 50px;
  height: 50px;
  background-color: #faa;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main">
  <div class="sub">One</div>
  <div class="sub">Two</div>
  <div class="sub">Three</div>
  <div class="sub">Four</div>
</div>
<button>
GET MAIN DIV WIDTH
</button>

Upvotes: 1

Related Questions