Saili G Saili G - 1 month ago 10
Javascript Question

How to manage different events with event listener for different elements?

$(document).ready(function ()
{
var player_1_listener = $('#myVid_1')[0];
$f(player_1_listener).addEvent('ready', ready);

var player_2_listener = $('#myVid_2')[0];
$f(player_2_listener).addEvent('ready', ready);

function addEvent(element, eventName, callback)
{
if (element.addEventListener)
{
element.addEventListener(eventName, callback, false);
}
else
{
element.attachEvent(eventName, callback, false);
}
}

function ready(player_id)
{
//var froogaloop = $f(player_id);
if (player_id === myVid_1)
{
var froogaloop = $f(player_id);
function onFinish()
{
froogaloop.addEvent('finish', function(data)
{
/*var players_unloading;
players_unloading=$('#myVid_1');
$f(players_unloading[0]).api('unload');*/
toggleOverlay_1();
$f(froogaloop[0]).api('unload');
});
}
//onFinish();
}
else if (player_id === myVid_2)
{
var froogaloop = $f(player_id);
function onFinish()
{
froogaloop.addEvent('finish', function(data)
{
/*var players_unloading;
players_unloading=$('#myVid_1');
$f(players_unloading[0]).api('unload');*/
toggleOverlay_2();
$f(froogaloop[0]).api('unload');
});
}
//onFinish();
}
}
onFinish();
});


I have 2 buttons which on clicking open an iframe and play videos. I am trying to get the player within the iframe to call it's api pause method to pause the video. I can do this well if I use only one iframe video, but I am unable to do when there are multiple iframe videos.

enter image description here

Answer

You will need to work with adding parameters to the functions in a way to re-use as much code as possible. The way i see it you can add playerid in all related functions and use that to minimize code within the ready(player_id) by utilizing the player_id as main id to help access all related video items.

$(document).ready(function () {
 var player = $('#myVid')[0];
 var player2 = $('#myVid2')[0];
 $f(player).addEvent('ready', ready); 
 $f(player2).addEvent('ready', ready); 

  function addEvent(element, eventName, callback) {
    if (element.addEventListener) {
     element.addEventListener(eventName, callback, false);
    }
    else {
      element.attachEvent(eventName, callback, false);
    }
  }

  function ready(player_id) {
    var froogaloop = $f(player_id);

    function onFinish() {
      froogaloop.addEvent('finish', function(data) {
      toggleOverlay(player_id);
      resetVideo(player_id);
  });
 }
 onFinish();
}

});

function toggleOverlay(playerid){
  $("#" + playerid).parent("#specialBox").parent().css("opacity",".8");
  $("#" + playerid).parent("#specialBox").parent().toggle();
  $("#" + playerid).parent("#specialBox").toggle();
}

function resetVideo(vidID)
{
   var player;
   player=$('#' + vidID);
   $f(player[0]).api('unload');
}

Here is working example: http://codepen.io/Nasir_T/pen/pEmEJE

Let me know if you need more help.