user1953826 user1953826 - 11 months ago 45
jQuery Question

How to determine if width size is 100% or 50%

I have button

that allow me to change div (
) width size.

I need to write in jquery, if the div width is 50%, when the button is clicked, change the div width to 100%. Or, if the div width is already 100%, change it to 50%.

How do I determine width using jquery? I'm a rookie on jquery. I just want to learn . Many thanks.

Answer Source

Assuming the requirement is:

if width is 50%, and when click button it change width to 100%.

if div width is 100%, then change to 50% on click button.

(and not just "write an if statement")

then you can use css classes and .toggleClass.

Create two css classes:

.halfwidth { width:50%; }
.fullwidth { width:100%; }

and give your div one of them:

<div id="box" class="halfwidth"></div>

then when you click the button, remove or add the halfwidth class and add or remove the fullwidth class. You can do this with .toggleClass()

$("#box").toggleClass("halfwidth fullwidth");

(space separated list of classes to toggle)

Run code snippet to see this in action

$(".inner").click(function() {
  $(this).toggleClass("halfwidth fullwidth");
.container { border:1px solid black; width 200px; height: 50px;}
.inner { border:1px solid red; background:pink; height: 50px; cursor:pointer;}
.halfwidth { width:50%; }
.fullwidth { width:100%; }
<script src=""></script>
<div class='container'>
  <div class='inner halfwidth'>