SublimeVideo JavaScript - javascript

I've been using SublimeVideo, and I've done so much with it already for the site I'm working on.
I've got 15-20 videos that I'm successfully using via SublimeVideo on a site in the basic way, by having a link on the page the user clicks on, and when clicked, the video opens in the SublimeVideo lightbox and starts playing.
But now, I'm needing to create "shorter URLs" for these videos that can be sent out in print publications and emails, and where the user is taken to the website to view, not just the video file.
Ideally, I was hoping to just use the id/data-uid with a hashtag in a single-page url and have the chosen video to automatically launch'n'play within the lightbox. That seems to be impossible (?).
I could settle with having a single page with the video tags hidden and have the hashtag unhide it and play it when in the URL. If none of this can work in a slick way, maybe I'll just go old-school and make a page for each video and just embed it in the page..
Anyway, after scouring all the documentation pages, their forums, and searching the web, I've only found a couple of options - neither of which have actually worked. I'll paste them below:
First, here's an example of the HTML I'm using for all the videos:
<p class="">video1 text link on page</p>
<video id="video1" data-uid="video1" title="video1 description" poster="/assets/images/video1.jpg" width="1084" height="574" style="display:none" data-autoresize="fit" preload="none">
<source src="/assets/videos/video1.mp4" />
</video>
That, by itself, works great! I don't want to change that. When the text link is clicked, the lightbox opens and the video plays perfectly.
So, let's say the page that holds the 15-20 videos with the above code for them is at:
http://example.com/resources/index.php
I thought I could simply make that URL for the first video:
http://example.com/resources/index.php#video1
...or even better...
http://example.com/resources#video1
...and follow suit for all the other video IDs.
And to get that to work, I've tried:
<script type="text/javascript">
sublimevideo.ready(function()
{
if (window.location.hash == '#video1') {
sublime('video1').play();
} else
if (window.location.hash == '#video2') {
sublime('video2').play();
} else
if (window.location.hash == '#video3') {
sublime('video3').play();
}
});
</script>
...that doesn't work. For some reason it works with whatever the first video is on the page, but by "work" I mean, it unhides it and makes it playable, not open in the lightbox and auto play.
So then I found code in the sharing documentation area like this:
<script type="text/javascript">
var hashtag = "#video1";
var hashtag = "#video2";
var hashtag = "#video3";
if (document.location.hash == hashtag) {
showTheVideo(hashtag);
}
function showTheVideo(hashtag) {
}
</script>
...but that doesn't work either.
Could somebody that does know JavaScript please spell it out for me?

I'll put the code that fixed the issue for me here in hopes it helps somebody else someday that may search and find it.
By putting the below code in the head of the page, under the...
<script type="text/javascript" src="//cdn.sublimevideo.net/js/UniqueIDprovidedInYourAccountGoesHere.js"></script>
...library (which is the random characters/numbers .js that SublimeVideo gives you in your account area), I was able to finally get the above detailed problem to work (YAY!!!).
So, using the same example as above, this URL now works as I needed (by not only taking you to the resources page, but also by launching the particular video in its lightbox).
http://example.com/resources.php#video=interview2
...and by putting:
RewriteRule ^resources$ resources.php [L]
...in the .htaccess file in the same dir, I was able to make it even easier for the user:
http://example.com/resources#video=interview2
As I understand it, the below JavaScript addition finds the hash, then looks for the "video=", then takes whatever is after that, and if it finds a matching "id" in an "a" tag, then it tells it to do it's SublimeVideo thing by launching that video in the lightbox. Brilliant!
<script type="text/javascript">
$(document).ready(function () {
var lochash = location.hash.substr(1);
var mylocation = lochash.substr(lochash.indexOf('video='))
.split('&')[0]
.split('=')[1];
sublime.ready(function () {
var lightbox = sublime.lightbox(mylocation);
lightbox.open();
});
});
</script>
Here's the HTML part (for reference):
<p class="">video2 text link on page that i left as reference for the user in case they close the video that was launched from the publication</p>
<video id="video2" data-uid="video2" title="video2 description" poster="/assets/images/interview2.jpg" width="1084" height="574" style="display:none" data-autoresize="fit" preload="none">
<source src="/assets/videos/interview2.mp4" />
</video>
Also note: I found out through trial and error that the name of the video in the URL, after the "#video=" must be the same as the "ID" in the "A" tag, not the "video" tag! So, you'll notice that the "id=" is (and needs to be) different between the two. The "id=" in the "video" tag is instead the same as the "href=".

