Categories
JavaScript Answers

How to Get an Element’s Top Position Relative to the Browser’s Viewport?

Sometimes, we may want to get an element’s top position relative to the browser’s viewport.

In this article, we’ll look at ways to get an element’s top position relative to the browser’s viewport.

Use the getBoundingClientRect Method

We can use the getBoundingClientRect method to get an element’s position relative to its viewport.

For instance, we can write:

const div = document.querySelector('div')  
const {  
  top: t,  
  left: l  
} = div.getBoundingClientRect();  
console.log(t, l)

We get the div with querySelector .

Then we call getBoundingClientRect on it to get an object with the top and left properties.

top has the position relative to the top of the viewport.

left has the position relative to the left side of the viewport.

Both are in pixels.

If we want to take scrolling into account, then we add the scrollY value to top and scrollX value to left .

For instance, we can write:

const div = document.querySelector('div')  
const {  
  top: t,  
  left: l  
} = div.getBoundingClientRect();  
const {  
  scrollX,  
  scrollY  
} = window  
const topPos = t + scrollX  
const leftPos = l + scrollY  
console.log(topPos, leftPos)

to include the scroll position with the element’s position.

Conclusion

We can get the element’s position relative to the viewport by using the getBoundingClientRect method.

Categories
JavaScript Answers

How to Show or Hide a div Using JavaScript?

Sometimes, we may want to show or hide a div in our web app.

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

Manipulate the style.display Property

To show or hide a div with JavaScript, we can manipulate the style.display property to change the CSS display property.

We show the div if we set it to 'block' , 'inline' , or 'inline-block' .

'block' makes it block level, 'inline' makes it inline. 'inline-block' is like block except that it doesn’t add a line break after the element.

And we hide it if we set it to 'none' .

For instance, we can write the following HTML:

<button id='show'>
  show
</button>
<button id='hide'>
  hide
</button>

<div>
  hello
</div>

Then we can write the following JavaScript code to toggle the display property of the div:

const showBtn = document.querySelector('#show')
const hideBtn = document.querySelector('#hide')
const div = document.querySelector('div')

showBtn.addEventListener('click', () => {
  div.style.display = 'block'
})
hideBtn.addEventListener('click', () => {
  div.style.display = 'none'
})

We get the show and hide buttons and the div with document.querySelector .

Then we call addEventListener with the 'click' argument to add click listeners to the buttons.

When we click on showBtn , we set div.style.display to 'block' .

And when we click on hideBtn , we set div.style.display to 'none' .

Manipulate the style.visibility Property

We can also change the value of the style.visibility property to show or hide a div.

The difference between display and visibility is that display adds or remove the div from the screen when we change its value.

visibility keeps the space of the element regardless of whether it’s shown or hidden.

For example, we can write:

const showBtn = document.querySelector('#show')
const hideBtn = document.querySelector('#hide')
const div = document.querySelector('div')

showBtn.addEventListener('click', () => {
  div.style.visibility = 'visible'
})
hideBtn.addEventListener('click', () => {
  div.style.visibility = 'hidden'
})

and keep the HTML the same as the previous example.

'visible' makes the div visible and 'hidden' makes it hidden.

Show or Hide a Collection of Elements

We can show or hide a collection of elements easily with JavaScript.

For instance, if we have the following HTML:

<button id='show'>
  show
</button>
<button id='hide'>
  hide
</button>

<div>
  hello
</div>
<div>
  world
</div>

Then we can loop through each div to show and hide them.

To do this, we write the following JavaScript:

const showBtn = document.querySelector('#show')
const hideBtn = document.querySelector('#hide')
const divs = document.querySelectorAll('div')

showBtn.addEventListener('click', () => {
  for (const div of divs) {
    div.style.display = 'block'
  }
})
hideBtn.addEventListener('click', () => {
  for (const div of divs) {
    div.style.display = 'none'
  }
})

We get the buttons the same way as the previous examples.

Then we get both divs with querySelectorAll .

In the click listeners, we loop through the divs and set the style.display property for each div.

We can do the same thing with the visibility property.

Conclusion

We can show or hide one or more divs with JavaScript easily.

Categories
JavaScript Answers

How to Compute the Sum and Average of the Elements in a JavaScript Array?

Sometimes, we want to compute the sum or average of the elements in a JavaScript array.

In this article, we’ll look at how to compute the sum and average of the elements in a JavaScript array.

Use a Loop

We can use the for-of loop to loop through an array to add all the numbers together to compute the sum.

Then to compute the average, we can divide the sum by the array’s length.

For instance, we can write:

const arr = [1, 2, 3]
let sum = 0;
for (const a of arr) {
  sum += a;
}

const avg = sum / arr.length;
console.log(sum)
console.log(avg)

We define an arr array with some numbers in it.

Then we define the sum variable and initialize it to 0.

Next, we add the for-of loop to loop through the arr entries.

