Categories
JavaScript Answers

How to Detect When a Div’s Height Changes with JavaScript?

We can use the ResizeObserver to watch for an element’s resizing.

For instance, if we have the following div:

<div style='background-color: yellow'>
  hello world
</div>

Then we can use it by writing:

const div = document.querySelector('div')
const resizeObserver = new ResizeObserver(() => {
  console.log(div.clientHeight);
});

resizeObserver.observe(div);

setTimeout(() => {
  div.style.height = '200px'
}, 1000)

We get the div with the document.querySelector method.

Then we use the ResizeObserver by instantiating it with a callback.

In the callback, we log the clientHeight to log the height of the div.

Next, we call resizeObserver.observe to watch the div for size changes.

Then we call setTimeout with a callback to set the height of the div to '200px' .

So we should see that the console log will first log 18 and then log 200 since we change the size of the div to 200px high 1 second after setTimeout is called.

Categories
JavaScript Answers

How to Draw a Smooth Curve Through N Points Using JavaScript HTML5 Canvas?

We can use the quadraticCurveTo method that comes with the canvas context object to draw a curve through n points.

To use it, we can first write the following HTML:

<canvas width="200" height="200"></canvas>

Then we can use it by writing:

const points = [{
  x: 1,
  y: 1
}, {
  x: 20,
  y: 30
}, {
  x: 30,
  y: 40
}, {
  x: 40,
  y: 20
}, {
  x: 50,
  y: 60
}]

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext("2d")
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);

for (const point of points) {
  const xMid = (point.x + point.x) / 2;
  const yMid = (point.y + point.y) / 2;
  const cpX1 = (xMid + point.x) / 2;
  const cpX2 = (xMid + point.x) / 2;
  ctx.quadraticCurveTo(cpX1, point.y, xMid, yMid);
  ctx.quadraticCurveTo(cpX2, point.y, point.x, point.y);
}
ctx.stroke();

We have the points array that has the x and y coordinates of some points.

Then we get the canvas with document.querySelector .

Next, we call the getContext method to get the context object.

Then we call beginPath to start drawing.

And then we call moveTo to move to the first point.

Next, we call quadraticCurveTo to draw the curve from the first point that we calculated from the (cpX1 , point.y) to (xMid ,yMid).

Then we draw the curve from (cpX2 , point.y ) to (point.x , point.y ).

cpX1 and cpX2 are the center points of x and y for the line segment between one point and the next.

And finally, we call stroke to draw the line onto the screen.

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.