using jquery to insert javascript (for Quicktime) into a <div> - javascript

I'm pretty new to javascript and programming and have run into a brick wall with my project. I have a div which contains the javascript to embed a quicktime player, when the page is first loaded no .mov file is pointed at by the page so a placeholder div is 'unhidden' and the player div is set to style.display = 'none'.
So far so good, the user then enters the name of the new movie, the placeholder div is hidden and the player div is unhidden. My problem is that the javascript in the player div didn't run when the div was made visible, if I make the script for the player into a seperate function then call it when the player div is unhidden then the player runs full screen and not in the div.
I've tried using jquery to add the javascript into the div after the div is made visible but can't seem to get $("#player").load(somescript) or $("#player").html(htmlwithjavain) to add the script.
I know the player div contenst can be changed as I can use $("#player").empty(); and $("#player").html(); to manipulate it.
Thanks for reading, hope you can help
Here's the relevant code:-
<html>
<head>
<title>Browse Media Player</title>
<link rel="stylesheet" type="text/css" href="CSS/browser.css" />
<script type="text/javascript">
<!--
var userinterrupt=false;
var runonce=false;
var currentfile;
var basemediapath = "http://10.255.10.71/IsilonBrowse/movfiles/";
var playerheight = 750;
var playerwidth = 900;
var currenttc;
var basetime;
var baseduration;
var currentduration = "no tc available";
var tcoffset = 35990;
var playspeed = 1;
var boolisplaying=true;
var boolonslide=false;
//function to fire off other methods when the DOM is loaded
//Use in place of body onload, using jquery library
//
$(document).ready(function()
{
//showEvents('jquery running');
showhideplayer(null);
});
//-->
</script>
</head>
<body onload="forceslider(); timecode()">
<div class="container">
<div id="timecode_container">
<div class="tc_overlay"></div>
<div id="timecode" class="timecode"></div>
</div>
<div id="player" class="playerdiv" style="display:none;">
**javascript for player goes here...**
</div>
<div id="noclipoverlay" class="playerdiv" style="display:none;">
<p>No media loaded...
</div>
<div id="noclipoverlay2" class="playerdiv" style="display:none;">
<p>loading media....
</div>
</div>
<div id="loadstatus"></div>
<div id="alerts"></div>
</body>
</html>
Now the mainstuff.js file which should add the javascript code:-
//function to switch the player div and mask div is no media file is
//defined in the 'currentfile' variable
//
function showhideplayer(state)
{
if (!currentfile)
{
showEvents('wtf no media');
document.getElementById("player").style.display = 'none';
document.getElementById("noclipoverlay").style.display = 'block';
}
else if (currentfile)
{
document.getElementById("player").style.display = 'block';
document.getElementById("noclipoverlay").style.display = 'none';
showEvents('valid media file');
}
}
//end of showhideplayer
//function to change movie files, note SetResetPropertiesOnReload must be set to false
//otherwise the B'stard player will default all attributes when setURL runs
//
function changemovie(newmovie)
{
oldfile = currentfile;
if (newmovie == currentfile)
{
showEvents('same file requested so no action taken');
return;
}
if (newmovie != currentfile)
{
showEvents('changing movie');
//switch the divs around to hide the 'no media slide'
document.getElementById("player").style.display = 'block';
document.getElementById("noclipoverlay").style.display = 'none';
}
showEvents('movie changed to: '+newmovie);
currentfile=newmovie;
if (!oldfile)
{
$("#player").empty();
showEvents('the old media file was blank');
$("#player").load("/path/loadplayer.js");
}
document.movie1.Stop();
document.movie1.SetResetPropertiesOnReload(false);
document.movie1.SetURL(currentfile);
//showEvents('movie changed to: '+newmovie);
if (boolisplaying)
{
document.movie1.Play();
}
}
[EDIT] and here's the contents of loadplayer.js:-
var movie1 = QT_WriteOBJECT(
currentfile, playerwidth, playerheight, "",
"controller","false",
"obj#id", "movie1",
"emb#id","qt_movie1",
"postdomevents","True",
"emb#NAME","movie1",
"enablejavascript","true",
"autoplay","true",
"scale","aspect",
"pluginspage","http://www.apple.com/quicktime/download/"
);

Without knowing the content of your loadplayer.js file, it will be difficult to give you a solution.
For example, if the script attempts to do a document.write() after the page has loaded, it will create a new page, overwriting the current page. Is that what you mean when you say the quicktime movie is running full screen?
Also it is generally not a good idea to load a SCRIPT element and insert it as HTML. When you add HTML to the page, jQuery finds all the SCRIPT elements and evaluates them in a global context, which might give you unexpected results.

Use QT_GenerateOBJECTText_XHTML or QT_GenerateOBJECTText from AC_QuickTime.js if you'd like to return a string.

Related

Adding a close function that doesn't reposition page

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)

Get an element in an <embed> tag

