Categories
JavaScript Answers

How to get the next / previous element using JavaScript?

To get the next / previous element using JavaScript, we use the nextSibling and previousSibling properties.

For instance, we write

<div id="foo1"></div>
<div id="foo2"></div>
<div id="foo3"></div>

Then we write

const foo3 = document.getElementById("foo2").nextSibling;
const foo1 = document.getElementById("foo2").previousSibling;

to get the element with ID foo2 with getElementById.

We get its next sibling with nextSibling, which is the div with ID foo3.

And get its previous sibling with previousSibling, which is the div with ID foo1.

Categories
JavaScript Answers

How to change cursor to waiting in JavaScript?

To change cursor to waiting in JavaScript, we set the body’s cursor style.

For instance, we write

document.body.style.cursor = "wait";

to set the body element’s cursor to 'wait' to show the loading the cursor.

Then we write

document.body.style.cursor = "default";

to set the body element’s cursor to 'default' to show the default cursor.

Categories
JavaScript Answers

How to add anchor jumping by using JavaScript?

To add anchor jumping by using JavaScript, we use the scrollTo method.

For instance, we write

const jump = (h) => {
  const top = document.getElementById(h).offsetTop;
  window.scrollTo(0, top);
};

to define the jump function.

In it, we get the element with getElementById.

And we get the y coordinate of the target element with offsetTop.

Then we call window.scrollTo with 0 and top to scroll to the element.

Categories
JavaScript Answers

How to detect if a browser is blocking a popup with JavaScript?

To detect if a browser is blocking a popup with JavaScript, we check various property of the window.

For instance, we write

const newWin = window.open(url);

if (!newWin || newWin.closed || typeof newWin.closed === "undefined") {
  //...
}

to call window.open to open url in a new window.

Then if newWin is undefined, or closed is true, or closed is undefined, then the popup window is blocked.

Categories
JavaScript Answers

How to disable an input type=text with JavaScript?

To disable an input type=text with JavaScript, we set the disabled or readOnly property.

For instance, we write

document.getElementById("foo").disabled = true;

or

document.getElementById("foo").readOnly = true;

to get the input with getElementById.

Then we disable the input by setting the disabled or readOnly property to true.

readOnly keeps the original input style when disabled.

disabled grays out the input when disabled.