jQuery

jQuery Dimension Methods Example

Greetings readers, in this tutorial we will show how to use the jQuery library and the jQuery dimension methods to get the dimensions of an element’s box.

1. Introduction

jQuery is nothing but a JavaScript library that comes with rich functionalities. It is small and faster than many JavaScript code written by an average web developer. By using jQuery developers can write less code and do more things, making web developer’s tasks very easy. In simple word, jQuery is a collection of several useful methods, which can be used to carry out many common tasks in JavaScript. A couple of lines of jQuery code can do things which need too many JavaScript lines to do. The true power of jQuery comes from its CSS-like selector, which allows it to select any element from DOM and change, update or manipulate it. Developers can use jQuery to do cool animations like fade in or fade out. They can also change the CSS class of a component dynamically e.g. making a component active or inactive. I have used this technique to make tabbed UI in HTML. I can vouch for jQuery that once developers start using it, they will never go back to plain old JavaScript as jQuery is clear, concise, and powerful.

1.1 Why jQuery?

  • It helps in improving the application performance and increasing the developer’s productivity
  • It helps in developing the browser compatible web-page
  • It helps in implementing the UI related critical functionality without writing the several lines of codes
  • It is fast and extensible i.e. developers can use the jQuery library to implement the customized behavior
  • It is simpler and easy to learn

1.2 jQuery Dimension Methods

The jQuery library provides several dimension methods to get and set the CSS dimensions for the HTML elements. The following diagram illustrates the different jQuery dimension methods and how these methods are calculating the dimensions of an HTML element’s box.

jQuery Dimension Methods - jQuery Dimensions
Fig. 1: jQuery Dimensions

1.2.1 jQuery width() Method

The jQuery width() method is used to set or get the width of an HTML element. This width does not include the padding, border, and margin of an element. Over here represent the simple syntax to practice this method.

Snippet

$(selector).width(value);

Here, the value parameter is an optional argument that alters the width of the HTML element.

1.2.2 jQuery height() Method

The jQuery height() method is used to set or get the height of an HTML element. This height does not include the padding, border, and margin of an element. Over here represent the simple syntax to practice this method.

Snippet

$(selector).height(value);

Here, the value parameter is an optional argument that alters the height of the HTML element.

1.2.3 jQuery innerWidth() Method

The jQuery innerWidth() method is used to returns the width of an HTML element. This width includes the padding but not the border of an element. Over here represent the simple syntax to practice this method.

Snippet

$(selector).innerWidth();

1.2.4 jQuery innerHeight() Method

The jQuery innerHeight() method is used to returns the height of an HTML element. This height includes the padding but not the border of an element. Over here represent the simple syntax to practice this method.

Snippet

$(selector).innerHeight();

1.2.5 jQuery outerWidth() Method

The jQuery outerWidth() method is used to returns the width of an HTML element. This width includes the padding and the border of an element. Over here represent the simple syntax to practice this method.

Snippet

$(selector).outerWidth(boolean_value);

Here,

  • The boolean_value parameter is an optional argument i.e.
    • If the parameter value is set to true, the method returns the width of the HTML element, including padding, margin, and border
    • If the parameter value is blank, the method returns the width of the HTML element, including padding and border

1.2.6 jQuery outerHeight() Method

The jQuery outerHeight() method is used to returns the height of an HTML element. This height includes the padding and the border of an element. Over here represent the simple syntax to practice this method.

Snippet

$(selector).outerHeight(boolean_value);

Here,

  • The boolean_value parameter is an optional argument i.e.
    • If the parameter value is set to true, the method returns the height of the HTML element, including padding, margin, and border
    • If the parameter value is blank, the method returns the height of the HTML element, including padding and border

Always remember, these methods return the width and height value as the unit-less pixel value (i.e. 300).

These new APIs make a developer life easier, really! But it would be difficult for a beginner to understand this without an example. Therefore, let us create a simple application using the jQuery library.

2. jQuery Dimension Methods Example

Here is a systematic guide for implementing this tutorial using the jQuery library.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure if you are confused about where you should create the corresponding files or folder later!

jQuery Dimension Methods - Application Project Structure
Fig. 2: Application Project Structure

2.3 Project Creation

This section will show on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

jQuery Dimension Methods - Create a Maven Project
Fig. 3: Create a Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

jQuery Dimension Methods - Project Details
Fig. 4: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

jQuery Dimension Methods - Archetype Selection
Fig. 5: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

jQuery Dimension Methods - Archetype Parameters
Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.jquery</groupId>
	<artifactId>jQueryDimensionMethods</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

3. Application Building

Let us create an application to understand the basic building blocks of this tutorial.

3.1 Load the jQuery Library

Since it is a pure JavaScript framework, so developers should add its reference using the <script> tag.

<script type="text/javascript" src="resource/js/jquery-3.3.1.min.js"></script>

Developers can either download the jQuery from the official website and the application will then directly load the jQuery library from the local drive or they can also include the direct CDN link under the script tag.

