I'm trying to work out how best to embed a Youtube video into a Javascript function so it will appear (and be playable) in a popup alert box.
This is the code I'm using:
<script>
function myFunction12() {
alert("");
}
</script>
And the video I'm trying to insert is here: https://www.youtube.com/watch?v=bWdQbxNEFEs&frags=pl%2Cwn
I've been trying to use the embed code provided by Youtube in the alert quotations, but it doesn't recognize HTML there and I'm not sure how to proceed. The video needs to appear and play in a popup box.
Thanks much in advance for any tips! I'm pretty new at writing Javascript and may ask follow up questions.
EDIT: I'm now working on creating a modal box that pops up with the video in it when the user clicks "1" on the imagemap. I think the components are correct, but I can't quite get the two to connect. Any suggestions would be greatly appreciated!
My code is here: w3schools.com/code/tryit.asp?filename=FXKTC5KYZEEL
You Can't; Use a Modal Instead
To my knowledge, it is not possible to embed a video in the alert popup as it only displays plaintext. Youtube embeds are created by using an iframe element which means that the video can't be placed in a traditional Javascript alert() popup.
Instead, if you want to have a video you should probably have some Javascript that either creates or unhides an element that contains the video you want. If the video isn't constant, you can set it's url with javascript as well.
You can use ALertifyJS. You can click outside. You have to use the Youtube Dialogue Alert. I used the CDN in the snippet below. Download Link --
https://alertifyjs.com/build/alertifyjs.zip
alertify.YoutubeDialog || alertify.dialog('YoutubeDialog', function() {
var iframe;
return {
// dialog constructor function, this will be called when the user calls alertify.YoutubeDialog(videoId)
main: function(videoId) {
//set the videoId setting and return current instance for chaining.
return this.set({
'videoId': videoId
});
},
// we only want to override two options (padding and overflow).
setup: function() {
return {
options: {
//disable both padding and overflow control.
padding: !1,
overflow: !1,
}
};
},
// This will be called once the DOM is ready and will never be invoked again.
// Here we create the iframe to embed the video.
build: function() {
// create the iframe element
iframe = document.createElement('iframe');
iframe.frameBorder = "no";
iframe.width = "100%";
iframe.height = "100%";
// add it to the dialog
this.elements.content.appendChild(iframe);
//give the dialog initial height (half the screen height).
this.elements.body.style.minHeight = screen.height * .5 + 'px';
},
// dialog custom settings
settings: {
videoId: undefined
},
// listen and respond to changes in dialog settings.
settingUpdated: function(key, oldValue, newValue) {
switch (key) {
case 'videoId':
iframe.src = "https://www.youtube.com/embed/" + newValue + "?enablejsapi=1";
break;
}
},
// listen to internal dialog events.
hooks: {
// triggered when the dialog is closed, this is seperate from user defined onclose
onclose: function() {
iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
},
// triggered when a dialog option gets update.
// warning! this will not be triggered for settings updates.
onupdate: function(option, oldValue, newValue) {
switch (option) {
case 'resizable':
if (newValue) {
this.elements.content.removeAttribute('style');
iframe && iframe.removeAttribute('style');
} else {
this.elements.content.style.minHeight = 'inherit';
iframe && (iframe.style.minHeight = 'inherit');
}
break;
}
}
}
};
});
//show the dialog
alertify.YoutubeDialog('GODhPuM5cEE').set({
frameless: true
});
<!-- JavaScript -->
<script src="//cdn.jsdelivr.net/npm/alertifyjs#1.13.1/build/alertify.min.js"></script>
<!-- CSS -->
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.13.1/build/css/alertify.min.css" />
<!-- Bootstrap theme -->
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.13.1/build/css/themes/bootstrap.min.css" />
<!-- Default theme -->
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/alertifyjs#1.13.1/build/css/themes/default.rtl.min.css" />
AlertifyJS by Mohammad Younes
Related
I'm currently working on an iframe for clients
It's juste a carrousel with pictures if the user clicks on a picture I need to display the content in full screen with some navigation (next, previous)
Since I never worked with CORS before, I'm getting a hard time figuring how to pass my data from the iframe to the client website :/
Here's a simplified version of the code
Iframe:
<div class="carrousel">
<div class="carrousel_item">
<img data_id="0">
</div>
<div class="carrousel_item">
<img data_id="1">
</div>
</div>
<script>
var gallery = { 0: url1, 1: url2}
jQuery(document).ready(function(){
jQuery('.carrousel.carrousel_item img').on('click', function(){
var data = { data: gallery, last_iterator: jQuery(this).data('id')}
var event = new CustomEvent('display_post', { detail: data })
return window.parent.document.dispatchEvent(event)
}
})
</script>
ScriptJS:
<script>
window.document.addEventListener('display_post', handleEvent, false)
function handleEvent(e) {
console.log(e.detail)
challenge_marque_explorer = data['data'] // image list
last_iterator = data['last_iterator'] // which image is displayed
display_post_details() // fill an overlay display with the image and nav arrow
}
</script>
If I try it on my domain, everything's is fine
But on an other domain I get error's (this one return : Uncaught DOMException: Permission denied to access property "document" on cross-origin object)
Edit:
After 1 hour making close to no progress, I noticed my FTP soft wasn't succeeding in sending the script, now my code works
Here's my working code using postMessage
iFrame:
var gallery = { 0: url, 1: url}
var origin
window.onmessage = function(event) {
origin = event.origin
};
jQuery(document).ready(function(){
jQuery('.carrousel.carrousel_item img').on('click', function(){
var data = { data: challenge_marque_explorer, last_iterator: i, dest: last_dest, page: 0 }
return window.parent.postMessage(JSON.stringify(data),origin);
}
})
The script for the parent page:
window.onmessage = function(event) {
console.log(event.data)
};
jQuery('#gallery_iframe').load(function(){
document.getElementById('gallery_iframe').contentWindow.postMessage('','*');
})
Thanks guys for your time and help :)
If you're stuck and don't see any progress in one of your script, try using 'alert()' to do a quick check on wether or not your file was really updated
Also think about checking the cache, don't loose time and patience due to a file that wasn't sending
I added the ability to display a youtube video within a Lightbox on my website. However, the code I found to help with this doesn't have a close (X) on the Lightbox. Whilst it does close by just clicking anywhere on the mask, I think not all web users are going to realise this, so I added a simple
x
onto the Lightbox div. Whilst this does actually give a functional closing (X) on the lightbox, it has the undesirable effect of the page being back at the top when the Lightbox has closed.
What I ideally want is for the Lightbox to simply close, and the page remains in the same place as it was when it opens, which is what happens if I just click on the mask.
I can see there is a section commented '// Hide lightbox when clicked on', but I have no clue how I can make an (X) also trigger this same action.
Here is the complete script used.
<div id="youtubelightbox" class="parent">x
<div class="centeredchild">
<div class="videowrapper">
<div id="playerdiv"></div>
</div>
</div>
</div>
<script>
// load Youtube API code asynchronously
var tag = document.createElement('script')
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0]
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag)
var isiOS = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)/i) != null //boolean check for iOS devices
var youtubelightbox = document.getElementById('youtubelightbox')
var player // variable to hold new YT.Player() instance
// Hide lightbox when clicked on
youtubelightbox.addEventListener('click', function(){
this.style.display = 'none'
player.stopVideo()
}, false)
// Exclude youtube iframe from above action
youtubelightbox.querySelector('.centeredchild').addEventListener('click', function(e){
e.stopPropagation()
}, false)
// define onYouTubeIframeAPIReady() function and initialize lightbox when API is ready
function onYouTubeIframeAPIReady() {
createlightbox()
}
// Extracts the Youtube video ID from a well formed Youtube URL
function getyoutubeid(link){
// Assumed Youtube URL formats
// https://www.youtube.com/watch?v=Pe0jFDPHkzo
// https://youtu.be/Pe0jFDPHkzo
// https://www.youtube.com/v/Pe0jFDPHkzo
// and more
//See http://stackoverflow.com/a/6904504/4360074
var youtubeidreg = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i;
return youtubeidreg.exec(link)[1] // return Youtube video ID portion of link
}
// Creates a new YT.Player() instance
function createyoutubeplayer(videourl){
player = new YT.Player('playerdiv', {
videoId: videourl,
playerVars: {autoplay:1,
rel:0,
showinfo:0,
fs:0
}
})
}
// Main Youtube lightbox function
function createlightbox(){
var targetlinks = document.querySelectorAll('.lightbox')
for (var i=0; i<targetlinks.length; i++){
var link = targetlinks[i]
link._videoid = getyoutubeid(link) // store youtube video ID portion of link inside _videoid property
targetlinks[i].addEventListener('click', function(e){
youtubelightbox.style.display = 'block'
if (typeof player == 'undefined'){ // if video player hasn't been created yet
createyoutubeplayer(this._videoid)
}
else{
if (isiOS){ // iOS devices can only use the "cue" related methods
player.cueVideoById(this._videoid)
}
else{
player.loadVideoById(this._videoid)
}
}
e.preventDefault()
}, false)
}
}
if (isiOS){ // iOS devices can only use the "cue" related methods
player.cueVideoById(this._videoid)
}
else{
player.loadVideoById(this._videoid)
}
After some trial and error I figured this out.
I changed the html to
<div id="youtubelightbox" class="parent">
<div class="centeredchild"><div id="x">x</div>
<div class="videowrapper">
<div id="playerdiv"></div>
</div>
</div>
</div>
And added the following to the script
x.addEventListener('click', function(){
youtubelightbox.style.display = 'none'
player.stopVideo()
}, false)
I'm building a mobile app using ratchet, and I love the toolset so far, but I'm running into an issue using a modal as a menu.
Here's the live index page.
This is the only custom js I'm using:
$(document).ready(function() {
if ((navigator.userAgent.match(/Android/i))) {
$('head').append('<link rel="stylesheet" href="css/ratchet-theme-android.min.css" type="text/css" />');
var plainAddress = $("#appAddress").text().replace(/\s+/g, "+");
var paramAddress = encodeURI(plainAddress);
var urlAddress = ('geo:0,0+?q=' + paramAddress);
$('#appLink').attr('href', urlAddress);
} else {
$('head').append('<link rel="stylesheet" href="css/ratchet-theme-ios.min.css" type="text/css" />');
var plainAddress = $("#appAddress").text().replace(/\s+/g, "+");
var paramAddress = encodeURI(plainAddress);
var urlAddress = ('http://maps.apple.com/?q=' + paramAddress);
$('#appLink').attr('href', urlAddress);
};
});
$.get('modal/qrModal.html', function(qr) {
$("#loadedModals").append(qr);
});
$.get('modal/menuModal.html', function(qr) {
$("#loadedModals").append(qr);
});
The rest is ratchet.js from goratchet.com. I'm pulling in the menu and the qr code via js because they're not unique to every page. The menu though when launched works fine, and when a selection is made the first time, it follows through, loads the page, and closes the modal.
After that it get's finicky.
Sometimes the modal won't load, sometimes it's unresponsive, sometimes it loads, loads a newpage but doesn't exit the modal.
Is this because I've exported it to external pages? Or is something else the matter?
It looks like your loadedModals container is being cleared out, and not repopulated after a new page is loaded via push.js.
<div id="loadedModals">
...
</div>
You can reload the modals after each push event by firing a callback.
var loadModal = function(){
$.get('modal/qrModal.html', function(qr) {
$("#loadedModals").append(qr);
});
$.get('modal/menuModal.html', function(qr) {
$("#loadedModals").append(qr);
});
};
loadModal();
window.addEventListener('push', loadModal);
I am trying to combine ContentFlow (http://jacksasylum.eu/ContentFlow/) and ColorBox (http://www.jacklmoore.com/colorbox/): when the user clicks on an image in ContentFlow I want an HTML page to be displayed in ColorBox.
I have tried using the code provided by the ColorBox examples' section to no avail. The HTML page is loaded by the browser as a normal link (not in ColorBox.)
I have even tried creating a ContentFlow addon (using the LightBox addon as an example) without any luck - nothing is displayed, not even simple images:
onclickActiveItem: function (item) {
var content = item.content;
if (content.getAttribute('src')) {
if (item.content.getAttribute('href')) {
item.element.href = item.content.getAttribute('href');
}
else if (! item.element.getAttribute('href')) {
item.element.href = content.getAttribute('src');
}
if (item.caption)
item.element.setAttribute ('title', item.caption.innerHTML);
colorbox.show(item.element);
}
}
Edited on 01/Oct/2013
The problem only manifests itself when an item contains an href. To prove this I changed the code above to show a static web page:
$.colorbox({open:true, href:"http://mysite.gr/colorbox/content/static.html"});
It the item is just a simple image the static web page is displayed in ColorBox. But if the item contains an href to the web page I want displayed in ColorBox the browser follows the link and loads the specified page. Any ideas on how to stop this from happening?
Thank you in advance for your help!
I have finally solved the problem I have described in my question. The solution involves creating a ContentFlow addon as follows:
new ContentFlowAddOn ('colorbox', {
init: function () {
var colorboxBaseDir = this.scriptpath+"../colorbox/";
var colorboxCSSBaseDir = colorboxBaseDir;
var colorboxImageBaseDir = colorboxBaseDir;
this.addScript(colorboxBaseDir+"jquery.colorbox.js");
this.addStylesheet(colorboxCSSBaseDir+"example3/colorbox.css");
},
ContentFlowConf: {
onclickInactiveItem: function (item) {
this.conf.onclickActiveItem(item);
},
onclickActiveItem: function (item) {
var content = item.content; // ContentFlow's content class
var theItem = item.item; // ContentFlow's item class - if you need access to it
var hrefToDisplay = '';
if (content.getAttribute('src')) {
if (content.getAttribute('href')) {
hrefToDisplay = item.content.getAttribute('href');
}
else if (!item.element.getAttribute('href')) {
hrefToDisplay = content.getAttribute('src');
}
$.colorbox({iframe:true, href:hrefToDisplay, title:item.caption});
}
}
}
});
The secret is to open the HTML page in an iframe.
Hope this helps!
thank you all for helping me previously with my Javascripting problems. My current problem is that I need to open & close a new window on an image's onMouseOver & onMouseOut, respectively, but if the new window onMouseOver == true then I don't want the new window to close.
I am sure there is a simple solution, but I can't seem to figure out a way to cancel the image's onMouseOut="closeDetails();" if the user hovers over the New Window. Below is most of the code I am dealing with. Thanks in advance for your help.
<body>
<img name="img1" id="img1" onMouseOver="windowDelay(this);"
onMouseOut="closeDetails();" src="images/127.jpg" height="240" width="166"/>
</body>
<script language="JavaScript" type="text/javascript">
// This opens the movie details pop-up after an
// half second interval.
function windowDelay(thatImg)
{
winOpenTimer = window.setTimeout(function() {openDetails(thatImg);}, 2000);
}
// This is the function that will open the
// new window when the mouse is moved over the image
function openDetails(thatImg)
{
// This creates a new window and uses the hovered image name as the window
// name so that it can be used in the that window's javascript
newWindow = open("", thatImg.name,"width=400,height=500,left=410,top=210");
// open new document
newWindow.document.open();
// Text of the new document
// Replace your " with ' or \" or your document.write statements will fail
newWindow.document.write("<html><head><title>Movies</title>");
newWindow.document.write("<script src='myDetails.js' type='text/javascript'>");
newWindow.document.write("</script></head>");
newWindow.document.write("<body bgcolor='white' onload='popUpDetails();'>");
newWindow.document.write("... SOME OTHER HTML....");
newWindow.document.write("</body></html>");
// close the document
newWindow.document.close();
}
// This is the function that will call the
// closeWindow() after 2 seconds
// when the mouse is moved off the image.
function closeDetails()
{
winCloseTimer = window.setTimeout("closeWindow();", 2000);
}
// This function closes the pop-up window
// and turns off the Window Timers
function closeWindow()
{
// If popUpHover == true then I do not want
// the window to close
if(popUpHover == false)
{
clearInterval(winOpenTimer);
clearInterval(winCloseTimer);
newWindow.close();
}
}
function popUpDetails()
{
// This will be used to prevent the Details Window from closing
popUpHover = true;
// Below is some other javascript code...
}
</script>
I would recommend against using a new browser window for this task. Try something like this:
var popup = {
open = function () {
if (this.element == null) {
// create new div element to be our popup and store it in the popup object
this.element = document.createElement('div');
this.element.id = "myPopup";
// you don't need a full html document here. Just the stuff you were putting in the <body> tag before
this.element.innerHTML = "<your>html</here>";
// Some bare minimum styles to make this work as a popup. Would be better in a stylesheet
this.element.style = "position: absolute; top: 50px; right: 50px; width: 300px; height: 300px; background-color: #fff;";
}
// Add it to your <body> tag
document.body.appendChild(this.element);
// call whatever setup functions you were calling before
popUpDetails();
},
close = function () {
// get rid of the popup
document.body.removeChild(this.element);
// any other code you want
}
};
// The element you want to trigger the popup
var hoverOverMe = document.getElementById("hoverOverMe");
// set our popup open and close methods to the proper events
hoverOverMe.onmouseover = popup.open;
hoverOverMe.onmouseout = popup.close;
That should do it. It's much easier to control than a new browser window. You will want to tweak the CSS yourself.
EDIT:
Here are instructions to do this with an actual window. To reiterate, using an actual window is not the best way to accomplish this task. A stylized div tag to look like a window is better because it offers more control, as well as standardized functionality across browsers. However, if you must use a window, here it is:
// You can use many principles from the example above, but I'll give the quick version
var popup;
var hoverOverMe = document.getElementById("hoverOverMe");
hoverOverMe.onmouseover = function () {
popup = window.open("path_to_content", "popup");
};
hoverOverMe.onmouseout = function () {
popup.close();
};
It works, but not very well (IMHO). If the user has their settings such that new windows open in new tabs (as I do), then a tab will open up. Javascript has no control over that. In Firefox, the new tab will open and gain focus, at which point it immediately closes because hoverOverMe had its onmouseout event fired (which obviously closes the window). I imagine you'd have this same problem with an actual window, too.