Stop YouTube video on modal close - after AJAX load - javascript

I have a small script that stops YouTube videos from playing after their modals are closed. The issue is it doesn't work if the HTML has been loaded via AJAX.
Script:
$('#panelModal-1').on('hidden.bs.modal', function () {
callPlayer('yt-player-1', 'stopVideo');
});
$('#panelModal-2').on('hidden.bs.modal', function () {
callPlayer('yt-player-2', 'stopVideo');
});
HTML (curly braces denote data pulled from CMS):
<li>
<a href="#" title="Watch Video" data-toggle="modal" data-target="#panelModal-{count}">
<div class="video-background" style="background-image:url(http://img.youtube.com/vi/{video_youtube_id}/hqdefault.jpg)"></div>
<div class="video-details">
<h4>{title}</h4>
<p>{video_subtitle}</p>
</div>
</a>
<!-- Modal -->
<div class="modal fade" id="panelModal-{count}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel-{count}">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel-{count}">{title}</h4>
</div>
<div class="modal-body">
<div id="yt-player-{count}" class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://www.youtube.com/embed/{video_youtube_id}?enablejsapi=1"></iframe>
</div>
</div>
</div>
</div>
</div>
</li>
The AJAX part is this:
$(document).ready(function()
{
$('.sub-nav').delegate('.load-case-studies', 'click', function(e)
{
// Don't follow the link
e.preventDefault();
$('.sub-nav a').removeClass('active');
$(this).addClass('active');
// Fetch the next page
$.get($(this).attr('href'), function(data)
{
// Only grab the part of the page we want
content = $(data).find('.ajax-wrapper').hide();
// Add it to the DOM
$(content).replaceAll('#entry-container');
// Fade-in our new content
$(content).fadeIn('fast');
});
});
});
How can I get the videos to stop playing after the modal is closed, if the data has been loaded via AJAX?

you can use following jQuery command.
$('#playerID').get(0).stopVideo();
If your using Player API :
var player = new YT.Player('player');
player.stopVideo();

Related

Appended images loaded from file cannot be selected

I am using the following script to load images from a folder and append them to a div:
$(function() {
var folder = "img/moreprojects/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
$("#gallery").append( "<div class=\"col-12 col-sm-3\" align='center'><img class='img-fluid img-thumbnail img-rounded mx-auto d-block' style=\"max-width: 240px; max-height: 240px; margin: 12px;\" src='"+ folder + val +"'></div>" );
}
});
}
});
});
However, when I call my next script, which opens a model for the image (which works on images already on the page), the images do not open:
$(function() {
$('img').on('click', function() {
$('.enlargeImageModalSource').attr('src', $(this).attr('src'));
$('#enlargeImageModal').modal('show');
});
});
How can I have this function, which already works for images in HTML already, work for my dynamically loaded images?
Note: I am using Bootstrap 4 and jQuery.
EDIT
HTML structure (I am using Bootstrap 4):
<section class="py-5">
<div class="container">
<div class="row" id="gallery">
<p class="lead">Welcome to our gallery! Here we showcase all the images from our projects and other work. Use the toggles below, to switch between a list view and a swiping gallery view!</p>
<br /><br />
</div>
</div>
</section>
<div class="modal fade" id="enlargeImageModal" tabindex="-1" role="dialog" aria-labelledby="enlargeImageModal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<img src="" class="enlargeImageModalSource" style="width: 100%;">
</div>
</div>
</div>
</div>
Changing the .on('click', ...) call from:
$('img').on('click', function() {...});
to
$(document).on('click', 'img', function() {...});
fixed the issue for calling a click event on the dynamically loaded images.

How to reset position for popup modal with Bootstrap?

