< BACK TO COMPONENTS

Build a Responsive Screen Distance Measure with HTML, CSS, and JavaScript

Faraz

By Faraz -

Explore the world of web development by building your own Screen Distance Measure using HTML, CSS, and JavaScript. Follow our step-by-step guide for a responsive and user-friendly distance calculation tool.


Build a Responsive Screen Distance Measure with HTML, CSS, and JavaScript.jpg

Welcome to the exciting world of web development! In this tutorial, we will guide you through the process of creating a Screen Distance Measure using HTML, CSS, and JavaScript. Whether you're a beginner eager to learn the basics or an intermediate developer looking to enhance your skills, this step-by-step guide is designed to help you build a responsive and user-friendly distance calculation tool from scratch.


In today's digital age, where devices come in various shapes and sizes, understanding and implementing responsive design principles is crucial. Our tutorial not only focuses on the technical aspects of coding but also emphasizes the importance of creating a visually appealing and functional application.


By the end of this journey, you'll not only have a working Screen Distance Measure but also gain valuable insights into HTML, CSS, and JavaScript. Let's dive in and unlock the potential of web development together!

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our Screen Distance Measure.


After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.


Let's break down the code:


1. <!DOCTYPE html>: Declares the HTML version and document type.


2. <html lang="en">: Defines the HTML document and sets the language attribute to English.


3. <head>: Contains meta-information about the document, such as character set, viewport settings, and the title of the webpage.


  • <meta charset="UTF-8">: Specifies the character encoding as UTF-8.
  • <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />: Sets the viewport properties for responsive design.
  • <title>Screen distance Measure</title>: Sets the title of the webpage.
  • <link rel="stylesheet" href="./style.css">: Links an external stylesheet (style.css) to the HTML document for styling purposes.

4. <body>: Contains the content of the webpage.


  • <svg>: This is an empty SVG (Scalable Vector Graphics) element, indicating that some graphics or visual elements might be added dynamically using JavaScript.
  • <div class="output">: A container with the class "output" for displaying the measurement result.
  • <h2></h2>: An empty heading element that will be used to display the measurement result.
  • <span>Drag black handles to change distance.</span>: A span element with instructional text.
  • <div class="math">: Another container with the class "math" for displaying mathematical calculations.
  • Three <span> elements containing JavaScript code snippets for calculating the distance between two points using the Pythagorean theorem.

5. <script>: Includes JavaScript files for functionality.


  • <script src='https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js'></script>: Includes the GreenSock Animation Platform (GSAP) library, specifically the TweenMax module.
  • <script src="script.js"></script>: Links an external JavaScript file (script.js) to the HTML document for additional functionality.

This is the basic structure of our screen distance measure tool using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the screen distance measure tool is in place, the next step is to add styling to the tool using CSS.


Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our tool.


Let's break down the CSS code:


