Tuesday 11 August 2020

What is the difference between width and outerWidth in jQuery?

 Width in jQuery

The width() is the horizontal measurement of the container, for example, width of a div. It excludes the padding, border, or margin.

Example

You can try to run the following code to learn how to get the width of an element in jQuery:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Width of div element: " + $("div").width());
    });
});
</script>
</head>
<body>

<div style="height:200px;width:200px;padding:20px;margin:1px;border:1px solid red; background-color:blue;"></div><br>
<button>Get Width of div</button>

</body>
</html>

outerWidth in jQuery

The outerWidth() returns the outer width of the first matched element. It includes padding and border.

Example

You can try to run the following code to get the outer width in jQuery:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Outer Width of div element: " + $("div").outerWidth());
    });
});
</script>
</head>
<body>

<div style="height:200px;width:200px;padding:20px;margin:1px;border:1px solid red; background-color:blue;"></div><br>
<button>Get Outer Width of div</button>

</body>
</html>

No comments:

Post a Comment