purple11111 purple11111 - 6 months ago 18
Javascript Question

tiltSlider play/pause video elements if li has class current

http://codepen.io/hennysmafter/pen/aNrVKG?editors=1010

The code in question is this:

(function($) {
$(document).ready(function(){
$('video').each(function() {
$(this).get(0).pause();
});
});

$(document).on('click','span',function(){
if ( $('li').hasClass('current') ) {
$('li.current').find('video').each(function() {
$(this).get(0).play();
});
} else if ( !$('li').hasClass('current') ) {
$('li').find('video').each(function() {
$(this).get(0).pause();
});
}
});

})(jQuery);


The problem.

The moment the user clicks on the 3rd nav button the li element has not yet assigned the custom class to it. So it now requires the user to manually click a 2nd time on the same nav button(which clearly is stupid.).

Requirements

The li with video elements can be any slide so I can't hardcode it in.

What have I tried.

I have tried Ayyoub Dahhane suggestion which works brilliantly but at the moment it is hardcoded which slides are video slides and this cannot be.
I have tried some other codes that can be seen at:
http://codepen.io/hennysmafter/pen/PNvEPN & http://codepen.io/hennysmafter/pen/MydEBw
I tried working with a delay. Codepen is already changed so no link for this. But it did not work anyway.

I find it absolutely bonkers that this proves to be so freaking difficult. So here my latest attempt which is working but shows a couple of errors in the console and it still requires double clicking: http://codepen.io/hennysmafter/pen/aNrVKG?editors=1010

So back to the drawing board.

Answer

Well as I was asked, here's my answer from onclick function requires double click because of class assignment delay :


I found what is causing the issue :

You are playing the elements whose parent has ".current" class when a span is clicked.

But when you click an element, it et the ".show" class, and the previously selected span get the ".hide" class AND keeps the ".current" class, until the animation is finished (then the ".show" & ".hide" class are removed and the ".current" class switch elements).

One solution is changing the selectors like this :

$(document).on('click','span',function(){
      console.log('the if is running');
      $('.current, .hide').find('video').each(function() {
          $(this).get(0).pause();
      });  
      $('.show').find('video').each(function() {
          $(this).get(0).play();
      });

});

By doing this, whenever a span is clicked, you pause the element whose parents have the ".hide" class, and play the ones whose parents have the ".show" class.

Another solution should be creating an event when a class is applied (See jQuery - Fire event if CSS class changed).

Comments