Categories
JavaScript Answers

How to Add a Custom Button to the Toolbar that Calls a JavaScript Function with CKEditor?

Sometimes, we want to add a custom button to the toolbar that calls a JavaScript function with CKEditor.

In this article, we’ll look at how to add a custom button to the toolbar that calls a JavaScript function with CKEditor.

Add a Custom Button to the Toolbar that Calls a JavaScript Function with CKEditor

To add a custom button to the toolbar that calls a JavaScript function with CKEditor, we can add a command with the addCommand method.

Then we can add a method that calls the command with the addButton method.

For instance, we can add the editor with:

<script src="https://cdn.ckeditor.com/4.16.1/standard/ckeditor.js"></script>

<textarea id="container">How are you!</textarea>

Then we write:

const editor = CKEDITOR.replace('container');

editor.addCommand("mySimpleCommand", {
  exec(edt) {
    console.log(edt.getData());
  }
});

editor.ui.addButton('SuperButton', {
  label: "Click me",
  command: 'mySimpleCommand',
  toolbar: 'insert',
  icon: 'https://avatars1.githubusercontent.com/u/5500999?v=2&s=16'
});

to create the editor with:

const editor = CKEDITOR.replace('container');

Then we add a command with:

editor.addCommand("mySimpleCommand", {
  exec(edt) {
    console.log(edt.getData());
  }
});

The first argument is the name of the command.

The 2nd argument is an object with the exec method that has the code for the command.

We just call getData to get the input value of the text editor.

Next, we call ui.addButton with the button name the first argument.

Then 2nd argument has the settings for the button, which includes the command property set to the command that we want to run.

The icon is the URL for the icon.

Conclusion

To add a custom button to the toolbar that calls a JavaScript function with CKEditor, we can add a command with the addCommand method.

Then we can add a method that calls the command with the addButton method.

Categories
JavaScript Answers

How to Draw Lines in the HTML Canvas Without the Last Ones Being Faded?

Sometimes, we want to draw lines in the HTML canvas without the last ones being faded

In this article, we’ll look at how to draw lines in the HTML canvas without the last ones being faded.

Draw Lines in the HTML Canvas Without the Last Ones Being Faded

To draw lines in the HTML canvas without the last ones being faded, we can use the lineTo method and set the strokeStyle to the values we want.

For instance, we can create a canvas with:

<canvas id="myCanvas" width="400" height="400"></canvas>

Then we write:

const objCanvas = document.getElementById("myCanvas");
const objContext = objCanvas.getContext("2d");
const intGridWidth = 20;

const drawBackground = () => {
  objContext.clearRect(0, 0, objCanvas.width, objCanvas.height);
  objContext.fillStyle = 'black';
  objContext.fillRect(0, 0, objCanvas.width, objCanvas.height);
  objContext.strokeStyle = "white";
  for (let i = 1; i < objCanvas.width / intGridWidth; i++) {
    const x = Math.floor(i * intGridWidth) + 0.5;
    objContext.moveTo(x, 0);
    objContext.lineTo(x, objCanvas.height);
    objContext.stroke();
  }

  for (let i = 1; i < objCanvas.height / intGridWidth; i++) {
    const y = Math.floor(i * intGridWidth) + 0.5
    objContext.moveTo(0, y);
    objContext.lineTo(objCanvas.width, y);
    objContext.stroke();
  }

}
drawBackground();

to create the drawBackground function that clears the rectangle with:

objContext.clearRect(0, 0, objCanvas.width, objCanvas.height);

Then we set the background to black with:

objContext.fillStyle = 'black';

Then we apply the background styles with:

objContext.fillRect(0, 0, objCanvas.width, objCanvas.height);

Next, we set the line stroke style with:

objContext.strokeStyle = "white";

Next, we create the vertical grid lines with:

for (let i = 1; i < objCanvas.width / intGridWidth; i++) {
  const x = Math.floor(i * intGridWidth) + 0.5;
  objContext.moveTo(x, 0);
  objContext.lineTo(x, objCanvas.height);
  objContext.stroke();
}

We create the horizontal grid lines with:

for (let i = 1; i < objCanvas.height / intGridWidth; i++) {
  const y = Math.floor(i * intGridWidth) + 0.5
  objContext.moveTo(0, y);
  objContext.lineTo(objCanvas.width, y);
  objContext.stroke();
}

We use moveTo to move to the position we want to start drawing.

lineTo adds the line from the start and end position respectively.