3.2 Define the Application

Next, we will define the sample application using the HTML tags.

<!------ jQuery Dimension Methods Example ------>
<div id="mybox" class="mybox-panel">
	Lorem ipsum dolor sit amet, consectetur
	adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui.
	Mauris magna metus, dapibus nec turpis vel, semper malesuada ante.
	Vestibulum id metus ac nisl bibendum scelerisque non non purus.
	Suspendisse varius nibh non aliquet sagittis. In tincidunt orci sit
	amet elementum vestibulum. Vivamus fermentum in arcu in aliquam.
	Quisque aliquam porta odio in fringilla non purus nisld Dapibus nec
	turpis vel, semper malesuada ant.
</div>
<div> </div>
				
<div class="three-inline-btns">
	<div class="inner">
		<button id="btn1" type="submit" class="btn btn-default">Get Width and Height</button>
	</div>
	<div class="inner">
		<button id="btn2" type="submit" class="btn btn-default">Get InnerWidth and InnerHeight</button>
	</div>
	<div class="inner">
		<button id="btn3" type="submit" class="btn btn-default">Get OuterWidth and OuterHeight</button>
	</div>
</div>
<div> </div>

<h5 id="myresult"></h5>

3.3 Define a jQuery Function

In this step, we’ll demonstrate the jQuery dimension methods that will append the results to the myresult id on a button click. Add the following code to the jQuery function.

$(document).ready(function() {
	// Get Width and Height
	$("#btn1").click(function() {
		var width = $("#mybox").width();
		var height = $("#mybox").height();
		$("#myresult").html("Width= " + width + ", " + "Height= " + height);
	});

	// Get InnerWidth and InnerHeight
	$("#btn2").click(function() {
		var inner_width = $("#mybox").innerWidth();
		var inner_height = $("#mybox").innerHeight();
		$("#myresult").html("Inner Width= " + inner_width + ", " + "Inner Height= " + inner_height);
	});

	// Get OuterWidth and OuterHeight
	$("#btn3").click(function() {
		var outer_width = $("#mybox").outerWidth();
		var outer_height = $("#mybox").outerHeight();
		$("#myresult").html("Outer Width= " + outer_width + ", " + "Outer Height= " + outer_height);
	});
});

3.4 First jQuery Application

Complete all the above steps and save the file. Let us see the sample code snippet.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <title>IndexPage</title>
	    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
		
		<!-- Css files -->
	    <link rel="stylesheet" type="text/css" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.1.3/css/bootstrap.min.css">
	    <link rel="stylesheet" type="text/css" href="resource/css/mystyle.css">
		
		<!-- JavaScript files -->
	    <script type="text/javascript" src="resource/js/jquery-3.3.1.min.js"></script>
	    <script type="text/javascript" src="resource/js/mystyle.js"></script>	    	   
	</head>
	<body>
	    <div class="container">
	        <h2 align="center" class="text-primary">jQuery Dimension Methods Example</h2><hr />
	        <div> </div>
	
	        <!------ jQuery Dimension Methods Example ------>
			<div id="mybox" class="mybox-panel">
				Lorem ipsum dolor sit amet, consectetur
				adipiscing elit. Nam eu sem tempor, varius quam at, luctus dui.
				Mauris magna metus, dapibus nec turpis vel, semper malesuada ante.
				Vestibulum id metus ac nisl bibendum scelerisque non non purus.
				Suspendisse varius nibh non aliquet sagittis. In tincidunt orci sit
				amet elementum vestibulum. Vivamus fermentum in arcu in aliquam.
				Quisque aliquam porta odio in fringilla non purus nisld Dapibus nec
				turpis vel, semper malesuada ant.
			</div>
			<div> </div>
	        		        
	        <div class="three-inline-btns">
	            <div class="inner">
	                <button id="btn1" type="submit" class="btn btn-default">Get Width and Height</button>
	            </div>
	            <div class="inner">
	                <button id="btn2" type="submit" class="btn btn-default">Get InnerWidth and InnerHeight</button>
	            </div>
	            <div class="inner">
	                <button id="btn3" type="submit" class="btn btn-default">Get OuterWidth and OuterHeight</button>
	            </div>
	        </div>
	        <div> </div>
	        
	        <h5 id="myresult"></h5>
	    </div>
	</body>
</html>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

jQuery Dimension Methods - Deploy Application on Tomcat
Fig. 7: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL to display the application’s index page.

http://localhost:8082/jQueryDimensionMethods/

Server name (localhost) and port (8082) may vary as per your Tomcat configuration.

jQuery Dimension Methods - Index page
Fig. 8: Index page

Users can click buttons to display the result of the different jQuery dimension methods. That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

In this section, developers learned how to create a simple application with the jQuery library. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of jQuery Dimension Methods for the beginners.

Download
You can download the full source code of this example here: jQueryDimensionMethods

Yatin

The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button