5

My web page has 5 videos on it. Only when you hover over the video will it begin to play. My code for this is as follows:

$(".service:nth-child(1) a").hover(function(){
    $('.service:nth-child(1) a video#bgvid').get(0).play();
},function(){
    $('.service:nth-child(1) a video#bgvid').get(0).pause();
});

I have used :nth-child because if I hover over video 4, it plays video 1 so I have to be specific. This means I have to repeat the above code for every video but change the :nth-child number accordingly. I'm not particularly skilled with JS but there has to be a better and more efficient way of doing this?

egr103
  • 3,858
  • 15
  • 68
  • 119

2 Answers2

3

Untested but this should get you started. Ha, a pun. this. Get it?

$('.service a').hover(function(){
  $(this).children('video').get(0).play();
}, function(){
  $(this).children('video').get(0).pause();
});

See also: https://stackoverflow.com/a/28443915/362536

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
  • Youd did a funny! ;) I have explored this option but it didn't work for me as I I need to target the child video#bgvid specifically within .service a if that makes sense? – egr103 May 02 '15 at 16:14
  • @egr103 It does. In that case, you can use `$(this).children('video')` or something like that. https://api.jquery.com/children/ Also note that you shouldn't use the same ID more than once. – Brad May 02 '15 at 16:18
  • Perfect that did the trick. I still had to use .get(0) to get it properly working but .children did the trick. Thanks! – egr103 May 02 '15 at 16:21
0

Like brad said, using this will allow you to get the currently hovered element. However, afaik jQuery doesn't give you access to the HTML5 video API through their object, so you'd need to do something like:

$('.service a video').hover(function(e){
  e.target.play();
}, function(e){
  e.target.pause();
});

When you bind a function to an event, this will always be the object on which the event was triggered. Calling $(this) returns a jQuery'd object

walidvb
  • 322
  • 1
  • 9