00-BBB 00-BBB - 5 months ago 19
Javascript Question

jQuery video hover optimising dynamic selectors

I'm working on something where the user hovers over a video to trigger it playing. When they hover over a different video, this new video starts playing and stops the others.

I'm using Vimeo and their Froogaloop library ( not too relevant here, could also be video tags, mainly concerned with the caching of the selectors ).

This code works fine, but I know it's not as optimised as it should be, it uses multiple selectors each time the hover function is called which I don't want to do. Can I improve this code so that it doesn't do this? Or is it Ok to keep calling the jQuery selectors like this in modern browsers now?

Here is a simplified working demo

function hoverVid() {
var frame = $(this).find('iframe');
var player = $f(frame[0]);
player.api('play');

var vids = $('.vid-row iframe').not(frame);
vids.each(function(index) {
var frame = $(this);
var player = $f(frame[0]);
player.api('pause');
});
}

$('.vid-row').hover(hoverVid);


Cheers :]

Answer

I improved it a bit - As per @GerardCuadras comment, removed the need for using the .not() filter by simply pausing all the videos, then playing the desired one.

This allowed me to cache the list of iframes. I also optimised the selector to use an #id and .find().

JSBin

var vidz = $('#vidz').find('iframe');

function hoverVid(e){

  vidz.each(function( index ){
    var frame = $(this);
    var player = $f(frame[0]);
    player.api('pause');
  });

  var frame = $(this).find('iframe');
  var player = $f(frame[0]);
  player.api('play'); 
}

$('.vid-row').hover(hoverVid);