Categories
JavaScript Answers

How to check if an element has been loaded on a page before running a script with JavaScript?

Sometimes, we want to check if an element has been loaded on a page before running a script with JavaScript.

In this article, we’ll look at how to check if an element has been loaded on a page before running a script with JavaScript.

How to check if an element has been loaded on a page before running a script with JavaScript?

To check if an element has been loaded on a page before running a script with JavaScript, we can use the mutation observer.

For instance, we write:

const observer = new MutationObserver((mutationRecords) => {
  console.log("change detected");
});
observer.observe(document.body, {
  childList: true
})

setTimeout(() => {
  const div = document.createElement('div')
  document.body.appendChild(div)
}, 100)

to create a MutationObserver instance.

Then we call observer.observer with the element we want to observe and an object that sets the items we want to observe,.

We set childList to true to watch for DOM item changes.

Next, we create a div and call document.body.appendChild with div to append a div to the body element.

And when we did that, we should see 'change detected' logged.

Conclusion

To check if an element has been loaded on a page before running a script with JavaScript, we can use the mutation observer.

Categories
JavaScript Answers

How to stop anchor element click from making page jump to top of page with JavaScript?

Sometimes, we want to stop anchor element click from making page jump to top of page with JavaScript.

In this article, we’ll look at how to stop anchor element click from making page jump to top of page with JavaScript.

How to stop anchor element click from making page jump to top of page with JavaScript?

To stop anchor element click from making page jump to top of page with JavaScript, we call preventDefault in the anchor element’s click handler.

For instance, we write:

<a href='#'>click me</a>

to add the anchor element.

Then we write:

const a = document.querySelector('a')
a.onclick = (e) => {
  e.preventDefault()
}

to select the anchor element with querySelectorAll.

Then we set a.onclick to a function that calls e.preventDefault to stop the page from moving up when we click it.

Conclusion

To stop anchor element click from making page jump to top of page with JavaScript, we call preventDefault in the anchor element’s click handler.

Categories
JavaScript Answers

How to attach event listener to a radio button with JavaScript?

Sometimes, we want to attach event listener to a radio button with JavaScript.

In this article, we’ll look at how to attach event listener to a radio button with JavaScript.

How to attach event listener to a radio button with JavaScript?

To attach event listener to a radio button with JavaScript, we can loop through each radio button and set its onclick property.

For instance, we write:

<form>
  <input type="radio" name="myradio" value="A" />
  <input type="radio" name="myradio" value="B" />
  <input type="radio" name="myradio" value="C" />
  <input type="radio" name="myradio" value="D" />
</form>

to add a form with radio buttons.

Then we write:

const radios = document.querySelectorAll('input')
for (const radio of radios) {
  radio.onclick = (e) => {
    console.log(e.target.value);
  }
}

to select the radio buttons with querySelectorAll.

Then we loop through them with a for-of loop.

In it, we set radio.onclick to a function that logs the value attribute of the radio button.

Conclusion

To attach event listener to a radio button with JavaScript, we can loop through each radio button and set its onclick property.

Categories
JavaScript Answers

How to compare decimal numbers with JavaScript?

Sometimes, we want to compare decimal numbers with JavaScript.

In this article, we’ll look at how to compare decimal numbers with JavaScript.

How to compare decimal numbers with JavaScript?

To compare decimal numbers with JavaScript, we can round both numbers and then compare them.

For instance, we write:

const a = 99.99
const b = 101.99
console.log((Math.round(a * 100) > Math.round(b * 100)))

to multiply a and b by 100 and call Math.round with the returned number to get rid of the decimals.

Then we use > to compare them.

Since a is smaller than b, the console log should log false.

Conclusion

To compare decimal numbers with JavaScript, we can round both numbers and then compare them.

Categories
JavaScript Answers

How to delete an item from list with React and JavaScript?

Sometimes, we want to delete an item from list with React and JavaScript.

In this article, we’ll look at how to delete an item from list with React and JavaScript.

How to delete an item from list with React and JavaScript?

To delete an item from list with React and JavaScript, we can use some array methods.

For instance, we write:

import React from "react";

const arr = [
  { id: 1, name: "apple" },
  { id: 2, name: "orange" },
  { id: 3, name: "grape" }
];

export default function App() {
  const [items, setItems] = React.useState(arr);

  const deleteItem = (index) => () =>
    setItems((items) => items.filter((_, i) => i !== index));

  return (
    <>
      {items.map((it, index) => {
        return (
          <div key={it.id}>
            {it.name} <button onClick={deleteItem(index)}>delete</button>
          </div>
        );
      })}
    </>
  );
}

to create the items state with useState.

Then we define the deleteItem function that takes the index of the item to delete and returns a function that calls setItems with (items) => items.filter((_, i) => i !== index) to set items to an array that doesn’t include the item in items at index.

Next, we call items.map to render the items with a delete button in each entry.

We set the onClick prop of the button to the function returned by deleteItem when called with the index.

Conclusion

To delete an item from list with React and JavaScript, we can use some array methods.