1. Body Styling:


  • The background of the body is set to white (#fff).
  • Two background patterns are created using linear gradients. One is a vertical gradient (#ebf4f9) with 1px width, and the other is a horizontal gradient with the same color and width.
  • Both patterns are repeated in an 8x8 grid and centered on the page.

2. Global Styling:


  • Applies a margin of 0 and sets the font family to sans-serif for all elements.

3. SVG Styling:


  • Makes all SVG elements take up 100% of the width and height of their container.
  • Fixes the position of SVG elements to the viewport.

4. Control Styling:


  • Styles elements with the class "control."
  • Set the fill color to black.
  • Changes the cursor to 'move' when hovering over elements with this class.

5. Segment Styling:


  • Styles elements with the class "segment."
  • Sets the stroke width to 2, stroke color to black, and the opacity to 0.3.

6. Output Styling:


  • Creates a fixed-width container with centered text positioned at the bottom of the page.
  • The container has a width of 400px, is horizontally centered using transform, and has a fixed position.

7. Math Styling:


  • Styles elements with the class "math."
  • Adds a margin of 20px and positions them absolutely on the page.
  • Child spans inside "math" have a monospace font, grey color, and reduced opacity.
  • The font size is set to 16px, but there are media queries to adjust it for smaller screens.

8. Media Queries:


  • Adjusts the font size of spans inside the "math" class for different screen widths:
  • For screens up to 700px wide, font size is increased to 24px.
  • For screens up to 400px wide, font size is further reduced to 12px.
  • For screens up to 300px wide, font size is even smaller at 9px.

This will give our tool an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body{
	background-color: #fff;
	background-size:  8px 8px, 8px 8px;
	background-position: center, center;
	background-image: linear-gradient(#ebf4f9 1px, transparent 1px),linear-gradient(90deg, #ebf4f9 1px, transparent 1px);
}
* {
  margin: 0;
  font-family: sans-serif;
}

svg {
  width: 100%;
  height: 100%;
  position: fixed;
}

.control {
  fill: black;
  cursor: move;
}

.segment {
  stroke-width: 2;
  stroke: black;
  opacity: 0.3;
}

.output {
  width: 400px;
  text-align: center;
  position: fixed;
  bottom: 60px;
  left: 50%;
  transform: translateX(-50%);
  user-select: none;
}

.math {
  margin: 20px;
  position: absolute;
}
.math span {
  font-family: monospace;
  display: block;
  color: grey;
  line-height: 24px;
  opacity: 0.5;
  font-size: 16px;
}

@media only screen and (max-width: 700px) {
  .math span {
  font-size: 24px;
}
}

@media only screen and (max-width: 400px) {
  .math span {
  font-size: 12px;
}
}

@media only screen and (max-width: 300px) {
  .math span {
  font-size: 9px;
}
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. Let's break down the code:


1. Variable Declarations:


  • svg: Represents the SVG element in the HTML document.
  • segment, controlA, controlB: Variables for SVG elements representing the line segment and two control points.
  • h2: Represents an HTML h2 element for displaying the distance information.
  • target: A variable to store the current target of a drag operation.

2. Draw Function:


  • The draw function updates the positions of the line segment and control points based on the current positions of controlA and controlB.
  • It also calculates and displays the distance between the control points using the Pythagorean theorem.

3. Initialization Function:


  • The init function sets up the initial state of the SVG, creating the line segment and control points.
  • Event listeners are added to the control points to initiate drag operations.

4. Event Listeners:


  • window.onresize triggers the draw function when the window is resized.
  • mousedown, mousemove, and mouseup event listeners handle the drag functionality.

5. Drag Functions:


  • startDrag: Initiates the drag operation by adding mousemove and mouseup event listeners.
  • stopDrag: Stops the drag operation by removing event listeners.
  • drag: Updates the position of the control point during a drag operation and triggers the draw function.

6. Utility Functions:


  • setAttributes: Sets attributes for an SVG element based on the provided object.
  • createElement: Creates an SVG element with specified attributes.

7. TweenMax Animation:


  • The code uses the TweenMax library to animate the movement of controlA and controlB points towards the center (0.5, 0.5) with a yoyo effect and a repeat. The onUpdate callback is used to call the draw function during the animation.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

var svg = document.querySelector("svg");
var segment;
var controlA;
var controlB;
var h2 = document.querySelector("h2");
var target;

function draw() {
	var x1 = Math.round(controlA.point.x * window.innerWidth);
	var y1 = Math.round(controlA.point.y * window.innerHeight);
	var x2 = Math.round(controlB.point.x * window.innerWidth);
	var y2 = Math.round(controlB.point.y * window.innerHeight);
	setAttributes(segment, {
		x1: x1,
		y1: y1,
		x2: x2,
		y2: y2
	});
	setAttributes(controlA, {
		cx: x1,
		cy: y1
	});
	setAttributes(controlB, {
		cx: x2,
		cy: y2
	});
	// calculate the distance between x
	var dx = x2 - x1;
	// calculate the distance between y
	var dy = y2 - y1;
	// use pythagoras theorem to find distance
	var distance = Math.sqrt((dx * dx) + (dy * dy));
	h2.innerHTML = "Distance: " + Math.round(distance) + " pixels";
}

function init() {
	segment = createElement("line", {
		class: "segment"
	});
	controlA = createElement("circle", {
		class: "control",
		r: 6
	})
	controlB = createElement("circle", {
		class: "control",
		r: 6
	});
	controlA.point = {
		x: 0.25,
		y: 0.25
	};
	controlB.point = {
		x: 0.75,
		y: 0.75
	};
	svg.appendChild(segment);
	svg.appendChild(controlA);
	svg.appendChild(controlB);
	controlA.addEventListener("mousedown", startDrag);
	controlB.addEventListener("mousedown", startDrag);
	draw();
}

init();
window.onresize = draw;

function startDrag(e) {
	target = e.target;
	window.addEventListener("mousemove", drag);
	window.addEventListener("mouseup", stopDrag);
}

function stopDrag(e) {
	window.removeEventListener("mousemove", drag);
	window.removeEventListener("mouseup", stopDrag);
}

function drag(e) {
	target.point.x = Math.min(Math.max(e.clientX / window.innerWidth, 0), 1);
	target.point.y = Math.min(Math.max(e.clientY / window.innerHeight, 0), 1);
	draw();
}

function setAttributes(element, attributes) {
	var keyword, key;
	for (keyword in attributes) {
		key = keyword.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
		element.setAttributeNS(keyword === "xlink:href" ? "http://www.w3.org/1999/xlink" : null, key, attributes[keyword]);
	}
}

function createElement(type, attributes) {
	var element = document.createElementNS("http://www.w3.org/2000/svg", type);
	setAttributes(element, attributes);
	return element;
}


TweenMax.to([controlA.point,controlB.point],1.5,{x:0.5,y:0.5,onUpdate:draw, yoyo:true,repeat:1,ease:Power2.easeInOut});

Final Output:

Build a Responsive Screen Distance Measure with HTML, CSS, and JavaScript.gif

Conclusion:

In conclusion, you've successfully ventured into the realm of web development by creating your Screen Distance Measure. Throughout this tutorial, we've covered essential steps, from setting up the HTML structure to adding responsive design elements, ensuring your distance calculation tool is not only functional but also visually appealing across various devices.


We hope this guide has provided you with valuable insights into HTML, CSS, and JavaScript. The skills you've acquired here can be applied to a myriad of other web development projects. Keep practicing, stay curious, and continue pushing the boundaries of what you can create.


For more in-depth learning, feel free to explore additional resources and tutorials. The world of web development is vast, and there's always more to discover. Thank you for joining us on this coding adventure, and best of luck with your future projects!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Related Post