Categories
JavaScript Answers

How to Flatten JavaScript Object Keys and Values to a Single Depth Object?

To flatten JavaScript object keys and values to a single depth object, we can create our own function to recursive traverse the object we’re flattening.

For instance, we write:

const obj = {
  name: "test",
  address: {
    personal: "abc",
    office: {
      building: 'random',
      street: 'some street'
    }
  }
}

const flattenObj = (obj, parent, res = {}) => {
  for (const key of Object.keys(obj)) {
    const propName = parent ? parent + '.' + key : key;
    if (typeof obj[key] === 'object') {
      flattenObj(obj[key], propName, res);
    } else {
      res[propName] = obj[key];
    }
  }
  return res;
}

const flattened = flattenObj(obj)
console.log(flattened)

to create the obj object that we want to flatten.

Then we add the flattenObj function that takes the obj, parent, and res objects.

Then we loop through the keys of the object with Object.keys and the for-of loop.

In the loop body, if parent is defined, then we concatenate the parent property name with the key we’re iterating through separated by a dot and assign it to propName.

Otherwise, we set propName to key.

If obj[key] is an object we call flattenObj with obj[key], propName, and res.

res has the flattened object result so far.

Otherwise, we set res[propName] to obj[key].

Once we’re done traversing, we return res.

Next, we call flattenObj with obj and assign it to flattened.

And then we see that flattened is:

{
  "name": "test",
  "address.personal": "abc",
  "address.office.building": "random",
  "address.office.street": "some street"
}
``
Categories
JavaScript Answers

How to Dynamically Change Font Size Based on Text Length Using JavaScript?

Sometimes, we want to dynamically change font size based on text length using JavaScript.

In this article, we’ll look at how to dynamically change the size of font size based on text length using JavaScript.

Dynamically Change Font Size Based on Text Length Using JavaScript

To dynamically change the size of font size based on text length using JavaScript, we can resize the text if the height of the containing div is bigger than the div containing the text.

For instance, we write:

<input type="text" >

<div id="outer" class="container" style="width:80%; height:100px; border:2px solid red; font-size:20px;">

  <div class="output" style="word-break: break-all; word-wrap: break-word;">
  </div>

</div>

to add the input to enter the text and the outer and inner divs.

The inner div will contain the text.

Next, we write:

const input = document.querySelector('input');
const output = document.querySelector('.output');
const outputContainer = document.querySelector('.container');

const resizeToFfit = () => {
  let fontSize = window.getComputedStyle(output).fontSize;
  output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';

  if (output.clientHeight >= outputContainer.clientHeight) {
    resizeToFfit();
  }
}

function processInput() {
  output.innerHTML = this.value;
  output.style.fontSize = '100px';
  resizeToFfit();
}

input.addEventListener('input', processInput);

to select the elements with document.querySelector.

Then we add the resizeToFit function that gets the font size of the output element with getComputedStyle.

Next, we set the fontSize to the parsed font size with:

output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';

Then if output.clientHeight is bigger than or equal to outputContainer.clientHeight, we call resizeToFit to resize the text.

Then we add the processInput function that takes the input value with this.value and assign it to output.innerHTML to show the text.

Next, we set the font size of the text to 100px.

And finally, we call resizeToFit to make the text fit in the box.

Then we call input.addEventListener to listen to the input event and run processInput when we type in something into the input.

Conclusion

To dynamically change the size of font size based on text length using JavaScript, we can resize the text if the height of the containing div is bigger than the div containing the text.

Categories
JavaScript Answers

How to Trigger CSS Animations in JavaScript?

Sometimes, we want to trigger CSS animations in JavaScript.

In this article, we’ll look at how to trigger CSS animations in JavaScript.

Trigger CSS Animations in JavaScript

To trigger CSS animations in JavaScript, we just add the class that is set to animate the keyframes in CSS.

For instance, if we have:

<div class='TimeCountdown_circle1'>
  circle
</div>
<div class='TimeCountdown_circle2'>
  circle
</div>

Then we add animation with:

@keyframes circle1 {
  from {
    background-color: red;
  }

  to {
    background-color: yellow;
  }
}

@keyframes circle2 {
  from {
    background-color: red;
  }

  to {
    background-color: yellow;
  }
}

.circle_ani1,
.circle_ani2 {
  animation-duration: 1s;
  animation-iteration-count: 1;
}

.circle_ani1 {
  animation-name: circle1;
}

.circle_ani2 {
  animation-name: circle2;
}

We add the @keyframes property with the animation we want to animate.

It’ll animate from the from styles to the to styles.

Then we set the animation-name to the keyframes we want to animate within the class selectors.

Next, we write:

const tempCircle1 = $('.TimeCountdown_circle1').removeClass('circle_ani1');
const tempCircle2 = $('.TimeCountdown_circle2').removeClass('circle_ani2');
window.setTimeout(() => {
  tempCircle1.addClass('circle_ani1');
  tempCircle2.addClass('circle_ani2');
}, 50);

to remove the circle_ani1 and circle_ani2 classes with jQuery’s removeClass after we select them.

Then we call addClass to add the classes to the elements.

Conclusion

To trigger CSS animations in JavaScript, we just add the class that is set to animate the keyframes in CSS.

Categories
JavaScript Answers

How to Set the Scrollbar Position with JavaScript?

Sometimes, we want to set the scrollbar position with JavaScript.

In this article, we’ll look at how to set the scrollbar position with JavaScript.

Set the Scrollbar Position with JavaScript

To set the scrollbar position with JavaScript, we can set the scrollTop property of the scroll container element to the value of the offsetTop property of the element we want to scroll to.

For instance, if we have:

