开发者

how do I show/hide a youtube video using jquery without losing current state?

开发者 https://www.devze.com 2023-04-13 05:10 出处:网络
I\'m building a jquery ajax page that shows a list of youtube videos. I\'ve got two views on the page (list & video), which are built as LI elements, floated left, inside a UL element. I built it

I'm building a jquery ajax page that shows a list of youtube videos. I've got two views on the page (list & video), which are built as LI elements, floated left, inside a UL element. I built it this way because the transition between the views is done using a horizontal slide effect and I found that using the list allows the page to vertically resize correctly when the height of the views are different.

When a video is selected from the list view, I first see if it exists inside the DOM. If it does, I simply move it to the video view. If not, I create a new DIV and load the video into it. Once the video is moved into the video view, I slide the video view into place. When transitioning back to the list view, I move the video into a hidden "helper" div so I can keep it in the DOM.

The problem I'm having is that the youtube player gets reset whenever I move it to/from the video view. So even if a video has been completely loaded (and/or partially played), after moving it, the player resets back to 0 and has to completely reload. I'm using appendTo() to move it around.

Here's a simplified jsfiddle test:

http://jsfiddle.net/UPhek/3/

You'll see in my test code that I can show/hide a player and keep the state. But when I use .appendTo() to move the video DIV into a helper DIV, I lose the state of开发者_开发技巧 the player. I setup 3 tests... you can change the test by changing the whichTest global variable.


Try changing the video's visibility:

visiblity: hidden

http://jsfiddle.net/UPhek/4/

Tou can append this item to the "video view" side, if it hasn't been loaded already, and then change it's visiblity, preferably with a css class.


You could use this in conjunction with the YouTube API and stop/start videos with javascript:

http://code.google.com/apis/youtube/js_api_reference.html

var video = document.getElementById('video');
video.pauseVideo();

You'll probably have to switch from an iframe to an embed tag


Also, the SWFObject javascript library is always good when working with Flash


Appending an element isn't the same as moving it. I haven't dove into the jQuery source for this answer but I'm pretty sure that what happens when you take an element and append it somewhere else, it's merely copying the original node, destroying it, then inserting the copy into the new location. This will destroy the state of your video.

Hunter has the answer you're looking for. By hiding the video and using the youtube api to stop it, you're effectively accomplishing your goal.

0

精彩评论

暂无评论...
验证码 换一张
取 消