Initialize jQuery & JavaScript for Video Elements Appended via Ajax

huangapple go评论89阅读模式
英文:

Initialize jQuery & JavaScript for Video Elements Appended via Ajax

问题

以下是翻译好的部分:

第1段:
我正在使用ajax将视频元素附加到网页上。在附加新视频后,我注意到一些JavaScript和jQuery没有初始化。

有3个代码片段需要一起使用。

  1. Ajax 调用的代码段
  2. 播放视频后取消静音的代码段
  3. 单击或触摸网页上任何位置后播放视频的代码段

第2段:
第1个代码段 以下代码段用于通过用户滚动页面后使用Ajax调用附加视频。

(接下来是第1个代码段的JavaScript代码,无需翻译)

第3段:
我希望附加的视频在单击或触摸网页后自动开始播放,并且在开始播放后取消静音。

我已经尝试了一些微小的调整,但在“通过ajax附加的视频”方面没有成功,但是当视频在初始加载期间已经在页面上时,这些代码可以完美地一起工作。

我需要这两个代码段在ajax之后都能正常工作。

第4段:
第2个代码段(用于取消带有autoplay属性的HTML视频的静音)

(接下来是第2个代码段的JavaScript代码,无需翻译)

第5段:
第3个代码段(用于通过单击或触摸手势在网页上播放HTML视频)

(接下来是第3个代码段的JavaScript代码,无需翻译)

第6段:
更新:

我在ajax调用成功后添加的附加功能对我来说非常有效。我现在唯一的问题在于上面列出的第3个代码段中,事件侦听器附加了一个布尔属性 { once: true },它只触发并调用一次函数。
如果我删除布尔属性,事件侦听器将在每次单击或触摸开始事件上触发并不断调用分配的函数。

我需要事件侦听器触发一次,并且仅在“每次ajax调用后”调用一次分配的函数。

英文:

I am using ajax to append videos elements to a webpage. After a new video is appended, I noticed that some JavaScript & jQuery are not initializing.

There are 3 code snippets that I need to work together.

1st. Code Snippet for Ajax call
2nd. Code Snippet That Unmutes Video after it is played
3rd. Code Snippet plays video after first initial click or touch gesture anywhere on webpage.

1st Code Snippet The following code snippet is used to Append Videos via Ajax Calls after the user scrolls the page.

var step = 1;
var loading = false;

$(window).scroll(function() {
    if ($(window).scrollTop() >= $(document).height() - $(window).height() - 1900) {
        if (loading === false) {
            loading = true;
            $.ajax({
                url: 'HTTPS://ENTER URL HERE.COM' + step,
                success: function(data) {
                    step++;
                    $('main2').append(data);
                    loading = false;
                },
                dataType: 'html'
            });
        }
    }
});

I want the appended video to automatically start playing after the webpage is clicked or touched and for the video to unmute after it starts playing.

I've tried minor tweaks but have not been successful at getting this to work with "videos appended via ajax", however these codes work perfectly together when the video is already on the page during the initial load.

I need both of the code snippets below to work after ajax.

2nd Code Snippet ( Used to unmute html video with autoplay attribute after it starts)

$("video").on('play', function() {
    $("video").prop('muted', false);
});

$("video").on('pause', function() {
    $("video").prop('muted', true);
});

$("video").on('ended', function() {
    $("video").prop('muted', true);
});

3rd Code Snippet ( Used to Play Html Videos on webpage with a click or touch gesture. )

Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
    get: function() {
        return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
    }
});

document.body.addEventListener("click", playVideoOnLowPower, {
    once: true
});
document.body.addEventListener("touchstart", playVideoOnLowPower, {
    once: true
});

function playVideoOnLowPower() {
    try {
        const videoElements = document.querySelectorAll("video");
        for (i = 0; i < videoElements.length; i++) {
            if (videoElements[i].playing) {
                // video is already playing so do nothing
                console.log('Playing');
            } else {
                // video is not playing so play video now
                videoElements[i].play();
                console.log('Not Playing');
            }
        }
    } catch (err) {
        console.log(err);
    }
}

UPDATE:

The additional function I added in the ajax call success workers like a charm for me. The only issue I have now is in the 3rd Code Snippet listed above, there is a Boolean attribute { once: true} attached to the event listener that only fires and calls the function once.
If I remove the Boolean attribute the event listener fires on each click or touch start event and continuously calls the function assigned.