a has the arr entry that’s being looped through.

In the loop body, we add the a value to the sum .

Then we create the avg variable and assign the quotient of the sum and arr.length to it.

Therefore, sum is 6 and avg is 2.

Use the Array.prototype.reduce Method

We can also use the array reduce instance method to compute the sum.

Then we can compute the average the same way as the previous example.

For instance, we can write:

const arr = [1, 2, 3]
const sum = arr.reduce((partialSum, a) => partialSum + a, 0)
const avg = sum / arr.length;
console.log(sum)
console.log(avg)

The reduce method takes a callback that has the partialSum and a .

Where partialSum is the partial sum returned after adding the arr entries that are iterated through.

a is the entry of arr being iterated through.

The callback returns the new partial sum.

The 2nd argument is the initial value of the sum .

The rest of the code is the same and we get the same result as the previous example.

Lodash sum and mean Methods

Lodash has the sum method that returns the sum of an array entries.

The mean method returns the average of the array entries.

For instance, we can write:

const arr = [1, 2, 3]
const sum = _.sum(arr)
const avg = _.mean(arr)
console.log(sum)
console.log(avg)

Both methods take the array we want to do the computation with as the argument.

Then we get the same result as before.

Conclusion

We can use Lodash or plain JavaScript to compute the sum and average of array entries.

Categories
JavaScript Answers

How to Filter Keys of an Object with Lodash?

Sometimes, we may want to extract some properties from an object and put them into a new object with Lodash.

In this article, we’ll look at how to get an object with only some of the keys from the original object.

Use the pickBy Method

Lodash comes with the pickBy method that takes an object and a callback that lets us return the condition of the keys we want to keep.

For instance, we can write:

const thing = {
  "a": 123,
  "b": 456,
  "abc": 6789
};

const result = _.pickBy(thing, (value, key) => {
  return _.startsWith(key, "a");
});
console.log(result)

Then we return an object with the properties from thing that starts with 'a' .

The first argument of pickBy is the object that we want to extract properties from.

The 2nd argument is the callback that returns the condition of the properties of the keys that we want to extract.

Then result is:

{
  "a": 123,
  "abc": 6789
}

Use the omitBy Method

We can also use the Lodash omitBy method to do the same thing.

For instance, we can write:

const thing = {
  "a": 123,
  "b": 456,
  "abc": 6789
};

const result = _.omitBy(thing, (value, key) => {
  return !_.startsWith(key, "a");
});
console.log(result)

The arguments are the same as pickBy except that the callback returns the condition for the keys that we don’t want in the returned object.

Therefore, result is the same as before.

Conclusion

We can use the pickBy or omitBy Lodash methods to extract the keys from an object and return an object with the properties we want from the original object.

Categories
JavaScript Answers

How to Render HTML to an Image with JavaScript?

Sometimes, we may want to render an HTML document or node to an image with JavaScript.

In this article, we’ll look at how to render an HTML document or node to an image with JavaScript.

Use the dom-to-image Library

The dom-to-image library makes converting an HTML node to an image easily.

For instance, if we have the following HTML:

<table>
  <tr>
    <td>col1 Val1</td>
    <td>col2 Val2</td>
  </tr>
  <tr>
    <td>col1 Val3</td>
    <td>col2 Val4</td>
  </tr>
</table>

<div>
</div>

Then we can add the library with the following script tag:

<script src="https://cdnjs.cloudflare.com/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js" integrity="sha512-01CJ9/g7e8cUmY0DFTMcUw/ikS799FHiOA0eyHsUWfOetgbx/t6oV4otQ5zXKQyIrQGTHSmRVPIgrgLcZi/WMA==" crossorigin="anonymous"></script>

Or we can add the library with NPM:

npm install dom-to-image

or Bower:

bower install dom-to-image

Then we can use it by writing the following JavaScript:

const table = document.querySelector("table");
const div = document.querySelector("div");
domtoimage.toPng(table)
  .then((dataUrl) => {
    const img = new Image();
    img.src = dataUrl;
    div.appendChild(img);
  })
  .catch((error) => {
    console.error(error);
  });

We call domtoimage.toPng with the element that we want to render to an image.

Then we get the dataUrl , which is the base64 string version of the image of the rendered element.

In the then callback, we create a new img element with the Image constructor.

Then we set the src property of it to dataUrl .

And then we call div.appendChild with img to append img to the div.

We can simplify this by using the async and await syntax:

const table = document.querySelector("table");
const div = document.querySelector("div");

(async () => {
  try {
    const dataUrl = await domtoimage.toPng(table)
    const img = new Image();
    img.src = dataUrl;
    div.appendChild(img);
  } catch (error) {
    console.error(error);
  }
})()

dataUrl is the same one as the then method callback parameter.

error is the same one as the one in the catch method callback parameter.

Conclusion

The dom-to-image Library lets us render an HTML node to an image easily with JavaScript.