Categories
JavaScript Answers

How to Add a Widget that we can Zoom In and Out on a Web Page When We Spin the Mouse Wheel Like on Google Maps with JavaScript?

Sometimes, we want to create a widget on a web page where we can zoom in and out on something as we can do on Google Maps with JavaScript.

In this article, we’ll look at how to create a widget that we can zoom in and out with the mouse wheel as we can do on Google Maps with JavaScript.

Draw the Image We can Zoom In and Out on the Canvas with JavaScript

We can draw the image we want to be able to zoom in and out on the canvas with JavaScript.

Then we can listen to the wheel event and transform the canvas image when we move the mouse wheel to let us zoom the image in and out.

For instance, we can write the following HTML:

<canvas id="canvas" width="600" height="200"></canvas>

Then we can write the following JavaScript code to draw the image on the canvas and zoom the image in and out as we move the mouse wheel:

const zoomIntensity = 0.2;

const canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
const width = 600;
const height = 200;

let scale = 1;
let originx = 0;
let originy = 0;
let visibleWidth = width;
let visibleHeight = height;

const draw = () => {
  context.fillStyle = "white";
  context.fillRect(originx, originy, width / scale, height / scale);
  context.fillStyle = "black";
  context.fillRect(50, 50, 100, 100);
  window.requestAnimationFrame(draw);
}
draw();

canvas.onwheel = (event) => {
  event.preventDefault();
  const mousex = event.clientX - canvas.offsetLeft;
  const mousey = event.clientY - canvas.offsetTop;
  const wheel = event.deltaY < 0 ? 1 : -1;
  const zoom = Math.exp(wheel * zoomIntensity);
  context.translate(originx, originy);
  originx -= mousex / (scale * zoom) - mousex / scale;
  originy -= mousey / (scale * zoom) - mousey / scale;
  context.scale(zoom, zoom);
  context.translate(-originx, -originy);
  scale *= zoom;
  visibleWidth = width / scale;
  visibleHeight = height / scale;
}

We have the draw function that clears the screen to white with the first and 2nd lines.

Then we call fillStyle and fillRect to draw a black square.

And then we call window.requestAnimationFrame to redraw the canvas.

Once we defined the draw function, we call it to start the initial draw.

Next, we set the canvas.onwheel property to a function that zoom the image in and out when we move the mouse wheel.

In the function, we first call event.preventDefault() to stop the default behavior when the mouse wheel moves.

Then we get the mouse offset with:

const mousex = event.clientX - canvas.offsetLeft;
const mousey = event.clientY - canvas.offsetTop;

Next, we write the following to normalize mouse movement to avoid unusual jumps:

const wheel = event.deltaY < 0 ? 1 : -1;

Then we get the zoom factor with:

const zoom = Math.exp(wheel * zoomIntensity);

And then we translate the visible origin so that it’s at the context’s origin with:

context.translate(originx, originy);

Then we compute the new origin after the zoom is done with:

originx -= mousex/(scale*zoom) - mousex/scale;
originy -= mousey/(scale*zoom) - mousey/scale;

Next, we call context.scale(zoom, zoom) to scale the image around the origin.

And then we translate the image to offset the visible origin so that it’s at the proper position after zoom:

context.translate(-originx, -originy);

And finally, we update the dimensions after zoom with:

scale *= zoom;
visibleWidth = width / scale;
visibleHeight = height / scale;

Now when we move the mouse wheel, the black square should zoom in and out.

Conclusion

We can add a widget with an image that we can zoom in and out by drawing an image on the canvas and translating and scaling the image when we move the mouse wheel.

Categories
JavaScript Answers

How to Clear the Focus of an Active Element with JavaScript?

Sometimes, we want to clear the focus of an active element with JavaScript.

In this article, we’ll look at how to clear the focus of an active element with JavaScript.

Get the Focused Element with the document.activeElement Property

We can get the element that’s in focus with the document.activeElement property.

Then we can call the blur method on it to remove focus from the focused element.

For instance, if we have an input element:

<input>

Then we can prevent users from focusing on it by writing:

document.addEventListener("focus", (e) => {  
  document.activeElement.blur()  
}, true);

We call addEventListener with 'focus' to listen to the focus event on document .

In the event listener, we call document.activeElement.blur to remove focus from the active element, which can be the input.

