Bootstrap 3 y Youtube en Modal


Estoy tratando de usar la función Modal de Bootstrap 3 para mostrar mi video de Youtube. Funciona, pero no puedo hacer clic en ningún botón en el video de Youtube.

¿Alguna ayuda en esto?

Aquí está mi código:

<div id="link">My video</div>

<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            </div>
            <div class="modal-body">
                <iframe width="400" height="300" frameborder="0" allowfullscreen=""></iframe>
            </div>
        </div>
    </div>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-1.10.1.min.js"><\/script>')</script>
<script src="js/bootstrap.min.js"></script>
<script>
    $('#link').click(function () {
        var src = 'http://www.youtube.com/v/FSi2fJALDyQ&amp;autoplay=1';
        $('#myModal').modal('show');
        $('#myModal iframe').attr('src', src);
    });

    $('#myModal button').click(function () {
        $('#myModal iframe').removeAttr('src');
    });
</script>
Author: alex, 2013-09-04

15 answers

Encontré este problema (o el problema que encontré y describí en https://github.com/twbs/bootstrap/issues/10489 ) relacionado con la transformación CSS3 (traducción) en la clase .modal.fade .modal-dialog.

En bootstrap.css encontrará las líneas que se muestran a continuación:

.modal.fade .modal-dialog {
  -webkit-transform: translate(0, -25%);
      -ms-transform: translate(0, -25%);
          transform: translate(0, -25%);
  -webkit-transition: -webkit-transform 0.3s ease-out;
     -moz-transition: -moz-transform 0.3s ease-out;
       -o-transition: -o-transform 0.3s ease-out;
          transition: transform 0.3s ease-out;
}

.modal.in .modal-dialog {
  -webkit-transform: translate(0, 0);
      -ms-transform: translate(0, 0);
          transform: translate(0, 0);
}

Reemplazar estas líneas con lo siguiente mostrará la película correctamente (en mi caso):

.modal.fade .modal-dialog {
  -webkit-transition: -webkit-transform 0.3s ease-out;
     -moz-transition: -moz-transform 0.3s ease-out;
       -o-transition: -o-transform 0.3s ease-out;
          transition: transform 0.3s ease-out;
}

.modal.in .modal-dialog {

}
 95
Author: Bass Jobsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-31 14:56:34

Armé este script modal de video de YouTube dinámico html/jQuery que reproduce automáticamente el video de YouTube cuando se hace clic en el disparador (enlace), el disparador también contiene el enlace para reproducir. El script encontrará la llamada modal nativa de bootstrap y abrirá la plantilla modal compartida con los datos del disparador. Vea a continuación y hágame saber lo que piensa. Me encantaría escuchar pensamientos...

HTML MODAL TRIGGER:

 <a href="#" class="btn btn-default" data-toggle="modal" data-target="#videoModal" data-theVideo="http://www.youtube.com/embed/loFtozxZG0s" >VIDEO</a>

PLANTILLA DE VÍDEO MODAL HTML:

<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="videoModal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <div>
          <iframe width="100%" height="350" src=""></iframe>
        </div>
      </div>
    </div>
  </div>
</div>

EL JQUERY FUNCIÓN:

//FUNCTION TO GET AND AUTO PLAY YOUTUBE VIDEO FROM DATATAG
function autoPlayYouTubeModal(){
  var trigger = $("body").find('[data-toggle="modal"]');
  trigger.click(function() {
    var theModal = $(this).data( "target" ),
    videoSRC = $(this).attr( "data-theVideo" ), 
    videoSRCauto = videoSRC+"?autoplay=1" ;
    $(theModal+' iframe').attr('src', videoSRCauto);
    $(theModal+' button.close').click(function () {
        $(theModal+' iframe').attr('src', videoSRC);
    });   
  });
}

LA LLAMADA A LA FUNCIÓN:

$(document).ready(function(){
  autoPlayYouTubeModal();
});

El VIOLÍN: http://jsfiddle.net/jeremykenedy/h8daS/1 /

 32
Author: developernator,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-13 11:03:43

¡Tengo un consejo para ti!

Usaría:

$('#myModal').on('hidden.bs.modal', function () {
    $('#myModal iframe').removeAttr('src');
})

En lugar de:

$('#myModal button').click(function () {
    $('#myModal iframe').removeAttr('src');
});

Porque también puede cerrar el modal sin el botón, por lo que con este código eliminará el video cada vez que el modal se oculte.

 16
Author: Jeffrey Bouva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-02 13:44:47

Aquí hay otra solución: Forzar el video de youtube HTML5

Simplemente añadir ?html5 = 1 al atributo source en el iframe, así:

<iframe src="http://www.youtube.com/embed/dP15zlyra3c?html5=1"></iframe>
 13
Author: Chris Scheler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:27

Encontrado esto en otro hilo, y funciona muy bien en el escritorio y móvil - que es algo que no parecía cierto con algunas de las otras soluciones. Añade este script al final de tu página:

<!--Script stops video from playing when modal is closed-->
<script>
    $("#myModal").on('hidden.bs.modal', function (e) {
        $("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
    });
</script>   
 11
Author: user2232930,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-09 20:17:43

Si no quieres editar el CSS de bootstrap o todo lo anterior no te ayuda en absoluto (como en mi caso), hay una solución fácil para que el video se ejecute en un modal en Firefox.

Solo necesita eliminar la clase" fade "del modal y, al abrir la clase "in", también:

$('#myModal').on('shown.bs.modal', function () {
    $('#myModal').removeClass('in');
});
 4
Author: 0xC0FF33,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-18 19:59:01

Lo he resuelto en la plantilla de wordpress:

$videoLink ="http://www.youtube.com/watch?v=yRuVYkA8i1o;".   
<?php
    parse_str( parse_url( $videoLink, PHP_URL_QUERY ), $my_array_of_vars );
    $youtube_ID = $my_array_of_vars['v'];    
?> 
<a class="video" data-toggle="modal" data-target="#myModal" rel="<?php echo $youtube_ID;?>">
    <img src="<?php bloginfo('template_url');?>/assets/img/play.png" />
</a>

<div class="modal fade video-lightbox" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">    
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            </div>
            <div class="modal-body"></div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<script> 
    jQuery(document).ready(function ($) {
        var $midlayer = $('.modal-body');     
        $('#myModal').on('show.bs.modal', function (e) {
            var $video = $('a.video');
            var vid = $video.attr('rel');
            var iframe = '<iframe />';  
            var url = "//youtube.com/embed/"+vid+"?autoplay=1&autohide=1&modestbranding=1&rel=0&hd=1";
            var width_f = '100%';
            var height_f = 400;
            var frameborder = 0;
            jQuery(iframe, {
                name: 'videoframe',
                id: 'videoframe',
                src: url,
                width:  width_f,
                height: height_f,
                frameborder: 0,
                class: 'youtube-player',
                type: 'text/html',
                allowfullscreen: true
            }).appendTo($midlayer);   
        });

        $('#myModal').on('hide.bs.modal', function (e) {
            $('div.modal-body').html('');
        }); 
    });
</script>
 4
Author: Bijaya Kumar Oli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-02 10:42:28

Bootstrap proporciona funcionalidad modal emergente desde el primer momento.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<a class="btn btn-primary" data-toggle="modal" href="#modal-video"><i class="fa fa-play"></i> watch video</a>
<div class="modal fade" id="modal-video" style="display: none;">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">close <i class="fa fa-times"></i></button>
      </div>
      <div class="modal-body">
        <iframe type="text/html" width="640" height="360" src="//www.youtube.com/embed/GShZUiyqEH0?rel=0?wmode=transparent&amp;fs=1&amp;rel=0&amp;enablejsapi=1&amp;version=3" frameborder="0" allowfullscreen=""></iframe>
        <p>Your video</p>
      </div>
    </div>
  </div>
</div>
 2
Author: jagdish.narkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-09 09:37:11

MMhh... ¿Podría publicar su documento HTML completo y qué navegador / versión utiliza?

He recreado su página y probado en 3 navegadores (Chrome, FF, IE8). Pude parar y comenzar el impresionante tráiler de WDS4 sin ningún problema. Aquí está mi código:

<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap 101 Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap -->
    <link href="bootstrap.min.css" rel="stylesheet" media="screen">

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="../../assets/js/html5shiv.js"></script>
      <script src="../../assets/js/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <div id="link">My video</div>

    <div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">

                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>

                <div class="modal-body">
                    <iframe width="400" height="300" frameborder="0" allowfullscreen=""></iframe>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="jq.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="bootstrap.min.js"></script>
    <script>
    $('#link').click(function () {
        var src = 'http://www.youtube.com/v/FSi2fJALDyQ&amp;autoplay=1';
        $('#myModal').modal('show');
        $('#myModal iframe').attr('src', src);
    });

    $('#myModal button').click(function () {
        $('#myModal iframe').removeAttr('src');
    });
</script>
  </body>
</html>

¿Podrías intentar subir el índice Z de tu jugador modal en la pila?

$('#myModal iframe').css("z-index","999");

 0
Author: TyMayn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-04 20:20:13
<a href="#" class="btn btn-default" id="btnforvideo" data-toggle="modal" data-target="#videoModal">VIDEO</a>

<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="videoModal" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <div>
                    <iframe width="100%" height="315" src="https://www.youtube.com/embed/myvideocode" frameborder="0" allowfullscreen></iframe>
                </div>
            </div>
        </div>
    </div>
</div>
 0
Author: FahadAkram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-22 08:23:10

Usando $('#introVideo').modal('show'); entra en conflicto con la activación propia de bootstrap. Al hacer clic en el enlace que abre el Modal se cerrará justo después de completar la animación de fundido. Simplemente retire el $('#introVideo').modal('show'); (usando bootstrap v3.3.2)

Aquí está mi código:

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<!-- triggering Link -->
<a id="videoLink" href="#0" class="video-hp" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a>


<!-- Intro video -->
<div class="modal fade" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="introductionVideo" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <div class="embed-responsive embed-responsive-16by9">
            <iframe class="embed-responsive-item allowfullscreen"></iframe>
        </div>
      </div>
    </div>
  </div>
</div>


<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"> </script>

<script>
  //JS

$('#videoLink').click(function () {
    var src = 'https://www.youtube.com/embed/VI04yNch1hU;autoplay=1';
    // $('#introVideo').modal('show'); <-- remove this line
    $('#introVideo iframe').attr('src', src);
});


$('#introVideo button.close').on('hidden.bs.modal', function () {
    $('#introVideo iframe').removeAttr('src');
})
</script>
 0
Author: Imadeddine Bouziani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-19 10:32:01

La respuesta de User3084135 funcionó bien como base para mí, pero también necesitaba incorporar:

  1. La etiqueta " video "para el video alojado localmente, así como la etiqueta" iframe " para el video alojado externamente
  2. Asegúrese de que la fuente fue eliminada sin embargo el modal fue descartado
  3. La solución funcionó en un diseño responsivo de Bootstrap
  4. Todos los videos se reproducen automáticamente en modal open
  5. Múltiples modales son posibles

Mi solución terminada parece esto:

BOTÓN DE DISPARO MODAL

<a href="#" class="portfolio-link" data-toggle="modal" data-frame="iframe" data-target="#portfolioModal1" data-theVideo="http://www.youtube.com/embed/xxxxxxxx">

El atributo data-frame puede ser "iframe" o "video" para reflejar el tipo de etiqueta apropiado: iframe para videos externos, video para hospedados localmente.

BOOTSTRAP RESPONSIVE VIDEO CONTAINERS

IFrame:

<div align="center" class="embed-responsive embed-responsive-16by9">
  <iframe width="420" height="315" src="" frameborder="0" allowfullscreen></iframe>
</div>

Video:

<div align="center" class="embed-responsive embed-responsive-16by9">
    <video width="640" height="364" controls>
        <source src="" type="video/mp4">
        Your browser does not support the video tag.
    </video>                               
</div>

Ambos residen dentro de los divs modales responsivos de Bootstrap estándar.

JQUERY SCRIPT

<script>
 $(document).ready(function(){
    function autoPlayModal(){
      var trigger = $("body").find('[data-toggle="modal"]');
      trigger.click(function() {
        var theFrame = $(this).data( "frame" );
        var theModal = $(this).data( "target" );
        videoSRC = $(this).attr( "data-theVideo" ); 
        if (theFrame == "iframe") {
          videoSRCauto = videoSRC+"?autoplay=1" ;
        } else {
          videoSRCauto = videoSRC;
          $("[id*=portfolioModal] video").attr('autoplay','true');
        }
        $(theModal+' '+ theFrame).attr('src', videoSRCauto); 
        $("[id*=portfolioModal]").on('hidden.bs.modal', function () {
            $("[id*=portfolioModal] "+ theFrame).removeAttr('src');
        })
      });
    }

  autoPlayModal();
});
</script>

Dado que la reproducción automática funciona de manera diferente con las etiquetas iframe y video, un condicional se utiliza para tratar con cada uno. Para permitir múltiples modales, se utiliza un selector comodín para identificarlos (portfolioModal1-6 en mi caso).

 0
Author: awvidmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-05 21:03:34

Tuve este mismo problema - acababa de agregar los enlaces de cdn font-awesome - comentando el bootstrap uno a continuación resolvió mi problema.. realmente no solucionó el problema ya que la fuente awesome aún funcionaba -

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
 0
Author: Fstarocka Burns,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-26 10:41:56

Ok. Encontré una solución.

                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">
                        <span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                    </button>
                    <h3 class="modal-title" id="modal-login-label">Capital Get It</h3>
                    <p>Log in:</p>
                </div>

                <div class="modal-body">

                    <h4>Youtube stuff</h4>



             <iframe src="//www.youtube.com/embed/lAU0yCDKWb4" allowfullscreen="" frameborder="0" height="315" width="100%"></iframe>       
             </div>


                </div>

            </div>
        </div>
    </div>
 0
Author: Mwangi Thiga,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-11 11:11:05

$('#videoLink').click(function () {
    var src = 'https://www.youtube.com/embed/VI04yNch1hU;autoplay=1';
    // $('#introVideo').modal('show'); <-- remove this line
    $('#introVideo iframe').attr('src', src);
});

$('#introVideo button.close').on('hidden.bs.modal', function () {
    $('#introVideo iframe').removeAttr('src');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<!-- triggering Link -->
<a id="videoLink" href="#0" class="video-hp" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a>

<!-- Intro video -->
<div class="modal fade" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="introductionVideo" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <div class="embed-responsive embed-responsive-16by9">
            <iframe class="embed-responsive-item allowfullscreen"></iframe>
        </div>
      </div>
    </div>
  </div>
</div>
 -3
Author: Kondal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-11 14:02:43