Categories
JavaScript Answers

How to Detect Page Zoom Levels in Modern Browsers?

Sometimes, we may want to detect page zoom levels in modern browsers.

In this article, we’ll look at how to detect zoom levels in modern browsers.

Using the window.devicePixelRatio Property

One way to detect the browser zoom level is to use the window.devicePixelRatio property.

For instance, we can write:

window.addEventListener('resize', () => {
  const browserZoomLevel = Math.round(window.devicePixelRatio * 100);
  console.log(browserZoomLevel)
})

When we zoom in or out, the resize event will be triggered.

So we can listen to it with addEventListener .

In the event handler callback, we get the window.devicePixelRatio which has the ratio between the current pixel size and the regular pixel size.

Divide outerWidth by innerWidth

Since outerWidth is measured in screen pixels and innerWidth is measured in CSS pixels, we can use that to use the ratio between them to determine the zoom level.

For instance, we can write:

window.addEventListener('resize', () => {
  const browserZoomLevel = (window.outerWidth - 8) / window.innerWidth;
  console.log(browserZoomLevel)
})

Then browserZoomLevel is proportional to how much we zoom in or out.

Conclusion

We can detect page zoom levels with the window.devicePixelRatio property or the ratio between the outerWidth and innerWidth .

Categories
JavaScript Answers

How to Convert a JavaScript Object Array to a Hash Map, Indexed by a Property Value of the Object?

Sometimes, we may want to convert a JavaScript objects array into a hash map object with the key of each entry being a property value of the object.

In this article, we’ll look at how to convert a JavaScript object array into a hash map object.

Array.prototype.reduce

The JavaScript array’s reduce method lets us convert an object array into an object easily.

For instance, we can write:

const arr = [{
    key: 'foo',
    val: 'bar'
  },
  {
    key: 'hello',
    val: 'world'
  }
];

const result = arr.reduce((map, obj) => {
  map[obj.key] = obj.val;
  return map;
}, {});

console.log(result)

to do the conversion.

We have an arr object array.

We call reduce to combine the objects in the array, which is obj into the object we return, which is map .

We get the obj.key and set the as a property name of map .

And we use obj.val as the value of obj.key .

The 2nd argument is an empty object, which is the initial value of the reduced result.

As a result, the value of result is:

{foo: "bar", hello: "world"}

Convert the Object Array to a Hash Map with the Map Constructor

We can convert the object array to a hash map with the Map constructor.

For instance, we can write:

const arr = [{
    key: 'foo',
    val: 'bar'
  },
  {
    key: 'hello',
    val: 'world'
  }
];

const result = new Map(arr.map(({
  key,
  val
}) => ([
  key,
  val
])));
console.log(result)

In the map method, we destructure the key and val properties from the parameter object in the callback.

Then we return an array with the key and val inside.

We then pass that to the Map constructor to create a hash map object from it.

And so, result is:

Map(2) {"foo" => "bar", "hello" => "world"}

according to the console log.

Lodash keyBy Method

We can also use the Lodash keyBy method to create the same object in the first example.

For instance, we can write:

const arr = [{
    key: 'foo',
    val: 'bar'
  },
  {
    key: 'hello',
    val: 'world'
  }
];

const result = _.keyBy(arr, o => o.key);
console.log(result)

We just pass in a callback to return the properties that the returned object will have.

The entries of arr will be set as the value of the keys according to the value of the key property.

And so we get:

{
  "foo": {
    "key": "foo",
    "val": "bar"
  },
  "hello": {
    "key": "hello",
    "val": "world"
  }
}

as the value of result .

Object.fromEntries

Another way to create a JavaScript object from an object array is to use the Object.fromEntries method.

For instance, we can write:

const arr = [{
    key: 'foo',
    val: 'bar'
  },
  {
    key: 'hello',
    val: 'world'
  }
];

const result = Object.fromEntries(
  arr.map(({
    key,
    val
  }) => ([
    key,
    val
  ]))
)
console.log(result)

We pass in an array of key-value pair arrays as we did when we try to create a Map instance from the array.

And so we get the same result as the first example for the value of result .

Conclusion

We can use array and object methods that are part of the JavaScript standard library of Lodash to create JavaScript object arrays to objects.

Categories
JavaScript Answers

How to Format Numbers by Prepending a 0 to Single-Digit Numbers in JavaScript?

Sometimes, we may want to format our numbers by pretending zeroes before it until it matches a given length.

In this article, we’ll look at how to format numbers by padding a number with leading zeroes until it meets a given length.

Number.prototype.toLocaleString

One way to pad a number with leading zeroes is to use the toLocaleString method.

It lets us pad a number with leading zeroes until it reaches a minimum length.

For instance, we can write:

const formattedNumber = (2).toLocaleString('en-US', {
  minimumIntegerDigits: 2,
  useGrouping: false
})
console.log(formattedNumber)

To pad the number 2 with leading zeroes until it’s 2 digits long.

minimumIntegerDigits is set to 2 so that the returned number string will be at least 2 characters long.

useGrouping set to false removes any digit grouping separator for the given locale.

Therefore, formattedNumber is '02' .

Write Our Own Function

We can also write our own function to pad a number string until it meets the given length.

For instance, we can write:

function leftPad(number, targetLength) {
  let output = number.toString();
  while (output.length < targetLength) {
    output = '0' + output;
  }
  return output;
}

