Categories
JavaScript Answers

How to Listen for Text Highlight in an HTML Element with JavaScript?

To listen for text highlight in an HTML element with JavaScript, we can listen to the selectionchange event.

For instance, if we have the following div:

<div>  
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed dapibus aliquam iaculis. Pellentesque interdum elit sapien, quis interdum enim laoreet sed. Mauris varius magna ac dapibus molestie. Sed porttitor sapien eget ipsum aliquet, lacinia venenatis lacus finibus. Phasellus in nibh mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed placerat tristique augue, id lacinia massa iaculis eu. Donec sed vestibulum odio. Fusce sit amet congue odio, eu consequat neque. Sed sed mauris id sem malesuada blandit eu at quam.  
</div>

Then we can write:

document.addEventListener("selectionchange", event => {  
  const selection = document.getSelection ? document.getSelection().toString() : document.selection.createRange().toString();  
  console.log(selection);  
})

to listen to the selectionchange event on document , which means we pick up all text selection changes on the page.

In the event handler, we call getSelection to get the text selection if it exists.

Otherwise, we call document.selection.createRange().toString() to get the text selection.

Categories
JavaScript Answers

How to Detect Scroll End with JavaScript?

To detect scroll end with JavaScript, we can listen to the scroll event.

Then in the event listener, we check if offsetHeight + scrollTop is bigger than or equal to scrollHeight .

For instance, if we have the following div:

<div style='overflow-y: auto; height: 100px'>  
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed dapibus aliquam iaculis. Pellentesque interdum elit sapien, quis interdum enim laoreet sed. Mauris varius magna ac dapibus molestie. Sed porttitor sapien eget ipsum aliquet, lacinia venenatis lacus finibus. Phasellus in nibh mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed placerat tristique augue, id lacinia massa iaculis eu. Donec sed vestibulum odio. Fusce sit amet congue odio, eu consequat neque. Sed sed mauris id sem malesuada blandit eu at quam.  
</div>

Then we can check fi we scrolled to the bottom of the div by writing:

const myDiv = document.querySelector('div')  
myDiv.addEventListener('scroll', () => {  
  if (myDiv.offsetHeight + myDiv.scrollTop >= myDiv.scrollHeight) {  
    console.log('scrolled to bottom')  
  }  
})

We get the div with document.querySelector .

Then we call addEventListener with 'scroll' to add a scroll event listener to it.

Then in the event listener function, we have:

myDiv.offsetHeight + myDiv.scrollTop >= myDiv.scrollHeight

to check check if offsetHeight + scrollTop of the div is bigger than or equal to scrollHeight of it.

If it’s true , then we see the 'scrolled to bottom' string logged.

Categories
JavaScript Answers

How to Find the First Scrollable Parent Element with JavaScript?

To find the first scrollable parent element with JavaScript, we can recursively search for the parent that has scrollHeight bigger than clientHeight .

For instance, we can write the following HTML:

<div class="outer">
  <div class="inner">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed dapibus aliquam iaculis. Pellentesque interdum elit sapien, quis interdum enim laoreet sed. Mauris varius magna ac dapibus molestie. Sed porttitor sapien eget ipsum aliquet, lacinia venenatis lacus finibus. Phasellus in nibh mauris. Interdum et malesuada fames ac ante ipsum primis in faucibus. Sed placerat tristique augue, id lacinia massa iaculis eu. Donec sed vestibulum odio. Fusce sit amet congue odio, eu consequat neque. Sed sed mauris id sem malesuada blandit eu at quam.
    <div class="content">
      <span id='start'>Scroll me into view</span>
    </div>
  </div>
</div>

Then we write:

const getScrollParent = (node) => {
  if (node === null) {
    return null;
  }

  if (node.scrollHeight > node.clientHeight) {
    return node;
  } else {
    return getScrollParent(node.parentNode);
  }
}

const span = document.querySelector('span')
const scrollable = getScrollParent(span)
console.log(scrollable)

to add the getScrollParent function that takes the HTML DOM node .

Then it checks if node.scrollHeight is bigger than node.clientHeight if the node isn’t null .

If it is, then it’s returned.

Otherwise, it calls getScrollParent with the node.parentNode to check the node up the DOM tree.

Then we call the function by getting the span with document.querySelector .

And then we call getScrollParent with it.

Therefore, we see that scrollable is the html element.

Categories
JavaScript Answers

How to Properly Unload or Destroy an HTML Element with JavaScript?

To properly unload or destroy an HTML element with JavaScript, we can pause the video, then remove the src attribute from the video element, and then call load again to reload the video element.

For instance, if we have the following HTML video element:

<video src='https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4' controls></video>

We can write:

const videoElement = document.querySelector('video');
videoElement.pause();
videoElement.removeAttribute('src');
videoElement.load();

to get the video element with document.querySelector .

Then we call pause to pause the video.

Next, we call removeAttribute with 'src' to remove the src attribute.

And then we call load to reload the video element.

Conclusion

To properly unload or destroy an HTML element with JavaScript, we can pause the video, then remove the src attribute from the video element, and then call load again to reload the video element.

Categories
JavaScript Answers

How to Disable Related Videos with the YouTube JavaScript API?

To disable related videos with the Youtube JavaScript API, we can set the rel property in the playerVars property to 0.

For instance, we can add the following HTML element for the video player:

<div id="player"></div>

Then we can write:

const tag = document.createElement("script");
tag.id = "iframe-demo";
tag.src = "https://www.youtube.com/iframe_api";
const [firstScriptTag] = document.getElementsByTagName("script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

window.onYouTubeIframeAPIReady = () => {  
  const player = new window.YT.Player("player", {    
    width: 200,    
    height: 100,    
    videoId: "M7lc1UVf-VE",    
    playerVars: {      
      rel: 0,      
      showinfo: 0,      
      ecver: 2   
    }  
  });
};

to add the YouTube script tag with:

const tag = document.createElement("script");
tag.id = "iframe-demo";
tag.src = "https://www.youtube.com/iframe_api";
const [firstScriptTag] = document.getElementsByTagName("script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

Then we set the window.onYouTubeIframeAPIReady to a function that invokes the window.YT.Player constructor with the ID of the element for the player as the first argument.

The 2nd argument is an object with various options like the video width and height and video ID. The playerVars.rel property is set to 0 so that related videos will not be shown.