Show and hide Div with Java Script

Asked

Viewed 616 times

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’t get it to 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 would like to show up to 8 videos on it and when clicking a button the other one hides. If possible do this with Javascript.

1 answer

3


You have to program HTML and Javascript to be scalable. In other words, they work no matter how many videos you have. One way to do it 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: http://jsfiddle.net/qhe7gfd3/

This code assumes you have all the button and div > iframe within a wrapper #videoGallery and that all of these div are hidden. That is, you don’t need the class noDisplay. And then you just add and remove classes. No .show() and .hide().

  • Could show this example with 6 videos ? I’m trying to add more videos and when clicking on the button appears 2 videos instead of 1 inside the div

  • I was doing wrong, forgot to close the last div. now it worked.

  • @user3192159 com 4: http://jsfiddle.net/qhe7gfd3/1/

  • Is it possible to do this without using external code? only with java script within html? this one is not working <script> 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'); }); </script>

  • @user3192159 without jQuery? yes, I can add that in a little while if you want

  • Yes I’m trying to avoid external codes

  • @user3192159 without jQuery: http://jsfiddle.net/w8fyzkgc/

  • 1

    It was great, this option without the need for external code, I will test in some browsers to see if it works at all.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.