Categories
JavaScript Answers

How to Center a Browser Popup Window on the Screen with JavaScript?

Sometimes, we want to open a popup window in our JavaScript web app.

And we may want to center the popup on the screen.

In this article, we’ll look at how to center a browser popup window on the screen with JavaScript.

Center a Browser Popup Window on the Screen with JavaScript

To center a browser popup window on the screen, we’ve to do some calculations and pass the results into the options string that we pass into window.open .

To do this, we write:

const popupCenter = ({
  url,
  title,
  w,
  h
}) => {
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : window.screenX;
  const dualScreenTop = window.screenTop !== undefined ? window.screenTop : window.screenY;

  const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
  const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

  const systemZoom = width / window.screen.availWidth;
  const left = (width - w) / 2 / systemZoom + dualScreenLeft
  const top = (height - h) / 2 / systemZoom + dualScreenTop
  const newWindow = window.open(url, title,
    `
      scrollbars=yes,
      width=${w / systemZoom},
      height=${h / systemZoom},
      top=${top},
      left=${left}
      `
  )

  if (window.focus) {
    newWindow.focus();
  }
}

popupCenter({
  url: 'http://www.yahoo.com',
  title: 'yahoo',
  w: 900,
  h: 500
});

We create the dualScreenLeft and dualScreenTop variables to shift the center of to left corner of the popup in case the user has 2 screens instead of one.

dualScreenLeft is calculated by getting screenLeft or screenX .

dualScreenTop is calculated by getting screenTop or screenY .

Then we calculate the width of the popup with the clientWidth , innerWidth , or screen.width .

The height of the popup is set to the clientHeight , innerHeight or scree.height .

Then we get the zoom level of the screen with the systemZoom variable.

Next, we calculate the coordinates of the top left corner with the left and top variables.

We calculate the left value by setting the width adjusted for the zoom level.

Then we shift the screen with dualScreenLeft in case we’re showing the window on the 2nd screen.

And we do a similar calculation to calculate top .

Next, we call window.open with the systemZoom and the top and left values.

And we call focus on the newWindow if the focus method exists.

Now when we call the popupCenter method, we see the popup centered regardless of whether we have one or 2 screens.

Conclusion

We can center a browser popup screen by making some calculations to get the coordinates of the top left corner of the popup on the screen and its width and height.

Categories
JavaScript Answers

How to Select One or More Elements in the DOM Based on an Attribute Value?

Sometimes, we want to select one or more elements in the DOM that has the given attribute and value.

In this article, we’ll look at how to select one or more elements in the DOM based on an attribute value.

Select One or More Elements in the DOM Based on an Exact Attribute Value

To select one or more elements in the DOM based on an attribute value, we can pass a selector into querySelector to select one element with the given attribute value.

To select all the elements with the given attribute value, we can use the querySelectorAll method.

The general format of the selector is:

tagName[attribute="value"]

For instance, if we want to select one element with an image with the given src attribute value given the following HTML:

<img src='https://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg'>

We can write:

const img = document.querySelector("img[src='https://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg']");
console.log(img)

We call querySelector with the tag name img ,

And the src attribute value is https://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg .

This will select the first element with the given tag name and attribute value.

If we want to select all elements with the given tag name and attribute value, we can replace querySelector with querySelectorAll .

Select One or More Elements in the DOM Containing a Given Attribute Value

We can add a ~ before the = sign to get one or more elements containing a given attribute value.

For instance, with the same HTML, we can write:

const img = document.querySelector("img[src~='https://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg']");
console.log(img)

We get the img element with the src attribute containing https://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg .

And we can replace querySelector with querySelectorAll to get all the img elements with src attributes containing the given URL.

Conclusion

We can select elements with the given attribute value with some simple CSS selectors and the querySelector or querySelectorAll methods.

Categories
JavaScript Answers

How to Calculate the Age Given the Birth Date in YYYY-MM-DD Format with JavaScript?

We can use native date methods to calculate the age of a person given the birth date in YYYY-MM-DD format.

To do this, we write:

const calculateAge = (birthday) => {
  const ageDifMs = Date.now() - new Date(birthday).getTime();
  const ageDate = new Date(ageDifMs);
  return Math.abs(ageDate.getUTCFullYear() - 1970);
}

console.log(calculateAge('1960-01-21'))

We create the calculateAge method with the birthday parameter that takes a date string that we can convert to a date to calculate the age based on it.

In the function, we subtract Date.now , which has the timestamp of the current date-time in milliseconds.

And we create a new Date instance and call getTime to get the timestamp of the birthday we pass in milliseconds.

Then we assign the result to ageDifMs .

Then we pass in ageDifMs to the Date constructor to get the ageDate which is the date that’s created from January 1, 1970 midnight UTC plus the timespan specified by the timespan we pass in.

We call getUTCFullYear to get the year minus 1970 to get the age.

Then call Math.abs to make sure it’s positive regardless of whether birthday is before January 1, 1970 midnight UTC or not.

