Click here to Skip to main content
15,920,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I work on a Social Media Page with Django/Python.

The feed.html diplays the Posts of Users. It is paginated, but I have an Infinite script where it automatically displays the next page, without needing to click to the next page. Users can upload Videos and Images, if you hover over the videos, it gets played.

The script:

JavaScript
var videos = document.querySelectorAll('video');
  for(var i=0; i<videos.length; i++)
     videos[i].addEventListener('play', function(){pauseAll(this)}, true);
  
  function pauseAll(elem){
    for(var i=0; i<videos.length; i++){
      //Is this the one we want to play?
      if(videos[i] == elem) continue;
      //Have we already played it && is it already paused?
      if(videos[i].played.length > 0 && !videos[i].paused){
      // Then pause it now
        videos[i].pause();
      }
    }
    }


prevents multiple videos from getting played, so if you hover over a video and it plays, but you hover over another video, the video before stops playing. That works well.

The Script for my infinite scroll is as follows:

JavaScript
var infinite = new Waypoint.Infinite({
    element: $('.infinite-container')[0],

    offset: 'bottom-in-view',

    onBeforePageLoad: function () {
      $('.loading').show();
    },
    onAfterPageLoad: function ($items) {
      $('.loading').hide();
    }
  });


But on the next Page, it doesn't apply, how do I fix that?

P.S.: Sorry for my bad English!

What I have tried:

I could not come up with a solution, so I tried nothing yet.
Posted
Updated 23-Aug-23 1:59am
v2

This code executes once, when the page loads:
JavaScript
var videos = document.querySelectorAll('video');
  for(var i=0; i<videos.length; i++)
     videos[i].addEventListener('play', function(){pauseAll(this)}, true);

If you want the play function to apply to the new elements in the page, you'll have to execute a selector against the new items that DO NOT have the event listener applied to them already.
 
Share this answer
 
The standard approach for handling events on new elements which don't exist when you assign the event handler is to use event delegation[^]. You wire up the handler to a parent element, and check the target to ensure that it's an element you want to process.
JavaScript
document.addEventListener('play', e => {
    if (e.target.tagName !== "VIDEO") { return; }
    pauseAll(e.target);
});
NB: You can't pass true for the useCapture parameter in this case:
Events that are bubbling upward through the tree will not trigger a listener designated to use capture.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900