Categories
JavaScript Answers

How to Paste Text as Plain Text into a Content Editable Element with JavaScript?

We can paste plain text into a content editable element by listening to the paste event and modifying the pasting behavior.

For instance, if we have the following div:

<div contenteditable>

</div>

Then we can modify the paste behavior by listening to the paste event:

const editor = document.querySelector('div')
editor.addEventListener("paste", (e) => {
  e.preventDefault();
  const text = e.clipboardData.getData('text/plain');
  document.execCommand("insertHTML", false, text);
});

We get the div with document.querySelector .

Then we listen to the paste event with addEventListener .

We pass in a callback that calls e.preventDefault to stop the default paste behavior.

Then we get the pasted text with the e.clipboard.getData method.

We pass in 'text/plain' to get the pasted data as plain text.

And then we call document.execCommand to run the insertHTML command with the text to paste it into the editor div as plain text.

Categories
JavaScript Answers

How to Disable Drag and Drop on HTML Elements?

We can disable drag and drop on HTML elements by setting the draggable attribute to false .

For instance, we can write:

<div draggable="false">
  hello world
</div>

We set draggable to false so we can’t drag it.

To make it more robust, we can also stop the default drag and drop behavior with:

const div = document.querySelector('div')
div.addEventListener('dragstart', (e) => {
  e.preventDefault()
})

div.addEventListener('drop', (e) => {
  e.preventDefault()
})

We add event listeners for the dragstart and drop events with addEventListener .

And we call e.preventDefault() on both to stop the default drag and drop action.

Categories
JavaScript Answers

How to Check if the Response of a Fetch is a JSON Object in JavaScript?

We can check if a response of a fetch call is a JSON object with JavaScript by putting the fetch call in a try-catch block and use JSON.parse to parse the response string.

For instance, we can write:

const myFetch = async (myRequest) => {  
  try {  
    const response = await fetch(myRequest);  
    const text = await response.text();  
    const data = JSON.parse(text);  
    console.log(data)  
  } catch (err) {  
    console.log(err)  
  }  
}  
myFetch('https://yesno.wtf/api')

to create the myFetch function with the myRequest string parameter for the URL.

We pass myRequest into fetch to make the request

Then we call response.text to get the response string.

Next, we call JSON.parse with text to try to parse the response string.

If it’s successful, data should be assigned the parsed JSON object.

Otherwise, an error will be raised and err is logged.

Categories
JavaScript Answers

How to Create an img Element with JavaScript?

One way to create an img element with JavaScript is to use the Image constructor.

For instance, we can write:

const img = new Image(200, 300);  
img.src = 'https://i.picsum.photos/id/487/200/300.jpg?hmac=jDYxTxKFMi18Gu5h9qt9ttwJKCk1-J6bZeHDtXGL2Vk';  
document.body.appendChild(img)

We use the Image constructor with 2 arguments to create an img element.

The arguments are the width and height respectively.

Then we set the src property to the image URL to set the src attribute value.

And then we call document.body.appendChild with img to append it to the body.

Create an img Element with JavaScript with the document.createElement Method

Another way to create an img element with JavaScript is to use the document.createElement method.

For instance, we can write:

const img = document.createElement('img');  
img.src = 'https://i.picsum.photos/id/487/200/300.jpg?hmac=jDYxTxKFMi18Gu5h9qt9ttwJKCk1-J6bZeHDtXGL2Vk';  
document.body.appendChild(img)

to use:

const img = document.createElement('img');

to create an img element.

And the rest of the code is the same.

Categories
JavaScript Answers

How to Create an HTML Table Using JavaScript?

We can create an HTML table with the document.createElement method.

For instance, if we have the following HTML:

<div>

</div>

Then we can create the table and attach it to the div by writing:

const div = document.querySelector("div");
const table = document.createElement('table');
table.border = '1';
const tableBody = document.createElement('tbody');
table.appendChild(tableBody);

for (let i = 0; i < 3; i++) {
  const tr = document.createElement('tr');
  tableBody.appendChild(tr);
  for (let j = 0; j < 4; j++) {
    const td = document.createElement('td');
    td.width = '75';
    td.appendChild(document.createTextNode(`cell ${i}-${j}`));
    tr.appendChild(td);
  }
}
div.appendChild(table);

We get the div with document.querySelector .

Then we create the table element with:

const table = document.createElement('table');

We set the border width in pixels with:

table.border = '1';

Then we create the tbody element with:

const tableBody = document.createElement('tbody');

Next, we append the tbody element to the table with:

table.appendChild(tableBody);

Then we add the tr and td elements into the tr with:

for (let i = 0; i < 3; i++) {
  const tr = document.createElement('tr');
  tableBody.appendChild(tr);
  for (let j = 0; j < 4; j++) {
    const td = document.createElement('td');
    td.width = '75';
    td.appendChild(document.createTextNode(`cell ${i}-${j}`));
    tr.appendChild(td);
  }
}

We create the table row element with:

const tr = document.createElement('tr');

Then we attach it to the tbody with:

tableBody.appendChild(tr);

Then we have another loop inside to add the td and append the td in the tr as its child:

for (let j = 0; j < 4; j++) {
  const td = document.createElement('td');
  td.width = '75';
  td.appendChild(document.createTextNode(`cell ${i}-${j}`));
  tr.appendChild(td);
}

We set the width of the td and call document.createTextNode and td.appendChild to add the text inside the td .

Then tr.appendChild(td) add the td as the last child of tr .

Finally, we add the table into the div with:

div.appendChild(table);