Categories
JavaScript Answers

How to Watch for Mouse Wheel Events with JavaScript?

We can watch for mouse wheel events with JavaScript by listening to the wheel event.

For instance, we can write:

let supportOffset = window.pageYOffset !== undefined,  
  lastKnownPos = 0,  
  scrollDir,  
  currYPos;  
window.addEventListener('wheel', (e) => {  
  currYPos = supportOffset ? window.pageYOffset : document.body.scrollTop;  
  scrollDir = lastKnownPos > currYPos ? 'up' : 'down';  
  lastKnownPos = currYPos;  
  console.log(lastKnownPos, currYPos, scrollDir)  
});

to call window.addEventListener to watch for mouse wheel motions on the browser tab.

In the event handler callback, we set currYPos to window.pageYOffset or document.body.scrollTop to get the current position of the vertical scrollbar.

Then we check that against the lastKnownPos which is the previous value of currYPos .

If lastKnownPos > currYPos is true , then we’re scrolling up since the current position is smaller in pixels than lastKnownPos .

Otherwise, we’re scrolling down.

Now when we scroll up and down on a browser tab that has scrollable content, then we should see the values in the console log logged.

Categories
JavaScript Answers

How to Get Notified When an Element is Added to the Page with JavaScript?

The easiest way to watch for changes in the DOM is to use the MutationObserver API built into most browsers.

To use it, we can write:

const observerConfig = {
  attributes: true,
  childList: true,
  characterData: true
};

const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    console.log(mutation.type);
  });
});
observer.observe(document.body, observerConfig);

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

to watch for changes in the DOM with the MutationObserver constructor.

We pass in a callback with the mutations parameter to the constructor.

And we get the mutations that are applied to the DOM from there.

mutation.type has the type of mutation that’s done.

We should see 'chilidsList' and 'attributes' as values.

'childList‘ is the change in child nodes.

'attributes' is the change in attribute nodes.

We call observer with the root element to observer and the observerConfig to config how the mutation observer watches changes.

attributes set to true means we watch for attribute node changes.

childList set to true means we watch for child node changes.

Categories
JavaScript Answers

What’s the Difference Between the tagName and nodeName Property of a DOM Node in JavaScript?

In a DOM node object, we see the tagName and nodeName property when we inspect a DOM node object.

In this article, we’ll look at the difference between the tagName and nodeName property of a DOM node in JavaScript.

Difference Between the tagName and nodeName Property of a DOM Node in JavaScript

The tagName and nodeName property of a DOM node isn’t the same in most cases.

It’s only the same if the node is an element node.

For instance, if we have the following HTML:

<div class="a">a</div>

Then we can log the values of nodeName and tagName for each types of nodes by writing:

const div = document.querySelector('div')
console.log(div.nodeType)
console.log(div.nodeName)
console.log(div.tagName)

const attributeNode = div.getAttributeNode('class')
console.log(attributeNode.nodeType)
console.log(attributeNode.nodeName)
console.log(attributeNode.tagName)

const childNode = div.childNodes[0]
console.log(childNode.nodeType)
console.log(childNode.nodeName)
console.log(childNode.tagName)

div is an element node representing the div.

The console log logs the following values:

div.nodeType is 1.

div.nodeName and div.tagName are both 'DIV' .

attributeNode is an attribute node for the class attribute of the div.

attributeNode.nodeType is 2.

attributeNode.nodeName is 'class' and div.tagName is undefined .

childNode is a DOM node for the text content of the div.

childNode.nodeType is 3.

childNode.nodeName is '#text' since childNode is a text node and div.tagName is undefined .

Therefore, we can see that nodeName and tagName are only the same for elements.

Conclusion

For DOM elements, nodeName and tagName are both set to the tag name of the element as their values.

However, for non-element nodes, their values will be different.

Categories
JavaScript Answers

How to Determine if an HTML Element’s Content Overflows with JavaScript?

The HTML element’s scrollWidth property has the full width of the content in an element.

The HTML element’s scrollHeight property has the full height of the content in an element.

The HTML element’s clientWidth property has the width of the content in an element that’s displayed.

The HTML element’s clientHeight property has the height of the content in an element that’s displayed.

Therefore, we can compare them to see if any content overflows.

If scrollWidth is bigger than clientWidth or scrollHeight is bigger than clientHeight , then we know content is overflowing.

For instance, if we have the following HTML:

<div style='width: 100px; height: 100px; overflow: auto'>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer efficitur mauris at nisl accumsan suscipit. Aliquam tempus ultrices consectetur.
</div>

Then we can check if the div’s content is overflowing the div by writing:

const checkOverflow = (el) => {
  const isOverflowing = el.clientWidth < el.scrollWidth ||
    el.clientHeight < el.scrollHeight;
  return isOverflowing;
}

const div = document.querySelector('div')
console.log(checkOverflow(div))

We create the checkOverflow function that takes the el DOM element object as the parameter.

And return the comparison between clientWidth and scrollWidth and clientHeight and scrollHeight as we described.

The console log should log true since the text in the div overflows the height of the div, so el.clientHeight < el.scrollHeight returns true .

Categories
JavaScript Answers

How to Get the Number of Digits of a Number with JavaScript?

We can get the number of digits of a non-negative integer with the Number.prototype.toString method.

For instance, we can write:

const getLength = (number) => {  
  return number.toString().length;  
}  
console.log(getLength(12345))

to get the number of digits of 12345.

To do that, we create the getLength function that takes the number parameter.

And we return the length of the string form of number .

Therefore, the console log should log 5 since 12345 has 5 digits.

Get the Number of Digits of Decimal Numbers

We can’t use toString to get the number of digits of decimal numbers since it just returns the string form of the number, including all the decimal digits and other characters that comes with the number.

To get the number of digits of a decimal number, we can use math methods.

For instance, we can write:

const getLength = (number) => {  
  return Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1;  
}  
console.log(getLength(12345.67))

to get the number of digits of number by taking the log with 10 of it and then add 1 to get the number of digits of it.

We have to make sure number is converted to a positive number with Math.abs so we can take the log of it.

Next, we call Math.floor to take the floor of the log to get the number of digits excluding the leftmost digit.

Then we get the floor of the log and 0 with Math.max and add 1 to get the number of digits.

Therefore, the console log should log 5 since we use the log operation to discard the decimal digits.