Related

Need to disable Javascript within an iFrame

I'm building a portfolio site; it's a one pager with a lightbox functionality. So, basically I am showing HTML5 ads I have built, which I am embedding in an iFrame. These ads have audio, so when I close out of the lightbox the audio continues to play. Now I have tried different methods but have been unsuccessful. I have tested one method which worked, where I removed the src of the iFrame (ONE iFrame which I assigned an ID). Like so:
**HTML:**
<iframe id="test" class="iframe-src" src="media/rogue-nation/300x250-progressive-post/index.html" width="300" height="250" style="border:none"></iframe>
**JavaScript:**
var test;
var lightbox;
test = document.getElementById('test');
lightbox = document.getElementById('lightbox');
lightbox.addEventListener("click", closeLightbox, false);
function closeLightbox() {
...
test.src = "none";
}
So...my questions are:
What is the "best" way to apply this method to each iFrame depending on which one was interacted with (tried, getElementsByClassName but was unsuccessful)
Is there a way to disable the scripts within an iFrame so I don't have to use this method, as I am not so crazy about it
Also, please don't post jQuery solutions or advise me to use jQuery, as it will not be helpful because I am writing plain JavaScript
Thanks in advance!
If your iframe content lives on the same domain it is easy. You could do something like this when your lightbox closes:
function closeLightbox() {
// get the iframe which is playing audio
var iframe = document.getElementById('iframe');
// make sure you can reference the audio element on the iframe
// e.g. with an id.
var sound = iframe.contentWindow.document.getElementById('sound');
sound.pause();
sound.currentTime = 0;
// then close the lightbox with some other code
// ...
}
JSBin Demo

Security Error while trying to play a sound in Firefox add-on?

