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);
Categories
JavaScript Answers

How to Sort a JavaScript Map Object?

We can sort a JavaScript map object by spreading the entries returned by the entries method into an array.

Then we call sort on that to sort the entries.

For instance, we can write:

const map = new Map();
map.set('2-1', "foo");
map.set('0-1', "bar");
map.set('3-1', "baz");
const mapAsc = new Map([...map.entries()].sort());
console.log(mapAsc)

to create a map object with several key-value pairs.

Then we call map.entries to return an iterator with arrays of key-value pairs in the map.

Next, we spread that into an array so we can call sort on it to sort it by the keys.

And then we convert it back to a map with the Map constructor.

Therefore, mapAsc is:

{"0-1" => "bar", "2-1" => "foo", "3-1" => "baz"}

Conclusion

We can sort a JavaScript map object by spreading the entries returned by the entries method into an array.

Then we call sort on that to sort the entries.