<div id='container' style='height: 100px; overflow-y: scroll'>
  <div>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis augue a ante rutrum, non ornare erat maximus. Fusce sagittis nunc sed tellus sagittis, vitae volutpat odio faucibus. Nullam consequat ut mi a consequat. Praesent a porttitor magna. Donec placerat mollis sapien ac eleifend.
  </div>
  <div id='row'>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus facilisis augue a ante rutrum, non ornare erat maximus. Fusce sagittis nunc sed tellus sagittis, vitae volutpat odio faucibus. Nullam consequat ut mi a consequat. Praesent a porttitor magna. Donec placerat mollis sapien ac eleifend.
  </div>
</div>

Then we write:

const container = document.getElementById('container');
const rowToScrollTo = document.getElementById('row');

container.scrollTop = rowToScrollTo.offsetTop;

We get the scroll container with document.getElementById and assign it to container.

And we do the same with the element we want to scroll to and assign it to rowScrollTo.

Finally, we set rowScrollTo.offsetTop to container.scrollTop to do the scrolling to the div with ID row.

Conclusion

To set the scrollbar position with JavaScript, we can set the scrollTop property of the scroll container element to the value of the offsetTop property of the element we want to scroll to.

Categories
JavaScript Answers

How to Rotate a Single Object on an HTML5 Canvas?

Sometimes, we want to rotate a single object on an HTML5 canvas.

In this article, we’ll look at how to rotate a single object on an HTML5 canvas.

Rotate a Single Object on an HTML5 Canvas

To rotate a single object on an HTML5 canvas, we can use the canvas context’s translate and rotate methods.

For instance, we write:

<canvas id='canvas'></canvas>

to create the canvas element.

Then we write:

const drawImageRot = (ctx, img, x, y, width, height, deg) => {
  ctx.save()
  const rad = deg * Math.PI / 180;
  ctx.translate(x + width / 2, y + height / 2);
  ctx.rotate(rad);
  ctx.drawImage(img, width / 2 * (-1), height / 2 * (-1), width, height);
  ctx.restore();
}

const img = new Image();
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAApgAAAKYB3X3/OAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAANCSURBVEiJtZZPbBtFFMZ/M7ubXdtdb1xSFyeilBapySVU8h8OoFaooFSqiihIVIpQBKci6KEg9Q6H9kovIHoCIVQJJCKE1ENFjnAgcaSGC6rEnxBwA04Tx43t2FnvDAfjkNibxgHxnWb2e/u992bee7tCa00YFsffekFY+nUzFtjW0LrvjRXrCDIAaPLlW0nHL0SsZtVoaF98mLrx3pdhOqLtYPHChahZcYYO7KvPFxvRl5XPp1sN3adWiD1ZAqD6XYK1b/dvE5IWryTt2udLFedwc1+9kLp+vbbpoDh+6TklxBeAi9TL0taeWpdmZzQDry0AcO+jQ12RyohqqoYoo8RDwJrU+qXkjWtfi8Xxt58BdQuwQs9qC/afLwCw8tnQbqYAPsgxE1S6F3EAIXux2oQFKm0ihMsOF71dHYx+f3NND68ghCu1YIoePPQN1pGRABkJ6Bus96CutRZMydTl+TvuiRW1m3n0eDl0vRPcEysqdXn+jsQPsrHMquGeXEaY4Yk4wxWcY5V/9scqOMOVUFthatyTy8QyqwZ+kDURKoMWxNKr2EeqVKcTNOajqKoBgOE28U4tdQl5p5bwCw7BWquaZSzAPlwjlithJtp3pTImSqQRrb2Z8PHGigD4RZuNX6JYj6wj7O4TFLbCO/Mn/m8R+h6rYSUb3ekokRY6f/YukArN979jcW+V/S8g0eT/N3VN3kTqWbQ428m9/8k0P/1aIhF36PccEl6EhOcAUCrXKZXXWS3XKd2vc/TRBG9O5ELC17MmWubD2nKhUKZa26Ba2+D3P+4/MNCFwg59oWVeYhkzgN/JDR8deKBoD7Y+ljEjGZ0sosXVTvbc6RHirr2reNy1OXd6pJsQ+gqjk8VWFYmHrwBzW/n+uMPFiRwHB2I7ih8ciHFxIkd/3Omk5tCDV1t+2nNu5sxxpDFNx+huNhVT3/zMDz8usXC3ddaHBj1GHj/As08fwTS7Kt1HBTmyN29vdwAw+/wbwLVOJ3uAD1wi/dUH7Qei66PfyuRj4Ik9is+hglfbkbfR3cnZm7chlUWLdwmprtCohX4HUtlOcQjLYCu+fzGJH2QRKvP3UNz8bWk1qMxjGTOMThZ3kvgLI5AzFfo379UAAAAASUVORK5CYII=";
img.onload = () => {
  const scale = 8;
  const srcCanvas = document.querySelector('canvas');
  const srcCtx = srcCanvas.getContext('2d');
  drawImageRot(srcCtx, img, 0, 0, 100, 100, 90)
};

to create the drawImageRot function to rotate the image.

The function takes the ctx canvas context, img img element object, x and y coordinates of the top left corner of the image, width and height of the image, and deg degrees of rotation.

In the function, we call save to save the contents.

Then we convert deg to rad radians.

Next, we call ctx.translate to translate the content by width / 2 and height / 2.

Then we call rotate to rotate the image.

After that we call drawImage to draw a rotated image.

Finally, we call restore to render the image.

Next we use the Image constructor to create the image.

Finally, we set img.onload to a function that gets the canvas with document.querySelector.

Then we call getContext to get the context.

And then we call drawImageRot to draw the image rotated 90 degrees.

Conclusion

To rotate a single object on an HTML5 canvas, we can use the canvas context’s translate and rotate methods.