I need the event listener to fire once and only call the assigned function once "after each ajax call"

答案1

得分: -1

如您所提到的,您的第一个代码片段正在附加新视频。所以,我假设main2只是一个拼写错误,实际上是一个元素的ID(也可以是类)。

由于您通过ajax绑定了视频,但在ajax成功时只是将视频绑定到$('main2'),而没有重新绑定事件。它不会自动具有您之前绑定的事件侦听器。所以,在ajax成功后,您需要重新绑定事件,如下所示:

Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
  get: function() {
    return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
  }
});

document.body.addEventListener("click", playVideoOnLowPower, {
  once: true
});
document.body.addEventListener("touchstart", playVideoOnLowPower, {
  once: true
});

function playVideoOnLowPower() {
  try {
    const videoElements = document.querySelectorAll("video");
    for (i = 0; i < videoElements.length; i++) {
      if (videoElements[i].playing) {
        // 视频已经在播放,所以什么都不做
        console.log('Playing');
      } else {
        // 视频没有在播放,所以现在播放视频
        videoElements[i].play();
        console.log('Not Playing');
      }
    }
  } catch (err) {
    console.log(err);
  }
}

$.ajax({
  url: 'https://dummyjson.com/http/200/mov_bbb.mp4',
  success: function(data) {
    if (data.status == 200) {
      var videoHtml = `<video width="400" controls>
                           <source src="https://www.w3schools.com/html/${data.message}" type="video/mp4">
                       </video>`;
    }
    $('#main2').append(videoHtml);
    videoEvents()
  }
});

function videoEvents() {
  $("video").on('play', function() {
    $(this).prop('muted', false);
  });

  $("video").on('pause', function() {
    $(this).prop('muted', true);
  });

  $("video").on('ended', function() {
    $(this).prop('muted', true);
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main2"></div>

这是您提供的代码的翻译部分。

英文:

As you mentioned your 1st Code Snippet is appending new video. So, I assume main2 just a typo error and is an ID of an element (can be class also).

Since, you bind the video via ajax, but in your ajax success you just bind the video to $(&#39;main2&#39;) and you haven't re-bind an event to it. It will not have the event listeners automatically that you bind previously. So, you need to rebind the event after your $(&#39;main2&#39;).append(data); in ajax success.

See the following example:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

Object.defineProperty(HTMLMediaElement.prototype, &#39;playing&#39;, {
get: function() {
return !!(this.currentTime &gt; 0 &amp;&amp; !this.paused &amp;&amp; !this.ended &amp;&amp; this.readyState &gt; 2);
}
});
document.body.addEventListener(&quot;click&quot;, playVideoOnLowPower, {
once: true
});
document.body.addEventListener(&quot;touchstart&quot;, playVideoOnLowPower, {
once: true
});
function playVideoOnLowPower() {
try {
const videoElements = document.querySelectorAll(&quot;video&quot;);
for (i = 0; i &lt; videoElements.length; i++) {
if (videoElements[i].playing) {
// video is already playing so do nothing
console.log(&#39;Playing&#39;);
} else {
// video is not playing so play video now
videoElements[i].play();
console.log(&#39;Not Playing&#39;);
}
}
} catch (err) {
console.log(err);
}
}
$.ajax({
url: &#39;https://dummyjson.com/http/200/mov_bbb.mp4&#39;,
success: function(data) {
if (data.status == 200) {
var videoHtml = `&lt;video width=&quot;400&quot; controls&gt;
&lt;source src=&quot;https://www.w3schools.com/html/${data.message}&quot; type=&quot;video/mp4&quot;&gt;
&lt;/video&gt;`;
}
$(&#39;#main2&#39;).append(videoHtml);
videoEvents()
}
});
function videoEvents() {
$(&quot;video&quot;).on(&#39;play&#39;, function() {
$(this).prop(&#39;muted&#39;, false);
});
$(&quot;video&quot;).on(&#39;pause&#39;, function() {
$(this).prop(&#39;muted&#39;, true);
});
$(&quot;video&quot;).on(&#39;ended&#39;, function() {
$(this).prop(&#39;muted&#39;, true);
});
}

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js&quot;&gt;&lt;/script&gt;
&lt;div id=&quot;main2&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年8月4日 21:54:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76836608.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定