I'm a beginner in Javascript and i'm trying to get an element from an embed tag. This embed tag contains a pdf.
I want to get the button "next page" from the pdf viewer, and simulate a click on it, in order to automaticly scroll to the next page of the pdf.
My HTML code is something like this (really simplified) :
<html>
<body>
<div id="display-zone">
<embed id="myPdf" src="./myPdf.pdf">
#document
<html>
<body>
<!-- The button I want to get in my JavaScript -->
<button id="next" class="toolbarButton pageDown"></button>
</body>
</html>
</embed>
</div>
</body>
</html>
My JS code to print the pdf viewer on the web page :
affichage.innerHTML = "<embed class=\"media\" id=\""+ongletsMedias[i].firstChild.data+"\" src= \""+ongletsMedias[i].firstChild.data+"\" width= \"1000\" height= \"800\">";
// ongletsMedias[i].firstChild.data equals to "myPdf"
t = 5000; // time before starting pdfDefile()
setTimeout(pdfDefile,t,ongletsMedias[i].firstChild.data,i,1); //call the function to scroll pdf pages
And finally my function pdfDefile() that I'm calling in order to scroll the pdf pages :
function pdfDefile(dir,i,page) {
var xhttp = new XMLHttpRequest();
var t = 0;
xhttp.onreadystatechange = function() {
var checkbox = document.getElementById('checkbox');
if (this.readyState == 4 && this.status == 200 && checkbox.checked) {
document.getElementById("span").innerHTML = this.responseText; // display the number of pages of my pdf
var t = 5000;
if (page < parseInt(this.responseText)) { //test for recursive call
/*HERE is where I want to get the "next" button */
setTimeout(pdfDefile,t,dir,i,page+1);// recall this function while there is a next page to display
} else {
setTimeout(jouerMedia,t,i+1);// call the main fuction, no problem here
}
}
};
xhttp.open("GET", "nbPagesPDF.php?pages="+dir, true);
xhttp.send();
}
I already look at an existing topic (Get element in embed tag), but I can't make it work in my JS.
So please, can you help me to make my code great again (may it have been ;-) ) ?
Regards
Try
var embed = document.getElementById('myPdf');
// Wait for document to load inside embed element
embed.on('load', function() {
embed.getElementById('next').click();
});
(I am using jQuery in this example for adding the event listener, not sure if you are using it on your project?)
Without jQuery you could do:
var embed = document.getElementById('myPdf');
embed.onload = function() {
embed.getElementById('next').click();
};
It might be possible you can not trigger a click event on that button since a user action often must have taken place to trigger click's from js.

How to make a simple slideshow in JS?

I'm trying to make a simple slideshow with JavaScript.
Here is my index.html
<body>
<h1>Slideshow example</h1>
<button onclick="slideshow.timer()">Next slide</button>
<div id="container"></div>
<script src="slide.js"></script>
</body>
And here is slide.js
var slideshow = {
sliderImages: ["img/img1.png", "img/img2.png"],
timer: function() {
this.sliderImages.forEach(function(img) {
var container = document.getElementById('container');
var image = document.createElement('img');
container.appendChild(image);
image.src= img;
})
}
}
If I click the "next slide" button, I see both of the images. It loops through the whole array. How could I make it loop through the array just once, when clicking the button?
I tried adding container.innerHTML = ''; so that the previous image would be removed when adding the next image, but that resulted it showing immidietly the image in sliderImages[1]. Am I approaching this whole thing wrong?
I updated your code. It is not the best way to write it but I just modified your example to show you the problem. The problem is your timer function which is just going through all the elements in the array at once. Instead what you may want to do is add some delay.
var slideshow = {
sliderImages: ["img/img1.png", "img/img2.png"],
currentImgIndex: 0,
timer: function() {
if (this.currentImgIndex < this.sliderImages.length ) {
var image = document.getElementById('img');
image.src= this.sliderImages[this.currentImgIndex];
this.currentImgIndex++;
setTimeout(function (){ slideshow.timer()}, 2000)
} else {
alert("no more images");
}
}
}
<body>
<h1>Slideshow example</h1>
<img id="img"/>
<button onclick="slideshow.timer()">Next slide</button>
<div id="container"></div>
<script src="slide.js"> </script>
</body>
If you are going to change the images only when the button is clicked, you don't need the forEach loop. If you are going to change images without user interaction then you need the loop but you need setInterval also.

How to Expand / Collapse a section of a Web Site and also change the image using JavaScript

