Categories
JavaScript Answers

How to Take a Screenshot of a div with JavaScript?

Sometimes, we may want to take a screenshot of a div with JavaScript.

In this article, we’ll look at how to take a screenshot of a div with JavaScript.

Use the html2canvas Library

We can use the html2canvas library to capture the div as an image and put it into a canvas element.

To use it, we can add the library with a script tag by writing:

<script src='https://html2canvas.hertzen.com/dist/html2canvas.min.js'></script>

We can also install it with NPM by running:

npm install --save html2canvas

Or we can install it with Yarn by running:

yarn add html2canvas

Next, we can add the div we want to capture into an image by writing:

<div id="capture" style="padding: 10px; background: #f5da55">
  <h4 style="color: #000; ">Hello world!</h4>
</div>

Then to select and capture the element, we can write:

const getScreenshotOfElement = async (element) => {
  const canvas = await html2canvas(element)
  document.body.appendChild(canvas)
}

const div = document.querySelector('div')
getScreenshotOfElement(div)

We have the getScreenOfElement function that takes the element we want to capture into an image and put into a canvas.

In the function, we just call the html2canvas function with the element .

This function returns a promise that resolves to a canvas element with the element converted to an image in the canvas.

Then we call document.body.appendChild with the canvas to append it to the body.

Next, we select the div with querySelector .

And then we call the getScreenOfElement function that we just created.

Now we should see the canvas with the image of our div displayed below the actual div.

Conclusion

We can use the html2canvas library to capture an element into an image inside a canvas element.

This lets us take a screenshot of an element easily.

Categories
JavaScript Answers

How to Set the Keyboard Caret Position of an HTML Text Box with JavaScript?

Sometimes, we want to set the keyboard carte position of an HTML text box with JavaScript.

In this article, we’ll look at how to set the keyboard caret position of an HTML text box with JavaScript.

Use the HTML Element’s createTextRange, move and select Methods

We can use the createTextRange method to create a selection, then we can move the cursor of the selection to the location we want.

For instance, if we have the following HTML:

<input>

Then we can write the following JavaScript code to move the cursor.

For instance, we can write:

const setCaretPosition = (elem, caretPos) => {
  if (elem !== null) {
    if (elem.createTextRange) {
      const range = elem.createTextRange();
      range.move('character', caretPos);
      range.select();
    } else {
      if (elem.selectionStart) {
        elem.focus();
        elem.setSelectionRange(caretPos, caretPos);
      } else
        elem.focus();
    }
  }
}

const input = document.querySelector('input')
input.value = 'hello world'
setCaretPosition(input, 10)

We create the setCaretPosition function with the elem and caretPos parameters.

elem is the input element that we want to move the cursor of.

caretPos is the position of the cursor starting from 0 for the first position.

We check if elem isn’t null with the if statement.

If it’s not null , then we can check if the createTextRange method exists.

If it does, then we call it to create the range object.

Next, we call move with 'character' and caretPos to move the cursor.

Then we call select to apply the move.

Otherwise, we can also use focus method to focus on the input.

Then we call setSelectionRange to move to the position given by caretPos .

Then if we set a value of the input that’s longer than caretPos , then we can call setCaretPosition to move the cursor to where we want.

Conclusion

We can set the keyboard caret position of an input by creating a selection and setting the end position of the cursor with the selection range object.

Categories
JavaScript Answers

How to Unflatten a JSON Object with JavaScript?

To unflatten a flattened JavaScript object, we can split each property path and add the nested properties into the unflatten object.

To do this, we write:

const unflatten = (data) => {
  if (Object(data) !== data || Array.isArray(data))
    return data;
  const regex = /\.?([^.\[\]]+)$|\[(\d+)\]$/
  const props = Object.keys(data);
  let result, p;
  while (p = props.shift()) {
    const m = regex.exec(p)
    let target;
    if (m.index) {
      const rest = p.slice(0, m.index);
      if (!(rest in data)) {
        data[rest] = m[2] ? [] : {};
        props.push(rest);
      }
      target = data[rest];
    } else {
      if (!result) {
        result = (m[2] ? [] : {});
      }
      target = result
    }
    target[m[2] || m[1]] = data[p];
  }
  return result;
};

console.log(unflatten({
  'a[0].b[0]': "c",
  'a[0].b[1]': "d"
}))

We create the unflatten function to do the unflattering of a flattened object.

It takes the data parameter which can be anything.

In the function,m we check if data isn’t an object or is an array.

If either is true, then we return data as is.

Otherwise, we have the regex to parse the property path.

props has the keys from data .

We then loop through the keys and call regex.exec to get the property path parts and assign it to m .

Next, we get the index of the extracted property parts.

We then check if the property path path is in data .

If it’s not, then we add it to data .

And then we call props.push with rest to props .

Then we assign data[rest] to target to update targer .

Otherwise, we assign result to target .

If there are no property parts left, we add the target ‘s property to data.

And then we return result .

Now when we run the unflatten function, we should see an object with the a property with an array value.

And in it, we have the b property with an array value with 'c' and 'd' inside.

Categories
JavaScript Answers

How to Flatten a Nested JSON Object with JavaScript?

We can loop through each object property and check if a property is an object.

If it is, then we put the key in an object.

For instance, we can write:

const flatten = (obj, prefix = [], current = {}) => {
  if (typeof(obj) === 'object' && obj !== null) {
    for (const key of Object.keys(obj)) {
      flatten(obj[key], prefix.concat(key), current)
    }
  } else {
    current[prefix.join('.')] = obj
  }
  return current
}

console.log(flatten({
  a: [{
    b: ["c", "d"]
  }]
}));
console.log(flatten([1, [2, [3, 4], 5], 6]));

We create the flatten function that takes the obj , prefix , and current parameters.

prefix is the property name of the nested object.

current is the current value of the flattened object.

In the function body, we check if obj is an object and that obj isn’t null .

If they’re both true, then we know obj is an object.

Then we can loop through the keys obtained from Object.keys and call flatten inside the loop with the obj[key] , prefix , and current to traverse to the nested object.

Otherwise, obj isn’t an object and we can put the property as a property of current .

Now when we do run the 2 console log statements, we get:

{a.0.b.0: "c", a.0.b.1: "d"}

and:

{0: 1, 2: 6, 1.0: 2, 1.1.0: 3, 1.1.1: 4, 1.2: 5}

respectively.

Categories
JavaScript Answers

How to Reset the setTimeout Timer with JavaScript?

Sometimes, we want to reset the setTimeout timer so that we can use it again.

In this article, we’ll look at how to reset the setTimeout timer with JavaScript.

Use the clearTimeout Function

We can use the timer created by setTimeout function with the clearTimeout function.

For instance, we can write:

let timer;

const runTimer = () => {
  timer = window.setTimeout(
    () => {
      document.body.style.backgroundColor = 'black'
    }, 3000);
}

runTimer();

document.body.onclick = () => {
  clearTimeout(timer)
  runTimer()
}

We have the timer variable that stores the timer returned by setTimeout .

Then we have the runTimer function that calls the setTimeout function with a callback that turns the page black after 3 seconds.

We assign the returned timer to timer .

Next, we call runTimer to turn the screen black after 3 seconds.

We also have a click handler assigned to the onclick property of document.body to turn the screen black after 3 seconds after clicking it.

The clearTimeout function will reset the timer and will start counting from 0 milliseconds again.

Conclusion

We can reset the timer created by setTimeout function with the clearTimeout function.