I'm new to Firefox add-on development, and I have a problem while trying to play a sound in my add-on.
It's an add-on for timekeeping. Users can configure meetings settings (duration, participants... etc) through a Panel. There is a toolbar. It contains several buttons (Start, Next, Stop, Add Participant) and a Frame (to display how many participants haven't speaked yet). I change the document.border.style property from "green" to "red" as timers countdown.
This works fine. But I was asked to make my add-on play a sound when the document.border.style property turns "orange" and then "red" and I can't make it works.
I have tried several things :
1-Adding a property/attribute (I don't know which term is the right to use in that context, maybe both, anyway) to my TimeKeeper variable for each sound that has to be played. Meaning in my code :
orangeBorderStyle: new Audio(relativePathToMyMp3orWAVFile),
redBorderStyle: new Audio(relativePathToMyMp3orWAVFile),
and then calling their play() method in the countdown() method. But it didn't work.
2-Currently, I'm trying to play the sounds from HTML5 audio tags I added to the frame.url HTML file. But it doesn't work either.
The HTML file looks like this :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Frame</title>
</head>
<body>
<script type="text/javascript" src="../javascript/Frame_script.js"></script>
Speakers Left : <input id="speakers" size="4" value="" disabled />
<audio id="orangeSound" src="Audio/orangeBorderSoundTest.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<audio id="redSound" src="Audio/redBorderSoundTest.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>
In Frame_script.js I have :
window.addEventListener("message", reactToMessages, false);
var orangeBorderSound=document.getElementById("orangeSound");
var redBorderSound=document.getElementById("redSound");
//console.log(orangeBorderSound);
function reactToMessages(e){
if(isNaN(e.data)==false){
displaySpeakersLeft(e);
}
if(e.data=="orangeBorderSound")
{
document.getElementById("orangeSound").play();
//console.log("Je joue le son Orange.");
} else if(e.data=="redBorderSound")
{
document.getElementById("redSound").play();
//console.log("Je joue le son Rouge.");
}
}
function displaySpeakersLeft(e){
document.getElementById("speakers").value=e.data;
}
and in Timers.js I have the following calls :
Frame.get().postMessage("orangeBorderSound", Frame.get().url);
Frame.get().postMessage("redBorderSound", Frame.get().url);
Both calls trigger the right code (when the console.log() are commented out, they are displayed correctly) but there is no sound in the end.
Please, note that the value of the input tag with ID "speakers" is correctly displayed in my add-on so it seems that the document.getElementById() methods returns the right thing, and that it is the right way to do things with an input tag. Meaning, the paths are the right ones. I can't see why it would be different with audio tags.
So here comes my question : I now see the error "Security Error: Content at moz-nullprincipal:... may not load or link to resource..." (the resource path given seems to be the right one for each audio file) in the Error Console.
Is this really a security issue ? Or would I have little to change to make my code works ? What would you do ?
Any explanation or suggestion would be appreciated. I really don't see what's wrong with what I've done. Why would it cause security problems ?
Please, note that I've tried to use the audio tags method in a new add-on with just a Play button in the Panel and nothing else, but this time with the audio tags in the Panel contentURL HTML file, calling the play() method in the contentScriptFile and it worked.
No security error this time.
But I suppose I can't accept such a solution in my timekeeping add-on since I need to synchronize the call of the play() method with the change of the border style and that there is no Play button this time. It does not correspond to what I want to obtain. It was just for testing purpose.
Timers.js which is in my lib directory cannot interact with the Panel contentScriptFile which is in the data directory, so it couldn't be a solution even if the sounds were correctly loaded and ready to be played.
What do I get wrong ?

Playing music that is linked and not loaded?

This is probably an odd question, but for fun i recreated the Spotify layout to their app in codepen, now I want to add some functionality, is there a way I can get music to play using JS or jQuery?
My first thought was to embed the video and hide it behind the play button, but that doesn't quite work for me.
Is there a way I can set a var where I set it = to a url, then use an onclick or toggle command to play the url?
The only way I could think about going this would be:
var expirePrettyLow = 'url:www.fake.com'
$('#play').toggle(
function(){
//play youtube link?
);
I hope this makes sense, is there an api I can call to just get the mp3s? I don't want to upload them since it's just linking, not trying to make a product out of this, just to add to portfolio.
For reference here is my codepen link.
Thanks for whatever advice/direction you can give me!
EDIT: To clarify, by 'linked' and not 'loaded'
I would like to accomplish this by linking to a url (ie: href="") as opposed to saving it in my directory and loading it through a filepath (ie: music/tracks/expire-prettylow.mp3)
User a blank audio tag and set the play button's onClick to "var newSrc = newSource.com/song.mp3; playTrack()", and have the playTrack() function load and play the song. Here's an example of a code that changes the source of the audio element then plays the new source.
<script>
function playTrack(){
var music = document.getElementById("myAudio");
music.src = newSrc;
music.load();
music.play();
}
</script>
<audio id="myAudio" src="">
Audio tag not supported
</audio>
Click a song to play it:
<ul>
<li onClick="newSrc = 'http://fidelak.free.fr/reprises/The%20Doors%20-%20People%20are%20Strange.mp3'; playTrack()">People are Strange</li>
<li onClick="newSrc = 'http://mp3light.net/assets/songs/14000-14999/14781-december-1963-oh-what-a-night-four-seasons--1411568407.mp3'; playTrack()">Oh What a Night</li>
</ul>
Set the src with JavScript, music.load(), then music.play()

How to pause a YouTube player when hiding the iframe?

I have a hidden div containing a YouTube video in an <iframe>. When the user clicks on a link, this div becomes visible, the user should then be able to play the video.
When the user closes the panel, the video should stop playback. How can I achieve this?
Code:
<!-- link to open popupVid -->
<p>Click here to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>
<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
<iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40" frameborder="0" allowfullscreen></iframe>
<br /><br />
<a href="javascript:;" onClick="document.getElementById('popupVid').style.display='none';">
close
</a>
</div><!--end of popupVid -->
The easiest way to implement this behaviour is by calling the pauseVideo and playVideo methods, when necessary. Inspired by the result of my previous answer, I have written a pluginless function to achieve the desired behaviour.
The only adjustments:
I have added a function, toggleVideo
I have added ?enablejsapi=1 to YouTube's URL, to enable the feature
Demo: http://jsfiddle.net/ZcMkt/
Code:
<script>
function toggleVideo(state) {
// if state == 'hide', hide. Else: show video
var div = document.getElementById("popupVid");
var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
div.style.display = state == 'hide' ? 'none' : '';
func = state == 'hide' ? 'pauseVideo' : 'playVideo';
iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}
</script>
<p>Click here to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>
<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
<iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<br /><br />
close
Here's a jQuery take on RobW's answer for use hiding /pausing an iframe in a modal window:
function toggleVideo(state) {
if(state == 'hide'){
$('#video-div').modal('hide');
document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
else {
$('#video-div').modal('show');
document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
}
}
The html elements referred to are the modal div itself (#video-div) calling the show / hide methods, and the iframe (#video-iframe) which has the video url as is src="" and has the suffix enablejsapi=1? which enables programmatic control of the player (ex. .
For more on the html see RobW's answer.
Here is a simple jQuery snippet to pause all videos on the page based off of RobW's and DrewT's answers:
jQuery("iframe").each(function() {
jQuery(this)[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*')
});
Hey an easy way is to simply set the src of the video to nothing, so that the video will desapear while it's hidden an then set the src back to the video you want when you click on the link that opens the video.. to do that simply set an id to the youtube iframe and call the src function using that id like this:
<script type="text/javascript">
function deleteVideo()
{
document.getElementById('VideoPlayer').src='';
}
function LoadVideo()
{
document.getElementById('VideoPlayer').src='http://www.youtube.com/embed/WHAT,EVER,YOUTUBE,VIDEO,YOU,WHANT';
}
</script>
<body>
<p onclick="LoadVideo()">LOAD VIDEO</P>
<p onclick="deleteVideo()">CLOSE</P>
<iframe id="VideoPlayer" width="853" height="480" src="http://www.youtube.com/WHAT,EVER,YOUTUBE,VIDEO,YOU,HAVE" frameborder="0" allowfullscreen></iframe>
</boby>
Since you need to set ?enablejsapi=true in the src of the iframe before you can use the playVideo / pauseVideo commands mentioned in other answers, it might be useful to add this programmatically via Javascript (especially if, eg. you want this behaviour to apply to videos embedded by other users who have just cut and paste a YouTube embed code). In that case, something like this might be useful:
function initVideos() {
// Find all video iframes on the page:
var iframes = $(".video").find("iframe");
// For each of them:
for (var i = 0; i < iframes.length; i++) {
// If "enablejsapi" is not set on the iframe's src, set it:
if (iframes[i].src.indexOf("enablejsapi") === -1) {
// ...check whether there is already a query string or not:
// (ie. whether to prefix "enablejsapi" with a "?" or an "&")
var prefix = (iframes[i].src.indexOf("?") === -1) ? "?" : "&";
iframes[i].src += prefix + "enablejsapi=true";
}
}
}
...if you call this on document.ready then all iframes in a div with a class of "video" will have enablejsapi=true added to their source, which allows the playVideo / pauseVideo commands to work on them.
(nb. this example uses jQuery for that one line that sets var iframes, but the general approach should work just as well with pure Javascript if you're not using jQuery).
I wanted to share a solution I came up with using jQuery that works if you have multiple YouTube videos embedded on a single page. In my case, I have defined a modal popup for each video as follows:
<div id="videoModalXX">
...
<button onclick="stopVideo(videoID);" type="button" class="close"></button>
...
<iframe width="90%" height="400" src="//www.youtube-nocookie.com/embed/video_id?rel=0&enablejsapi=1&version=3" frameborder="0" allowfullscreen></iframe>
...
</div>
In this case, videoModalXX represents a unique id for the video. Then, the following function stops the video:
function stopVideo(id)
{
$("#videoModal" + id + " iframe")[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
I like this approach because it keeps the video paused where you left off in case you want to go back and continue watching later. It works well for me because it's looking for the iframe inside of the video modal with a specific id. No special YouTube element ID is required. Hopefully, someone will find this useful as well.
You can stop the video by calling the stopVideo() method on the YouTube player instance before hiding the div e.g.
player.stopVideo()
For more details see here: http://code.google.com/apis/youtube/js_api_reference.html#Playback_controls
RobW's way worked great for me. For people using jQuery here's a simplified version that I ended up using:
var iframe = $(video_player_div).find('iframe');
var src = $(iframe).attr('src');
$(iframe).attr('src', '').attr('src', src);
In this example "video_player" is a parent div containing the iframe.
just remove src of iframe
$('button.close').click(function(){
$('iframe').attr('src','');;
});
Rob W answer helped me figure out how to pause a video over iframe when a slider is hidden. Yet, I needed some modifications before I could get it to work. Here is snippet of my html:
<div class="flexslider" style="height: 330px;">
<ul class="slides">
<li class="post-64"><img src="http://localhost/.../Banner_image.jpg"></li>
<li class="post-65><img src="http://localhost/..../banner_image_2.jpg "></li>
<li class="post-67 ">
<div class="fluid-width-video-wrapper ">
<iframe frameborder="0 " allowfullscreen=" " src="//www.youtube.com/embed/video-ID?enablejsapi=1 " id="fitvid831673 "></iframe>
</div>
</li>
</ul>
</div>
Observe that this works on localhosts and also as Rob W mentioned "enablejsapi=1" was added to the end of the video URL.
Following is my JS file:
jQuery(document).ready(function($){
jQuery(".flexslider").click(function (e) {
setTimeout(checkiframe, 1000); //Checking the DOM if iframe is hidden. Timer is used to wait for 1 second before checking the DOM if its updated
});
});
function checkiframe(){
var iframe_flag =jQuery("iframe").is(":visible"); //Flagging if iFrame is Visible
console.log(iframe_flag);
var tooglePlay=0;
if (iframe_flag) { //If Visible then AutoPlaying the Video
tooglePlay=1;
setTimeout(toogleVideo, 1000); //Also using timeout here
}
if (!iframe_flag) {
tooglePlay =0;
setTimeout(toogleVideo('hide'), 1000);
}
}
function toogleVideo(state) {
var div = document.getElementsByTagName("iframe")[0].contentWindow;
func = state == 'hide' ? 'pauseVideo' : 'playVideo';
div.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
};
Also, as a simpler example, check this out on JSFiddle
This approach requires jQuery. First, select your iframe:
var yourIframe = $('iframe#yourId');
//yourId or something to select your iframe.
Now you select button play/pause of this iframe and click it
$('button.ytp-play-button.ytp-button', yourIframe).click();
I hope it will help you.
RobW's answers here and elsewhere were very helpful, but I found my needs to be much simpler. I've answered this elsewhere, but perhaps it will be useful here also.
I have a method where I form an HTML string to be loaded in a UIWebView:
NSString *urlString = [NSString stringWithFormat:#"https://www.youtube.com/embed/%#",videoID];
preparedHTML = [NSString stringWithFormat:#"<html><body style='background:none; text-align:center;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>var player; function onYouTubeIframeAPIReady(){player=new YT.Player('player')}</script><iframe id='player' class='youtube-player' type='text/html' width='%f' height='%f' src='%#?rel=0&showinfo=0&enablejsapi=1' style='text-align:center; border: 6px solid; border-radius:5px; background-color:transparent;' rel=nofollow allowfullscreen></iframe></body></html>", 628.0f, 352.0f, urlString];
You can ignore the styling stuff in the preparedHTML string. The important aspects are:
Using the API to create the "YT.player" object. At one point, I only had the video in the iFrame tag and that prevented me from referencing the "player" object later with JS.
I've seen a few examples on the web where the first script tag (the one with the iframe_api src tag) is omitted, but I definitely needed that to get this working.
Creating the "player" variable at the beginning of the API script. I have also seen some examples that have omitted that line.
Adding an id tag to the iFrame to be referenced in the API script. I almost forgot that part.
Adding "enablejsapi=1" to the end of the iFrame src tag. That hung me up for a while, as I initially had it as an attribute of the iFrame tag, which does not work/did not work for me.
When I need to pause the video, I just run this:
[webView stringByEvaluatingJavaScriptFromString:#"player.pauseVideo();"];
Hope that helps!
This is working fine to me with YT player
createPlayer(): void {
return new window['YT'].Player(this.youtube.playerId, {
height: this.youtube.playerHeight,
width: this.youtube.playerWidth,
playerVars: {
rel: 0,
showinfo: 0
}
});
}
this.youtube.player.pauseVideo();
A more concise, elegant, and secure answer: add “?enablejsapi=1” to the end of the video URL, then construct and stringify an ordinary object representing the pause command:
const YouTube_pause_video_command_JSON = JSON.stringify(Object.create(null, {
"event": {
"value": "command",
"enumerable": true
},
"func": {
"value": "pauseVideo",
"enumerable": true
}
}));
Use the Window.postMessage method to send the resulting JSON string to the embedded video document:
// |iframe_element| is defined elsewhere.
const video_URL = iframe_element.getAttributeNS(null, "src");
iframe_element.contentWindow.postMessage(YouTube_pause_video_command_JSON, video_URL);
Make sure you specify the video URL for the Window.postMessage method’s targetOrigin argument to ensure that your messages won’t be sent to any unintended recipient.

Toggling between instances of NiftyPlayer on a page - won't stop playing when hidden on IE

I've got a page with links to MP3s, when the link is clicked I use javascript to show a small Flash player (NiftyPlayer) under the link. When a different link is clicked, the old player is hidden and the new player is revealed.
The player auto-starts when the element is shown, and auto-stops when hidden - in Firefox.
In IE it will only auto-start and NOT auto-stop. This is what I would like to solve.
This is an example HTML with link and player
Misunderstood What You Said
<div id="player662431" class="playerhide"><embed src="http://www.example.com/shop/flash/player.swf?file=/mp3/Beat The Radar - Misunderstood What You Said.mp3&as=1" quality="high" bgcolor="#000000" width="161" height="13" name="niftyPlayer662431" align="" type="application/x-shockwave-flash" swLiveConnect="true" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>
Here is the javascript (I've got jQuery installed to let me hide all the open players on this page apart from the new one)
function toggle_visibility(id) {
$('.playerhide').hide();
var e = document.getElementById(id);
e.style.display = 'block';
}
I think what I need to do is start the player manually with javascript (rather than using the autostart as=1 function in the URL string)
There is some javascript that comes with NiftyPlayer to allow this EG
niftyplayer('niftyPlayer1').play()
there is also a stop method.
I need some help with javascript - how do I add this call to play into my toggle_visibility function (it has the same unique ID number added to the name of the player as the ID of the div that's being shown, but I don't know how to pull this ID number out of one thing and put it in another)
I also would like to be able to do
niftyplayer('niftyPlayer1').stop()
to stop the audio of the previously running player. Is it possible to store the current ID number somewhere and call it back when needed?
Thanks for the help, i'm a PHP programmer who needs some support with Javascript - I know what I want to achieve, just don't know the commands to do it!
Thanks
If you assigned each niftyplayer object a classname, f.x. ".players", then you could loop through each player, like this:
function toggle_visibility(id) {
$(".players").each(function(){
playerId = $(this).attr('id');
if(niftyplayer(playerId).getState() == 'playing') {
//Stop the currently playing player
niftyplayer(playerId).stop();
//Hide the div that was playing
$("#" + playerId).hide();
}
});
//Start the new player
niftyplayer(id).play();
$("#" + id).show();
}
So what this actually does, is it loops through all the players on the website. It checks if the status of each player is equal to "playing", if it is, then it stops it and hides the div tags. Then it starts the new player and shows that div tag.
I think this does it. Try it out.
I have a much better solution after I noticed a very nasty bug / 'feature' when using Internet Explorer in conjunction.
I had noticed that in IE the pages were taking a very long time to load when I had a lot of hidden Nifty Players, I looked closer using Fiddler and found that each instance of NiftyPlayer was preloading the MP3 in full, rather than loading on demand as with Firefox and Chrome etc.
This meant that a page with 100 items (each item having up to 4 MP3s) took several minutes to load at times with obvious data transfer implications.
My solution which is rather simpler (but maybe clunkier) than Indyber's is to just use
function toggle_visibility(id,mp3location) {
// hide all players
$(".playerarea").html('');
// show clicked player
$('#' + id).html('<embed src=\"http://www.xxx.com/shop/flash/player.swf?file=http://www.xxx.com/mp3/' + decodeURIComponent(mp3location) + '.mp3&as=1\" quality=high bgcolor=#000000 WMODE=transparent width=\"161\" height=\"13\" align=\"\" type=\"application/x-shockwave-flash\" swLiveConnect=\"true\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" class=\"playerNew\">');
}
which works fine with IE, and also solves the problem of not being able to stop the players from playing in IE

Categories