I was looking for a solution to my problem and I saw a lot of different ways to do that but none of them worked to me.
I'll paste my code here and see if you can help me somehow.
I have a draggable popup to display a note. There is a list of items on the main screen and everytime the user clicks on the "View" link it opens the popup with the Note for this specific item.
Everything is working properly. The popup opens with the right information and I can move the popup around the screen. Then only problem I have is:
Once I close the popup and open a new one, instead of reseting the popup to the original position it opens exactly where I left the other one. I need to reset the position for the popup when the user closes it.
This is my js:
require(['jquery'
, 'bootstrap'
, 'datepicker'
, 'typeahead'
, 'combobox'
, 'tagsinput'
], function($){
// DOM ready
$(function(){
$('.modal-dialog').draggable();
$('#noteModal').on('show.bs.modal', function(e) {
//get data-id attribute of the clicked element
var note = $(e.relatedTarget).data('note');
//populate the textbox
$(e.currentTarget).find('span[name="note"]').text(note);
});
});
});
This is the modal on my html page:
<!-- Modal to display the Note popup -->
<div class="modal" id="noteModal" tabindex="-1" role="dialog" aria-labelledby="noteModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="noteModalLabel">Note</h4>
</div>
<div class="modal-body">
<span name="note" id="note"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
How can I reset the position for the popup everytime the user closes it?
THank you!
Inside your click handler, you can use JQuery to set the css of the modal like so:
if (!$(".modal.in").length) {
$(".modal-dialog").css({
top: 0,
left: 0
});
}
This will reset the position of your modal. You can use it before you call your modal in your JavaScript, assuming you are using JS to open your modal.
Try running the snippet below or see this CodePen Demo for an example of this using your modal.
// DOM ready
$(function() {
$(".modal-dialog").draggable();
$("#btn1").click(function() {
// reset modal if it isn't visible
if (!$(".modal.in").length) {
$(".modal-dialog").css({
top: 0,
left: 0
});
}
$("#noteModal").modal({
backdrop: false,
show: true
});
});
$("#noteModal").on("show.bs.modal", function(e) {
var note = $('#btn1').data('note');
$(e.currentTarget).find('span[name="note"]').html(note);
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<!-- Modal to display the Note popup -->
<div class="modal" id="noteModal" tabindex="-1" role="dialog" aria-labelledby="noteModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="noteModalLabel">Note</h4>
</div>
<div class="modal-body">
<span name="note" id="note"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<button id="btn1" data-note="I am a note. Hello.">Show Modal</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
If you want to keep the background usable while your modal is open, I posted a solution to this a little while ago here.
I hope this helps!

Is there a way top open a modal from selecting a node from vis.js?

I'm trying to open a modal when clicking on a node within a network map i have made using vis.js
I am unsure about where I would place the data-target tag,but I'm not sure if that's the issue, below is the JS that I have written to handle a click action as well as the modal
Currently the data-target is declared within the div tag where the network map is placed after it has been generated (I know this is wrong)
The JS is being Generated in PHP hence the PHP var being thrown in there
Click Action -
network.on( 'click', function(properties) {
var ids = properties.nodes;
var clickedNodes = ".$nodes.".get(ids);
console.log('clicked nodes:', clickedNodes);
console.log('/monitoring/loadNode/'+clickedNodes[0].id);
$( '#myModalDeviceDetails' ).html('<h1><center><font color=\'white\'>Loading</font></center></h1>');
$( '#myModalDeviceDetails' ).load( '/monitoring/loadNode/'+clickedNodes[0].id ).show();
});
Modal-
<div class="modal fade modal-primary" id="myModalDeviceDetails" tabindex="-1" role="dialog" aria-labelledby="Device Details">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Device Details</h4>
</div>
<div class="modal-body">
loading...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Thanks in advance!
I can see that is a bootstrap modal. It has functions like the following:
$('#myModal').modal('toggle');
$('#myModal').modal('show');
$('#myModal').modal('hide');
I would recommend hiding the modal when you load the page and than just show it.

How to stop Vimeo video when Bootstrap modal is dismissed?

I have a Vimeo modal that works wonderfully and - after some effort - I've gotten the video to stop when the modal is closed via the 'X' button. However, since I put the close function on the 'X' button, if the user clicks away from the video to close the modal rather than using the button, the video keeps playing.
Here is the HTML where I call the stopVideo() function with onclick:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="stopVideo()">
<span aria-hidden="true">×</span>
</button>
</div>
And here is the Javascript function that stops the video:
<script>
function stopVideo(){
var $frame = $('iframe#nofocusvideo');
// saves the current iframe source
var vidsrc = $frame.attr('src');
// sets the source to nothing, stopping the video
$frame.attr('src','');
// sets it back to the correct link so that it reloads immediately on the next window open
$frame.attr('src', vidsrc);
}
</script>
So, how can I alter the function to apply not to the specific close button, but to any instance where the modal loses focus such as clicking away from the video?
I'm a novice, so go easy on me. Thanks in advance!
EDIT 1:
I've changed the script to the following:
<script>
function stopVideo(){
var $frame = $('iframe#nofocusvideo');
// saves the current iframe source
var vidsrc = $frame.attr('src');
// sets the source to nothing, stopping the video
$frame.attr('src','');
// sets it back to the correct link so that it reloads immediately on the next window open
$frame.attr('src', vidsrc);
}
$('#promo-video').on('hidden.bs.modal', function (e) {
stopVideo();
})
</script>
The stopVideo() function is not being called. Any idea what I'm doing wrong?
EDIT 2:
Here's the code for the modal in question:
<!-- VIDEO MODAL -->
<div class="modal fade" id="promo-video" tabindex="-1" role="dialog" aria-labelledby="modal-video-label">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="stopVideo()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="modal-video">
<div class="embed-responsive embed-responsive-16by9">
<iframe id="nofocusvideo" src="https://player.vimeo.com/video/180565514?api=1&player_id=vimeoplayer" name="vimeoplayer" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End Video Modal -->
Here's the working code for it using the default bootstrap id's. Not too sure why yours isn't working.
function stopVideo() {
var $frame = $('iframe#nofocusvideo');
// saves the current iframe source
var vidsrc = $frame.attr('src');
// sets the source to nothing, stopping the video
$frame.attr('src', '');
// sets it back to the correct link so that it reloads immediately on the next window open
$frame.attr('src', vidsrc);
}
$('#myModal').on('hidden.bs.modal', function(e) {
stopVideo();
})
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<iframe id="nofocusvideo" src="https://player.vimeo.com/video/182738685" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
A solution that work for me is reload the modal contents:
$("#modal-video").on("hidden.bs.modal", function () {
var url = $('#video-frame').attr('src');
$('#video-frame').attr('src', '');
$('#video-frame').attr('src', url);
});
After a lot of trial and error, changing the javascript to the following solved my problem:
<script>
( function($) {
function iframeModalOpen(){
$('.modalButton').on('click', function(e) {
var src = $(this).attr('data-src');
var width = $(this).attr('data-width') || 640;
var height = $(this).attr('data-height') || 360;
var allowfullscreen = $(this).attr('data-video-fullscreen');
$("#promo-video iframe").attr({
'src': src,
'height': height,
'width': width,
'allowfullscreen':''
});
});
$('#promo-video').on('hidden.bs.modal', function(){
$(this).find('iframe').html("");
$(this).find('iframe').attr("src", "");
});
}
$(document).ready(function(){
iframeModalOpen();
});
} ) ( jQuery );
</script>
I have a series of vimeo player in modal and finally figured out a dynamic way to stop the video after closing the modal. Seriously, bootstrap/vimeo should add this as default!!
$('.modal').on('hidden.bs.modal', function () {
var $this = $(this);
//get iframe on click
var vidsrc_frame = $this.find("iframe");
var vidsrc_src = vidsrc_frame.attr('src');
console.log(`videosrc=` + vidsrc_src);
vidsrc_frame.attr('src', '');
vidsrc_frame.attr('src', vidsrc_src);
});
Have a nice day!
This option is better and dynamic
$(function(){
$('.modal, .close').click(function(){
$("iframe").each(function() {
var src= $(this).attr('src');
$(this).attr('src',src);
});
});
});

jquery accessing data-attrs

I'm using bootstrap modal for destroying task objects. When I click on a given task on the index page the modal window pops up and the destroy link of that task gets loaded via data attr, so modal will know which task should be destroyed when user clicks on #delete-task-submit button.
The code works as it is, but I'd like to use data-behavior="delete-task-submit" instead of #delete-task-submit to be clear that this has nothing to do with styling and it's only there for the js call.
What's the right way to do it? I'm asking this because #delete-task-submit is used in the first js call for finding/setting data-task-destroy-link and don't know how else I can find that data attribute without adding id/extra class there.
<div class="modal fade" id="delete-task-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content" style="text-align:left">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Delete Task</h4>
</div>
<div class="modal-body">
<h4>Are you sure?</h4>
<p> </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deletetaskclose">Close</button>
<a href="#" id="delete-task-submit" type="button" class="btn btn-danger" data-task-destroy-link >Delete Task</a>
<!-- DESTROY LINK GETS INSERTED HERE -->
</div>
</div>
</div>
</div>
$(document).on('click', '[data-behavior="open-delete-task-modal"]', function (event) {
var taskDeleteLink = $(this).data("task-delete-link");
$('#delete-task-submit').data("task-destroy-link", taskDeleteLink);
});
$(document).on('click', '#delete-task-submit', function (event) {
var href = $(this).data("task-destroy-link");
$.ajax({
type: "DELETE",
url: href,
dataType: "script"
});
});
I'm asking this because #delete-task-submit is used in the first js call for finding/setting data-task-destroy-link and don't know how else I can find that data attribute without adding id/extra class there.
Replace $('#delete-task-submit') with $('[data-behavior="delete-task-submit"]') selector in that part of your code and add data-behavior="delete-task-submit" attribute to your link.
Delete Task

Categories