And we pass in true as the 3rd argument so that the focus event propagates from parent to child instead of the other way around.

This way, we can get the element that’s focused on and call blur on it to remove focus from it.

Conclusion

We can remove focus from an active element with the document.activeElement.blur method.

Categories
JavaScript Answers

How to Extract the Base URL from a String in JavaScript?

Sometimes, we want to extract the base URL from a string with JavaScript.

In this article, we’ll look at ways to extract the base URL from a string with JavaScript.

Create an Anchor Element and Get the Base URL Parts From the Created Element

We can create an anchor element and get the base URL parts from the created element.

For instance, we can write:

const a = document.createElement("a");
a.href = "http://www.example.com/article/2020/09/14/this-is-an-article/";
const baseUrl = `${a.protocol}//${a.hostname}`
console.log(baseUrl)

We create the a element with document.createElement .

Then we set the href of it to the URL we want to extract the base URL from.

Then we can get the baseURL by combining the protocol and hostname properties.

As a result, we see that baseURL is ‘http://www.example.com’ .

Create a URL Object and Get the Base URL Parts From the Created Element

Another way to get the base URL from a URL is to create an URL instance and extract the base URL parts from the object.

For instance, we can write:

const url = new URL("http://www.example.com/article/2020/09/14/this-is-an-article/")
const baseUrl = `${url.protocol}//${url.hostname}`
console.log(baseUrl)

We pass in the full URL as an argument of the URL constructor.

Then we can get the base URL by combining the protocol and hostname as we did before.

And so baseURL should be the same as the previous example.

Conclusion

We can extract the base URL from a string with JavaScript by creating an anchor element or using the URL constructor.

Categories
JavaScript Answers

How to Create a File Object in JavaScript?

Sometimes, we want to create a file object without our JavaScript code.

In this article, we’ll look at how to create a file object with JavaScript.

Create a File Object with the File Constructor

We can create a file with the File constructor with JavaScript.

For instance, we can write:

const parts = [
  new Blob(['you construct a file...'], {
    type: 'text/plain'
  }),
  ' Same way as you do with blob',
  new Uint16Array([33])
];

const file = new File(parts, 'sample.txt', {
  lastModified: new Date(2020, 1, 1),
  type: "text/plain"
});

const fr = new FileReader();

fr.onload = (evt) => {
  document.body.innerHTML = `
   <a href="${URL.createObjectURL(file)}" download="${file.name}">download</a>
    <p>file type: ${file.type}</p>
    <p>file last modified: ${new Date(file.lastModified)}</p>
  `
}

fr.readAsText(file);

We create the parts array with the parts of a file.

The first entry of parts is a Blob instance with the file content.

The first argument of Blob is the file content in an array.

The 2nd argument of Blob has the file metadata.

The 2nd and 3rd entries of parts has more file content.

Next, we use the File constructor to create a file object.

The first argument is the file content, which we stored in parts .

The 2nd argument is the file name.

The 3rd argument is some metadata.

Next, we create a FileReader instance so we can read the file contents.

We set the onload property of it to watch when the file loads into memory.

In the callback, we get the file metadata from the file .

And we use URL.createObjectURL with file to create a URL so we can download the file from a link we create by setting it as the value of href .

When we call readAsText with file , the onload method will run.

Now when we click on download, we see the sample.txt file download with the content that we put into parts in the text file.

Conclusion

We can create a file with the File constructor. And then we can read the file with the FileReader object.

Categories
JavaScript Answers

How to Check if a JavaScript Object Property is a Method?

In JavaScript, a method is a JavaScript object property that has a function as its value.

Sometimes, we want to check if an object property is a method.

In this article, we’ll look at how to check if a JavaScript object property is a method.

Use the typeof Operator

We can use the typeof operator to check if an object property is a method.

If an object property is a method, then the typeof operator should return 'function' .

For instance, we can write:

const obj = {
  prop1: 'no',
  prop2() {
    return false;
  }
}

console.log(typeof obj.prop2 === 'function');

to check if obj.prop2 is a method.

If it’s a method, then typeof obj.prop2 should return 'function' .

The console log logs true , so we know obj.prop2 is a method.

If it’s not a method or it doesn’t exist, then typeof obj.prop2 won’t return 'function' .

Conclusion

We can use the typeof operator to check if an object property is a method.