Therefore, the console log should log 61.

Using moment.js

To make calculate the date difference easier, we can use the moment.js library.

To do this, we write:

const calculateAge = (birthday) => {
  const startDate = new Date();
  const endDate = new Date(birthday);
  return Math.abs(moment.duration(endDate - startDate).years());
}

console.log(calculateAge('1960-01-21'))

In the calculateAge function, we take the birthday parameter like we have before.

But instead of using native date methods, we use the moment.duration method to calculate the duration.

We call it with endDate — startDate to get the moment duration object.

Then we call years to get the duration as the number of years.

And then we call Math.abs to make sure that the number returned is positive.

Then the console log should give us the same result as before.

Categories
JavaScript Answers

How to Check if the Type of a JavaScript Variable is Boolean?

Since JavaScript is a dynamically typed language, its variables can contain data of any type.

Therefore, we need a way to check for the data type of a variable.

In this article, we’ll look at ways to check if the data type of a JavaScript variable is a boolean.

The typeof Operator

One way to check if a variable is a boolean variable is using the typeof operator.

To do this, we write:

if (typeof variable === "boolean") {
  // ...
}

We check if the data of the variable variable is a boolean with the expression if the if statement.

It’ll return true if variable is a boolean.

The === Operator

Another way to check is a variable is a boolean is to check if it equals to true or false with the === operator.

For instance, we can write:

const isBoolean = (val) => {
  return val === false || val === true;
}
console.log(isBoolean(true))
console.log(isBoolean('abc'))

We create the isBoolean that checks whether val is false or true .

Since we use the === operator, either expression in the OR expression will return true only if val is exactly equal to the value being compared.

Therefore, the first console log should log true .

And the 2nd one should log false .

Check the String Representation of the Variable with toString

In addition to checking if the value is exactly equal to true or false , we can also compare the string value of it to see if it’s a boolean.

For instance, we can write:

const isBoolean = (val) => {
  return val === true || val === false || toString.call(val) === '[object Boolean]';
}
console.log(isBoolean(true))
console.log(isBoolean('abc'))

We call toString.call with our val parameter to see if it returns ‘[object Boolean]’ .

If it does, then it gives us more confidence that val is a boolean.

Using the valueOf Method

In case that we have boolean variables that are boxed with the Boolean constructor, we can also call the valueOf method to return the primitive version of the boolean variable.

For instance, we can write:

const isBoolean = (val) => {
  return typeof val === 'boolean' ||
    (
      typeof val === 'object' &&
      val !== null &&
      typeof val.valueOf() === 'boolean'
    );
}
console.log(isBoolean(true))
console.log(isBoolean('abc'))

to add:

(
  typeof val === 'object' &&
  val !== null &&
  typeof val.valueOf() === 'boolean'
)

to check if val is an object that isn’t null but the when we call valueOf it, we get 'boolean' returned.

This expression would be true if we invoke the Boolean constructor by writing expressions like:

new Boolean(true)

to create a boxed boolean object.

The console logs should be the same as the previous examples.

Conclusion

There’re many ways we can use to check if a JavaScript variable is a boolean variable.

Categories
JavaScript Answers

How to Hide or Show Elements with JavaScript?

In many situations, we may want to create components that we can show and hide by toggling them.

In this article, we’ll look at how to hide or show elements with JavaScript.

Hide or Show Elements with JavaScript

We can show or hide elements with JavaScript by setting the style.display property of an element.

We can hide it by setting it to 'none' .

And we can show it by setting it to 'block' .

For instance, we can write the following HTML:

<button>
  toggle
</button>
<p>
  hello world
</p>

Then we can add the following JavaScript code:

const button = document.querySelector('button')
const p = document.querySelector('p')

button.addEventListener('click', () => {
  if (p.style.display === 'none') {
    p.style.display = 'block'
  } else {
    p.style.display = 'none'
  }
})

We add a button and p element with the HTML.

Then we select the elements with document.querySelector .

And then we add a click event listener with the button.addEventListener method.

We check if p.style.display is 'none' .

If it’s 'none' , then we set p.style.display to 'block' .

Otherwise, we set it to 'none' .

'none' makes the element disappear. No space is allocated for the element.

And 'block' makes it display as a block element.

Now when we click on the button, we see the p element being toggled on and off.

Alternatively, we can set the visibility property instead.

The difference between visibility and display is that visibility allocates space for the element no matter if it’s displayed or not.

This isn’t the case with display .

So we can also write:

const button = document.querySelector('button')
const p = document.querySelector('p')

button.addEventListener('click', () => {
  if (p.style.visibility === 'hidden') {
    p.style.visibility = 'visible'
  } else {
    p.style.visibility = 'hidden'
  }
})

And we get the same result in our example.

Conclusion

We can set the display property to 'block' or visibility to 'visible' to show an element.

And we can set the display property to 'none' or visibility to 'hidden' to hide an element.