EDIT #1
Thanks to the 2 users who responded, their solutions worked great! Something I forgot to mention in the original post was, Is there any way to adjust the user's view so that when the expanded section is collapses by the user, their "view" (or the actual web page) can adjust up to an anchored spot?
ORIGINAL POST
I've got a section of a website that I want to first be collapsed and not able to be viewed by the user. Then, when they hit an arrow on the screen, the hidden content will then display AND the image needs to change from a "down" arrow to an "up" arrow.
I'm able to do this with the below code right now but I have to have two arrows. Can anyone help so that I only have one arrow on screen and it changes based on when the user clicks on it? I'd also like this to be able to be done an infinite amount of times by the user (ie if the user clicks the "down" arrow, the section expands and the arrow changes to an "up" arrow but then when the user hits that "up" arrow the section collapses and the arrow changes back to a "down" arrow. Possible?
<script language="JavaScript" type="text/javascript">
<!--
function sizeTbl(h) {
var tbl = document.getElementById('tbl');
tbl.style.display = h;
}
// -->
</script>
<br>
<img src="up_arrow.png">
<img src="down_arrow.png">
Thanks for any help!
I have added your code and created a jsfiddle for you...
changed code:-
function sizeTbl(h) {
var tbl = document.getElementById('container');
tbl.style.display = h;
if (h == "block") {
document.getElementById('down').style.display = 'none';
document.getElementById('up').style.display = 'block';
} else {
document.getElementById('up').style.display = 'none';
document.getElementById('down').style.display = 'block';
}
}
working example:-
click to see example:-http://jsfiddle.net/XUjAH/1089/
thanks
I've taken out the parameter from your sizeTbl method
Then I'm getting the src property of the image (note I've given it an ID). Depending on the src we can show/hide the table and change the image property
Here's a jsFiddle
<script language="JavaScript" type="text/javascript">
<!--
function sizeTbl() {
var tbl = document.getElementById('tbl');
var icon = document.getElementById('toggle-table');
if (icon.src === 'down_arrow.png'){
tbl.style.display = 'block';
icon.src = 'up_arrow.png';
}
else {
tbl.style.display = 'none';
icon.src = 'down_arrow.png';
}
}
// -->
</script>
<br>
<img src="down_arrow.png" id="toggle-table">
You've added some extra requirements to your question. You've tagged jQuery and this is the easiest solution for this scenario.
Remove the javascript:sizeTbl() from your <anchor> tag. This is known as inline JS and isn't recommended because it means you are mixing your presentation code with your business logic.
You make the <anchor> tag act like a normal anchor tag and attach a click event in the document's ready event.
function sizeTbl() {
var tbl = document.getElementById('tbl');
var icon = document.getElementById('toggle-table');
if (icon.innerText === 'show') {
tbl.style.display = 'block';
icon.innerText = 'hide';
} else {
tbl.style.display = 'none';
icon.innerText = 'show';
}
}
$(document).ready(function(){
$('#sizeTbl').on('click', sizeTbl);
});
I've created a new jsFiddle that demonstrates this.
Notes:
You need to be using jQuery for this to work
Note that I've given the <anchor> tag an ID. This is so that I can locate it in code
If you have any other comments, the etiquette on SO is to ask new questions. The answers get too long and complicated otherwise

Collapsing JavaScript/HTML div on page load?

I need help collapsing a collapsible div on page load.
I'm using this JavaScript code:
<script type="text/javascript">
function switchMenu(obj) {
var el = document.getElementById(obj);
if ( el.style.display != "none" ) {
el.style.display = 'none';
}
else {
el.style.display = '';
}
}
document.getElementById('aboutme').style.display = 'none';
</script>
to collapse HTML div id="aboutme" when the <a ...>about me</a> is clicked:
<div class="container">
about me
<div id="aboutme">
sample text to be expanded and collapsed
</div>
</div>
I can't get the page to close my div#aboutme on page load.
I want this page to load with my div collapsed.
I thought that the JS line
document.getElementById('aboutme').style.display = 'none';
should do the trick but it doesn't. What am I doing wrong?
Thanks for your help.
If you want your div to load collapsed, simply write the following
<div id="aboutme" style="display:none">
sample text to be expanded and collapsed
</div>
This should resolve the problem.
However, if you are still interested in the JavaScript solution keep reading.
As you said I can't get the page to close my div#aboutme on page load - the problem is that you are not using "onload" event.
Simply put the line document.getElementById('aboutme').style.display = 'none'; in your body's onload attribute..
something like this
<body onload="document.getElementById('aboutme').style.display = 'none';">
...
</body>
and you should see the results with JavaScript. I recommend you use "style" method instead. much better.
Exactly how do you make that JS run on window load? It may simply run before the page is rendered
Does clicking on the link work? if it does, that would prove that the issue is simply the loading sequence
The easiest solution would be to place your code at the very end of your HTML file, just before the closing </body> tag. The code below is more generic, and can be placed anywhere. Note that to toggle the link back on I set the display to 'inline' (or block, i.e. whatever it was before - you may want to save that to a variable to be sure)
<script type="text/javascript">
function switchMenu(id) {
var el = document.getElementById(id);
if ( el.style.display != "none" ) {
el.style.display = 'none';
}
else {
el.style.display = 'inline'; //or block - i.e. whatever it is rendered by
}
}
//add to the window onload event
if( window.addEventListener ){
window.addEventListener( 'load', function(){ switchMenu('aboutme')}, false);
} else if (window.attachEvent) {
window.attachEvent("onload", function(){ switchMenu('aboutme') } );
}
</script>

Categories