const formattedNumber = leftPad(2, 2)
console.log(formattedNumber)

We create the leftPad function that takes the number to format and the targetLength to pad to as arguments.

We convert the number to a string with the toString method and assign it to output.

Then we use a while loop to prepend the output with zeroes until the targetLength is met.

Then we return the output string.

So when we call leftPad with 2 and 2, we get '02' .

String.prototype.padStart

Another way to pad a number string with zeroes until a given length is to use the string padStart method.

For instance, we can write:

const formattedNumber = (2).toString().padStart(2, "0");
console.log(formattedNumber)

We call toString on 2 to convert it to a string.

Then we call padStart on it with the length that we want to pad to and the character to pad the string with.

padStart prepends the string with the characters in the 2nd argument repeatedly until the length in the first argument is met.

Therefore, formattedNumber is the same as the other examples.

Conclusion

We can format numbers with leading zeroes until it meets a given length with JavaScript with a few simple methods or operations.

Categories
JavaScript Answers

How to Display JavaScript DateTime in 12 Hour AM/PM Format?

Sometimes, we may want to display a JavaScript date-time in 1 hour AM/PM format.

In this article, we’ll look at how to format a JavaScript date-time into 12 hour AM/PM format.

Create Our Own Function

One way to format a JavaScript date-time into 12 hour AM/PM format is to create our own function.

For instance, we can write:

const formatAMPM = (date) => {
  let hours = date.getHours();
  let minutes = date.getMinutes();
  let ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12;
  minutes = minutes.toString().padStart(2, '0');
  let strTime = hours + ':' + minutes + ' ' + ampm;
  return strTime;
}

console.log(formatAMPM(new Date(2021, 1, 1)));

We have the formatAMPM function that takes a JavaScript date object as a parameter.

In the function, we call getHours tio get the hours in 24 hour format.

minutes get the minutes.

Then we create the ampm variable and it to 'am' or 'pm' according to the value of hours .

And then we change the hours to 12 hour format by using the % operator to get the remainder when divided by 12.

Next, we convert minutes to a string with toString and call padStart to pad a string with 0 if it’s one digit.

Finally, we put it all together with strTime .

So when we log the date, we get:

12:00 am

Date.prototype.toLocaleString

To make formatting a date-time to AM/PM format easier, we can use the toLocaleString method.

For instance, we can write:

const str = new Date(2021, 1, 1).toLocaleString('en-US', {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
})
console.log(str);

We call toLocaleString on our date object with the locale and an object with some options.

The hour property is set to 'numeric' to display the hours in numeric format.

This is the same with minute .

hour12 displays the hours in 12-hour format.

So str is ‘1’2:00 AM’ as a result.

Date.prototype.toLocaleTimeString

We can replace toLocaleString with toLocaleTimeString and get the same result.

For instance, we can write:

const str = new Date(2021, 1, 1).toLocaleTimeString('en-US', {
  hour: 'numeric',
  minute: 'numeric',
  hour12: true
})
console.log(str);

And we get the same result.

moment.js

We can also use moment.js to format a date object into a 12-hour date-time format.

To do this, we call the format method.

For example, we can write:

const str = moment(new Date(2021, 1, 1)).format('hh:mm a')
console.log(str);

And we get the same result as before.

a adds the AM/PM.

hh is the formatting code for a 2 digit hour.

mm is the formatting code for a 2 digit minute.

Conclusion

We can format a JavaScript date-time to 12-hour format with vanilla JavaScript or moment.js.

Categories
JavaScript Answers

How to Create a style Tag with JavaScript?

Sometimes, we may want to create a style tag dynamically within our web page.

In this article, we’ll look at how to create a style tag dynamically with JavaScript.

Create a style Element with createElement Attach it to the head Tag with appendChild

We can create a style element with the docuemnt.createElement method as we do with any other kind of element.

Then we can attach the created element to the head tag by writing:

const style = document.createElement('style')
style.type = 'text/css';
style.textContent = 'h1 { color: green }';
document.head.appendChild(style)

We create the style element with document.createElement .

Then we set the type property of it to 'text/css' .

And then we set the textContent of the style element to the styles we want.

Finally, we call document.head.appendChild to append the style element to the head tag as a child.

We can now add the following HTML:

<h1>
  hello
</h1>

And we that the h1 text is green.

document.head.insertAdjacentHTML Method

We can also use the document.head.insertAdjacentHTML method to add our own HTML into the head tag.

This includes inserting a style element into the head tag.

To do this, we write:

document.head.insertAdjacentHTML("beforeend", `
  <style>
    h1 { color :green }
  </style>
`)

We pass in beforeend to insert the style element before the closinghead tag.

And so we get the same result as before.

Inserting a Stylesheet Dynamically

We can also insert a CSS stylesheet dynamically.

For instance, we can write:

const ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css";
document.head.appendChild(ss);

We create the link element with the document.createElement method.

Then we set the type to 'text/css' to make it reference a CSS stylesheet.

rel sets the rel attribute to stylesheet .

href sets the href attribute to the CSS file we want to reference.

Then we call document.head.appendChild to append the CSS.

And now we get the styles from the Bootstrap stylesheet applied in our app.

Conclusion

We can create a style element with JavaScript or add a link tag dynamically to reference to external CSS with JavaScript to add styles dynamically.