Show and hide Div with Java Script

2

The code below is to show and hide the contents of a div .

I'm trying to use it to show some videos, but I can not make it show more than 2 videos.

See the code:

Html

<button id="opt1">Option 1</button>
<button id="opt2">Option 2</button>

 <div class="yesDisplay">
<p>Video 01</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/6AmRg3p79pM?controls=0&amp;showinfo=0"frameborder="0" allowfullscreen></iframe>
 </div>

 <div class="noDisplay">
<p>Video 02</p>
<iframe width="560" height="315" src="https://www.youtube.com/embed/6AmRg3p79pM?controls=0&amp;showinfo=0"frameborder="0" allowfullscreen></iframe>
 </div>

CSS

 .noDisplay{display:none;}

 .yesDisplay{display:block;}

SCRIPT

$('#opt1').click(function(){
$('.yesDisplay').show();
$('.noDisplay').hide();
});

$('#opt2').click(function(){
$('.yesDisplay').hide();
$('.noDisplay').show();
}); 

I'd like to show up to 8 videos on it, and when you click on a button the other hides. If possible do this with JavaScript.

    
asked by anonymous 11.06.2015 / 23:50

1 answer

3

You have to program HTML and JavaScript to be scalable. In other words, to work regardless of how many videos you have. One way to do this would be like this:

var buttons = $('#videoGallery button');
var videos = $('#videoGallery div');

buttons.on('click', function () {
    var index = buttons.get().indexOf(this);
    videos.removeClass('yesDisplay');
    videos.eq(index).addClass('yesDisplay');
});

jsFiddle: link

This code assumes that you have all button and div > iframe inside a wrapper #videoGallery and that all div are hidden. That is, you do not need the noDisplay class. And then just add and remove classes. Nothing of .show() and .hide() .

    
12.06.2015 / 00:04