stroke draws the line onto the canvas.

Conclusion

To draw lines in the HTML canvas without the last ones being faded, we can use the lineTo method and set the strokeStyle to the values we want.

Categories
JavaScript Answers

How to Convert a File Input Value to a Byte Array with JavaScript?

Sometimes, we want to convert a file input value to a byte array with JavaScript.

In this article, we’ll look at how to convert a file input value to a byte array with JavaScript.

Convert a File Input Value to a Byte Array with JavaScript

To convert a file input value to a byte array with JavaScript, we can convert the selected file into a byte array by creating an FileReader instance.

For instance, if we have the following HTML:

<input type='file'>

Then we can write:

const input = document.querySelector('input')
const reader = new FileReader();
const fileByteArray = [];

input.addEventListener('change', (e) => {
  reader.readAsArrayBuffer(e.target.files[0]);
  reader.onloadend = (evt) => {
    if (evt.target.readyState === FileReader.DONE) {
      const arrayBuffer = evt.target.result,
        array = new Uint8Array(arrayBuffer);
      for (const a of array) {
        fileByteArray.push(a);
      }
      console.log(fileByteArray)
    }
  }
})

to get the input with document.querySelector .

Then we create a FileReader instance with:

const reader = new FileReader();

And we create a byte array with:

const fileByteArray = [];

Next, we call reader.readAsArrayBuffer in the file input’s change event listener to read the file into an array buffer.

Then we set the onloadend function to a function that runs when the file is loaded.

In the function, we get the buffer result with assign it to arrayBuffer .

Then we create the Uint8Array and assign it to array .

Finally, we push all the array entries into the fileByteArray .

Conclusion

To convert a file input value to a byte array with JavaScript, we can convert the selected file into a byte array by creating an FileReader instance.

Categories
JavaScript Answers

How to Get the Number of Lines in a textarea Using JavaScript?

Sometimes, we want to get the number of lines in a textarea using JavaScript.

In this article, we’ll look at how to get the number of lines in a textarea using JavaScript.

Get the Number of Lines in a textarea Using JavaScript

To get the number of lines in a textarea using JavaScript, we can call split on the input value of the textarea by the newline character.

Then we get the length of the returned string array.

For instance, we can write:

<textarea></textarea>

to create a textarea element.

Then we write:

const textarea = document.querySelector('textarea')
textarea.addEventListener('input', () => {
  const text = textarea.value;
  const lines = text.split("\n");
  const count = lines.length;
  console.log(count);
})

We select the textarea with the document.querySelector.

Then we call addEventListener to listen to the input event.

In the input event handler, we get the textarea’s input value with textarea.value.

Then we call split with \n to split the value by the newline character.

And finally, we get the length of the split lines.

Therefore, now we should see the number of lines logged as we type.

Conclusion

To get the number of lines in a textarea using JavaScript, we can call split on the input value of the textarea by the newline character.

Then we get the length of the returned string array.

Categories
JavaScript Answers

How to Calculate the UTC Offset Given a Time Zone String in JavaScript?

Sometimes, we want to calculate the UTC offset given a time zone string in JavaScript.

In this article, we’ll look at how to calculate the UTC offset given a time zone string in JavaScript.

Calculate the UTC Offset Given a Time Zone String in JavaScript

To calculate the UTC offset given a time zone string in JavaScript, we can use the JavaScript date’s toLocaleString method to get the time zone offset.

For instance, we can weite:

const getTimezoneOffset = (d, timeZone) => {
  const a = d.toLocaleString("ja", {
    timeZone
  }).split(/[/s:]/);
  a[1]--;
  const t1 = Date.UTC(...a);
  const t2 = new Date(d).setMilliseconds(0);
  return (t2 - t1) / 60 / 1000;
}

console.log(getTimezoneOffset(new Date(2016, 0, 1), "America/New_York"))

to create the getTimezoneOffset function that takes the d date and timeZone .

We get the date parts in an array with the toLocaleString method which we called with the timeZone .

Then we subtract the month number by 1 to match the JavaScript convention with:

a[1]--;

Next, we call Date.UTC with the a array spread as the arguments to create t1

Then we create t2 with 0 milliseconds.

Next, we subtract t2 and t1 and divide that by 60 seconds and return that.

Now we get the time zone offset in minutes.

Conclusion

To calculate the UTC offset given a time zone string in JavaScript, we can use the JavaScript date’s toLocaleString method to get the time zone offset.