You can set the width of a
<div>
box dynamically using the jQuery width()
method.
The
width()
method simply returns the element's width as unit-less pixel value. However calling the width(value)
method sets the width of the element, where the value can be either a string (e.g. 100%
, 50px
, 25em
, auto
etc.) or a number. If only a number is provided for the value, jQuery assumes it as a pixel unit.Copy Code Below
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Set a DIV width</title>
<style type="text/css">
.box{
float: left;
background: #f2f2f2;
border: 1px solid #ccc;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".set-width-btn").click(function(){
var newWidth = $(".input-width").val();
$(".box").width(newWidth);
});
});
</script>
</head>
<body>
<form>
<input type="text" class="input-width">
<button type="button" class="set-width-btn">Set Width</button>
<p>Enter the value in input box either as number (e.g. 100, 200) or combination of number and unit (e.g. 100%, 200px, 50em, auto) and click the "Set Width" button.</p>
</form>
<br>
<div class="box">This is simple DIV box</div>
</body>
</html>
No comments:
Post a Comment