Categories
JavaScript Answers

How to Scroll Back to the Top of a Scrollable Div with JavaScript?

Sometimes, we want to scroll back to the top of a scrollable div with JavaScript.

In this article, we’ll look at how to scroll back to the top of a scrollable div with JavaScript.

Use the scroll Method

We can use the scroll method of an element to scroll a scrollable div back to the top.

For instance, if we have the following HTML:

<button>
  scroll to top
</button>
<div>

</div>

And the following CSS:

div {
  height: 300px;
  overflow-y: scroll;
}

Then we can add some content to the div and make the div scroll to the top when we click the button by writing:

const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

const btn = document.querySelector('button')
btn.addEventListener('click', () => {
  div.scroll({
    top: 0,
    behavior: 'smooth'
  });
});

We get the div with document.querySelector .

Then we add a for loop to add some content to the div with document.createElement to create a p element.

And we call div.appendChild to append the p elements to the div.

Next, we get the button with document.querySelector .

And then we call addEventListener on the button to add a click listener.

In the click listener, we call div.scroll with an object with top set to 0 to scroll to the top.

And behavior is set to 'smooth' to add smooth scrolling.

Now when we click on the scroll to top button, the scrollable div should go back to the top with smooth scrolling motion during scrolling.

Conclusion

We can use the scroll method to scroll a div to the top.

Categories
JavaScript Answers

How to Detect Clicks into an Iframe Using JavaScript?

Sometimes, we want to check if a user clicked into an iframe using JavaScript.

In this article, we’ll look at how to detect clicks into an iframe with JavaScript.

Focus on the Main Window Then Add a blur Event Listener to the Window

We can focus on the main window and then add a blur event listener to the window to see which element is activated after the blur event is emitted by the window.

For instance, if we have the following iframe:

<iframe src='https://example.com'>

</iframe>

Then we can focus on on the window and add a blur listener to it by writing:

focus();
const listener = window.addEventListener('blur', () => {
  if (document.activeElement === document.querySelector('iframe')) {
    console.log('clicked on iframe')
  }
  window.removeEventListener('blur', listener);
});

We call focus to focus on the main window.

Then we call window.addEventListener to add a blur event listener to the window.

In the event listener, we check if document.activeElement is the iframe to check if the iframe is the element that we focused on.

If it is, then we log a message.

Then we immediately remove the blur event listener after that.

Now when we click on the iframe, we should see the ‘clicked on iframe’ message logged.

Conclusion

We can detect clicks in an iframe with JavaScript by listening to the blur event on the window.

Categories
JavaScript Answers

How to Check if a Mouse Button is Kept Down After we Press it with JavaScript?

Sometimes, we want to check if a mouse button is still down after we press it with JavaScript.

In this article, we’ll look at how to check if a mouse button is kept down after we press it with JavaScript.

Listen to the mousedown and mouseup Events

We can listen to the mousedown and mouseup events to check if a mouse button is kept down after we press the mouse button.

For instance, we can write:

let mouseDown = 0;  
window.onmousedown = () => {  
  ++mouseDown;  
  if (mouseDown) {  
    console.log('mouse button down')  
  }  
}  
window.onmouseup = () => {  
  --mouseDown;  
  if (mouseDown) {  
    console.log('mouse button down')  
  }  
}

We set the window.onmousedown and window.onmouseup properties to functions that change the mouseDown count to listen for the mousedown and mouseup events on the whole tab.

If the mousedown event is emitted, we increment mouseDown .

If the mouseup event is emitted, we decrement mouseDown .

mousedown event is emitted when we press the mouse button down.

And mouseup is emitted when we stop pressing the mouse button.

Therefore, if mouseDown is bigger than 0, the mouse button is kept down.

Conclusion

We can check if a mouse button is kept down by listening to the mousedown and mouseup events and mount how many times the mouse button is pressed down or lifted up.

Categories
JavaScript Answers

How to Force a Page Scroll Position to the Top of the Page on Page Refresh with JavaScript?

By default, the scroll position of the page is kept after we refresh the page.

Sometimes, we want to force a page to scroll to the top when we refresh it.

In this article, we’ll look at how to force a page to scroll to the top when we refresh the page.

Listen to the beforeunload Event and use the scrollTo Method

To run code when the page refreshes, we can listen to the beforeunload event.

Then in the beforeunload event handler, we call the scrollTo method to scroll to the top of the page when it refreshes.

For instance, if we have the following HTML:

<div>

</div>

Then we can write:

const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

window.onbeforeunload = () => {
  window.scrollTo(0, 0);
}

to add some elements into the div with the document.createElement method and the appenndChild method.

Then we set the window.onbeforeunload property to a function that calls window.scrollTo with 0 and 0 to scroll to the top.

Now when we refresh the page, we scroll to the top of the page.

Conclusion

We can force a page to scroll to the top when we refresh the page by listening to the beforeunload event with a listener and call scrollTo ibn the event listener.

Categories
JavaScript Answers

How to Check a Selected Image’s Width and Height with JavaScript?

Sometimes, we want to check a selected image’s width and height selected with a file input with JavaScript.

In this article, we’ll look at how to check a selected image’s width and height with JavaScript.

Use the FileReader and Image Constructors

We can use the FileReader constructor to create an object to read the file.

Then we can use the Image constructor to create an image with the read file as the content.

For instance, if we have the following file input:

<input type='file'>

Then we can read the file into an image by writing:

const fileUpload = document.querySelector('input')
const reader = new FileReader();
fileUpload.addEventListener('change', () => {
  reader.readAsDataURL(fileUpload.files[0]);
  reader.onload = (e) => {
    const image = new Image();
    image.src = e.target.result;
    image.onload = () => {
      const {
        height,
        width
      } = image;
      if (height > 100 || width > 100) {
        alert("Height and Width must not exceed 100px.");
        return false;
      }
      alert("Uploaded image has valid Height and Width.");
      return true;
    };
  };

})

We select the file input with document.querySelector .

Then we create a FileReader instance.

And then we add a change event listener to the file input with addEventListener .

In the event listener, we call reader.readAsDataURL to read the file.

The file is stored in fileUpload.files object.

Index 0 has the first file selected.

Then we set the reader.onload property to a function that creates the Image instance.

We set image.src to e.target.result to set the read file as the content of the img element created.

Then we set the image.onload property to a function that gets the width and height of the image.

And we check the width and height to be what we want with the if statements.

Now if we select an image file, we should see the alert boxes pop up depending on the size of the image.

Conclusion

We can use the FileReader constructor to create an object to read the file.

Then we can use the Image constructor to create an image with the read file as the content to check the width and height of an image file selected.