Categories
JavaScript Answers

How to Round Up to the Next Multiple of 5 with JavaScript?

We can use the Math.ceil method to round up to the next multiple of 5 with JavaScript.

For instance, we can write:

const round5 = (x) => {
  return Math.ceil(x / 5) * 5;
}
console.log(round5(18))

We create the round5 function to return the number x divided by 5.

Then we round that number up to the nearest integer with Math.ceil .

Next, we multiply that by 5 to get x rounded up to the nearest integer.

Therefore, the console log logs 20.

Categories
JavaScript Answers

How to Embed SVGs into React?

We can embed SVGs directly with JSX into our React app.

For instance, we can write:

import React from "react";

const SvgWithXlink = (props) => {
  return (
    <svg
      width="100%"
      height="100%"
      xmlns="http://www.w3.org/2000/svg"
      xmlnsXlink="http://www.w3.org/1999/xlink"
    >
      <style>{\`.classA { fill:${props.fill} }\`}</style>
      <defs>
        <g id="Port">
          <circle style={{ fill: "inherit" }} r="10" />
        </g>
      </defs>

      <text y="15">black</text>
      <use x="70" y="10" xlinkHref="#Port" />
      <text y="35">{props.fill}</text>
      <use x="70" y="30" xlinkHref="#Port" className="classA" />
      <text y="55">blue</text>
      <use x="70" y="50" xlinkHref="#Port" style={{ fill: "blue" }} />
    </svg>
  );
};

export default function App() {
  return (
    <div className="App">
      <SvgWithXlink fill="green" />
    </div>
  );
}

to embed the SVG in the SvgWithXLink component.

We just put the elements required to embed the SVG into the component.

And we can pass props into the elements as we do with any other HTML elements or components.

We have the circle to add circles.

And the xLinkHref attribute lets us the circle by the id of the g element.

x and y are the coordinates of the location of the elements.

In App , we add SvgWithXLink with the fill prop set to 'green' .

Now we see 3 circles.

Categories
JavaScript Answers

How to Get Elements by Their name Attribute Value with JavaScript?

We can use the document.getElementsByName to get elements by the value of their name attribute.

For instance, if we have the following HTML:

Account <input type="text" name="acc"  value='abc'/>
Password <input type="password" name="pass" />

Then we can get the value of the first input by writing:

const [acc] = document.getElementsByName("acc")
console.log(acc.value)

We call document.getElementsByName with 'acc' to return a NodeList with all the elements that have the name attribute set to acc .

Then we destructure that to get the first element from the NodeList.

Finally, we get the value of it with acc.value .

Therefore, acc.value is 'abc' .

Categories
JavaScript Answers

How to Remove Multiple Elements from an Array in JavaScript?

One way to remove multiple elements from a JavaScript array is to use a for -of loop.

For instance, we can write:

const valuesArr = ["v1", "v2", "v3", "v4", "v5"],
  removeValFromIndex = [0, 2, 4];

for (const i of removeValFromIndex.reverse()) {
  valuesArr.splice(i, 1);
}
console.log(valuesArr)

We have the valuesArr with the items we want to remove.

removeValFromIndex has the indexes with the indexes of valuesArr that we want to remove.

Then we loop through the removeValFromIndex backwards with reverse and the for-of loop and remove each item with splice .

We’ve to loop backwards so that we won’t mess up the indexes for items that are yet to be removed.

Therefore, valuesArr is [“v2”, “v4”] .

Use Array.prototype.filter

Also, we can use the JavaScript array filter method to remove items from the array given the indexes of the items we want to remove.

For instance, we can write:

const valuesArr = ["v1", "v2", "v3", "v4", "v5"],
  removeValFromIndex = [0, 2, 4];

const filtered = valuesArr.filter((value, index) => {
  return !removeValFromIndex.includes(index);
})
console.log(filtered)

We call filter with a callback that has the index parameter as the 2nd parameter.

Then we call includes with index to see if the index isn’t in removeValFromIndex .

If it’s not, then we keep the item with the given index in the returned array.

Therefore, filtered is [“v2”, “v4”] .

Categories
JavaScript Answers

How to Get the Caret Index Position of a contentEditable Element with JavaScript?

We can use the document.getSelector to get the selection.

And then we can use that to get the length of the selection to get the cursor position.

For instance, we can write the following HTML:

<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>

Then we can write the following JavaScript code to get the location of the cursor by writing:

const cursorPosition = () => {
  const sel = document.getSelection();
  sel.modify("extend", "backward", "paragraphboundary");
  const pos = sel.toString().length;
  if (sel.anchorNode != undefined) sel.collapseToEnd();
  return pos;
}

const elm = document.querySelector('[contenteditable]');

const printCaretPosition = () => {
  console.log(cursorPosition(), 'length:', elm.textContent.trim().length)
}
elm.addEventListener('click', printCaretPosition)
elm.addEventListener('keydown', printCaretPosition)

We have the cursorPosition function that calls the documebnt.getSelection method to get the text inside the div.

Then we call modify to adjust the current selection.

We move 'backward' by 'paragraphboundary' .

Then we get the length of the selection after converting it to a string.

And then we collapse the selection and return pos to return the position of the cursor.

Next, we get the div with querySelector .

And then we create the printCaretPosition to print the cursor position.

Finally, we call addEventListener so that we call printCaretPosition when we click or type on the div.