Basically I've an html file which contains all the elements needed for my web app videos.
So Now I'm in a position where I need to counts numbers of user videos and show them to user.
Script:
for(var i=1;i<(s.length)-2;i++){
$('#vid_c_'+i).append('<div id="vid_'+i+'"></div>');
$("<div>").load("video_content.html",function(index) {
return function() {
$(this).find('.video').attr({id: 'video_id_'+index});
$("#vid_"+index).append($(this).html());
}
})(i));
var myElem = document.getElementById('video_id_'+i);
if (myElem === null) alert('does not exist!');
$(this).find('#video_id_'+i).attr('src', video_src[i-1]);
console.log(video_src[i-1]+ " "+"#video_id_"+i);
}
So Basically What happen is that for loop creates (s.length)-2 which is the amount of user videos and load video elements in a div and for each video it specifies a unique ID increased by value of i. So far it works fine now I need to specify video source which is assigned in video_src[i-1].
As you can see I've myElem which test if the element exists or not And the result is the it alerts saying does not exist even though I have loaded my video element And I can see it in my browser inspect mode with the Id assigned fine which makes the next line for assigning video source not to work. I also have tried:
$(this).find('.video').attr({id: 'video_id_'+index, 'src': video_src[i-1]});
and inside .load() function video_src shows to be undefined.
In my console.log it show the exact video source as needs to be assigned.
So I would really appreciate if someone tell me how to assign video source each time the video element is loaded from my video_content.html file.
Anyway, Based on all my research And tests I had I came up that inside .load(function(){}); I can't access data of current page because it's executing script from my video_cntent.html file. So In order to set the source of my video element I created two for Loops:
for(var i=1;i<(s.length)-2;i++){
var video_src = video_source[i-1];
localStorage.setItem('Item_'+i, video_src);
$('#vid_c_'+i).append('<div class="move_2" id="vidi_'+i+'"></div>');
}
for(var i=1;i<(s.length)-2;i++){
$("<div>").load("video_cntent.html",(function(index) {
return function() {
var retrieveitem = localStorage.getItem('Item_'+index);
$(this).find('#vidi_'+index).attr({id: 'video_id_'+index, 'src': retrieveitem});
}
})(i));
}
As you can see in my first loop I am accessing video_source and storing it in localStorage and it stores all my video sources based on value of i.
And in my second Loop I'm retrieving all the stored data again based on value of i and using it to set source of my video element.
Related
I currently only know javascript. But the thing is I looked up how to do it and some people talk about something called localStorage. I have tried this and for some reason when I jump to a new page those variables aren't kept. Maybe I am doing something wrong? I jump to a new page via
and all I want do do is select a certain image. take that image to a new page and add it to that page.
I tried using the localStorage variables and even turning it into JSON.stringify and doing JSON.parse when trying to call the localstorage to another script. It didn't seem to work for me. Is there another solution?
This is some of my code. There are two scripts.
document.querySelectorAll(".card").forEach(item => {
item.addEventListener("click", onProductClick);
})
var div;
var productImg;
var ratingElement;
var reviewCount;
var price;
function onProductClick(){
// This took a week to find out (this.id)
// console.log(this.id);
div = document.getElementById(this.id);
productImg = div.getElementsByTagName('img')[0];
ratingElement = div.getElementsByTagName('a')[2];
reviewCount = div.getElementsByTagName('a')[3]
price = div.getElementsByTagName('a')[4];
console.log(div.getElementsByTagName('a')[4]);
var productData = [div, productImg,ratingElement,reviewCount,price];
window.localStorage.setItem("price", JSON.stringify(price));
}
function TranslateProduct(){
console.log("Hello");
}
This is script 2
var productPageImage = document.getElementById("product-image");
var myData = localStorage['productdata-local'];
var value =JSON.parse(window.localStorage.getItem('price'));
console.log(value);
// function setProductPage(img){
// if(productImg != null){
// return;
// }
// console.log(window.price);
// }
To explain my thought process on this code in the first script I have multiple images that have event listeners for a click. I wanted to Click any given image and grab all the data about it and the product. Then I wanted to move that to another script (script 2) and add it to a dynamic second page. yet I print my variables and they work on the first script and somehow don't on the second. This is my code. in the meantime I will look into cookies Thank you!
Have you tried Cookies
You can always use cookies, but you may run into their limitations. These days, cookies are not the best choice, even though they have the ability to preserve data even longer than the current window session.
or you can make a GET request to the other page by attaching your serialized object to the URL as follows:
http://www.app.com/second.xyz?MyObject=SerializedData
That other page can then easily parse its URL and deserialize data using JavaScript.
you can check this answer for more details Pass javascript object from one page to other
I have an internet radio station and I need a script that will display a picture of the current song in a particular dvi with an id. The image is automatically uploaded via ftp to the server each time the song changes..
HTML:
<div id="auto"></div>
JS:
$ (document).ready(function() {
$('#auto').html('<img src="artwork.png"></img>');
refresh();
});
function refresh() {
setTimeout (function() {
$('#auto').html('<img src="artwork.png"></img>');
refresh();
}, 1000);
}
I tried this, but all I get is that the image is loaded, but in case of a change, I have to manually refresh the whole page again..
I'll point out multiple things here.
I think your code is just fine if you are going for the setTimeout recursive calls instead of one setInterval action to repeat it.
File Caching
your problem is probably the browser's cache since you are using the same image name and directory all the time. browsers compare the file name and directory and to decide to load it from its cache or else it will request it from the server. there are different tricks you can do to reload the image from the server in this particular case.
Use different file names/directories for the songs loaded dynamically
Use a randomized GET query (e.g. image.png?v=current timestamp)
Your method for switching
you are replacing the file with FTP, I wouldn't recommend that. maybe you should have all your albums and thumbnails uploaded to the server and use a different dynamic switching for efficiency and less error proneness and will help you achieve method #1 in the previous section better.
Loading with constant refresh
I would like to highlight that if you are using nodeJs or nginx servers - which are event based - you can achieve the same functionality with much less traffic. you don't need a refresh method since those servers can actually send data on specific events to the browser telling it to load a specific resource at that time. no constant refresh is required for this.
You consider your options, I tried to be as comprehensive as I could
At the top level, browser cache the image based on its absolute URL. You may add extra query to the url to trick browser that is another new image. In this case, new URL of artist.png will be artist.png?timestamp=123
Check this out for the refresh():
function refresh() {
setTimeout (function() {
var timestamp = new Date().getTime();
// reassign the url to be like artwork.png?timestamp=456784512 based on timestmap
$('#auto').html('<img src="artwork.png?timestamp='+ timestamp +'"></img>');
refresh();
}, 1000);
}
You may assign id attribute to the image and change its src url
html
<img id="myArtworkId" src="artwork.png"/>
js in the refresh method
$('#myArtworkId').attr('src', 'artwork.png?timestamp=' + new Date().getTime());
You can use window.setInterval() to call a method every x seconds and clearInterval() to stop calling that method. View this answer for more information on this.
// Array containing src for demo
$srcs = ['https://www.petmd.com/sites/default/files/Acute-Dog-Diarrhea-47066074.jpg',
'https://www.catster.com/wp-content/uploads/2018/05/Sad-cat-black-and-white-looking-out-the-window.jpg',
'https://img.buzzfeed.com/buzzfeed-static/static/2017-05/17/13/asset/buzzfeed-prod-fastlane-03/sub-buzz-25320-1495040572-8.jpg?downsize=700:*&output-format=auto&output-quality=auto'
]
$i = 0;
$(document).ready(function() {
$('#auto').html('<img src="https://images.pexels.com/photos/617278/pexels-photo-617278.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"></img>');
// call method after every 2 seconds
window.setInterval(function() {
refresh();
}, 2000);
// To stop the calling of refresh method uncomment the line below
//clearInterval()
});
function refresh() {
$('#auto').html('<img src="' + $srcs[$i++] + '"></img>');
// Handling of index out of bound exception
if ($srcs.length == $i) {
$i = 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="auto"></div>
We're using an external scrubber (a UI element that is not the default seek bar) for seeking (via jquery ui draggable) and it is not updating the jwplayer when it should be.
Synopsis of our code:
$('#scrubber').draggable({
// ...
stop: function (event, ui) {
$('#scrubber').draggable('enable');
var intSecFromEnd,
intSeek,
intTotalTime = 0,
intScrubPosition = ui.position.left,
intScrubTime = intScrubPosition;
// Find which video in the playlist to use
$.each(playlist, function (i, obj) {
intTotalTime += parseInt(obj.duration);
if (intTotalTime > (intScrubTime)) {
intSecFromEnd = intTotalTime - parseInt(intScrubTime);
intSeek = Math.floor((parseInt(obj.duration) - intSecFromEnd));
jwplayer('videoPlayer').load(playlist);
jwplayer('videoPlayer').playlistItem(i);
jwplayer('videoPlayer').seek(intSeek);
jwplayer('videoPlayer').pause();
/*
Play the video for 1 second to refresh the video player, so it is correctly displaying the current point in the video
Does not work either
*/
// setTimeout(function () {
// jwplayer('videoPlayer').pause();
// }, 1000);
return false;
}
});
}
});
You'll notice the key bit:
jwplayer('videoPlayer').load(playlist);
jwplayer('videoPlayer').playlistItem(i);
jwplayer('videoPlayer').seek(intSeek);
jwplayer('videoPlayer').pause();
When i put this into the console directly with an integer value where intSeek is it works exactly as it should, so I'm puzzled where the disconnect might be.
variation (that only works one one item in the playlist)
This works on the first member of the playlist only because the seek() function is defaulted to element 0 in the playlist.
jwplayer('videoPlayer').load(playlist);
jwplayer('videoPlayer').seek(intSeek);
jwplayer('videoPlayer').pause();
Naturally, it would stand to reason that jwplayer('videoPlayer').playlistItem(i) would retrieve the item at the index we want and, according to the docs, should:
Start playback of the playlist item at the specified index.
but, as this is effectively what is in the first example, it doesn't work.
Notes
When triggering the .seek() method externally from the player, the onSeek() method never gets fired by the jwplayer.
putting in the following, the jwplayer onReady event never gets fired. jwplayer(strVideo).playlistItem(i).onReady({ console.log('ready'); });
we're trying onPlaylistItem(index).seek(seconds) but this doesn't works.
This work only on active playlistitem and -of course- only about first file.
We're trying to use a pre-loaded playlist with seek button for every item of playlist.
We use a playlist with more files and the user can go to a specific file and second clicking a button that call:
jwplayer().onPlaylistItem(<index_file>).seek(seconds);
This jump to the seconds but not to the correct playlist item.
With a previuos test using "playListItem" player jump to the correct file but start from beginning and not seek to seconds. (but work only in html5 mode and not with flash).
Now we've tested this code
<a onclick='var only_once =false;jwplayer().playlistItem(1);jwplayer().onPlay(function () {
if (only_once == false) {
only_once = true;
jwplayer().seek(60);
}
});' class="btn">HLS play 2nd file at 1 min</a>
but this solution works only in Flash mode and not in html 5 mode player!
I'm having some issues working with the Sound Cloud custom html5 player (http://developers.soundcloud.com/docs/custom-player) specifically on internet explorer (tested on version 7, 8 and 9).
It seems whenever the player is created (right now this is dynamically through JS) it is running into an error with a function in the "sc-player.js" file (provided by sound cloud here).
The error is "Unable to get the value or property 'id': object null or undefined". This is the code that messes up: line 640 character 9
// selecting tracks in the playlist
$('.sc-trackslist li').live('click', function(event) {
var $track = $(this),
$player = $track.closest('.sc-player'),
trackId = $track.data('sc-track').id,
play = $player.is(':not(.playing)') || $track.is(':not(.active)');
if (play) {
onPlay($player, trackId);
}else{
onPause($player);
}
$track.addClass('active').siblings('li').removeClass('active');
$('.artworks li', $player).each(function(index) {
$(this).toggleClass('active', index === trackId);
});
return false;
});
I understand this is trying to find the id of a track on the generated list, however I have hidden this list on the page, so really shouldn't that click event should not even fire? I have tried removing the click event all together but that seems to cause a number of other issues with the player.
Just wondering if anyone else has experienced this or knows how to get around it?
EDIT -
I manually attached "test" data the track. And this seems to solve that first error, but of course brings up another. This time the same error is spat out for this line (in the sc-player.js file):
getPlayerData = function(node) {
return players[$(node).data('sc-player').id];
}
This is the code I use to call the player, the track argument being the link to a music tracks soundcloud page, and #player being the empty div its being created on top of:
function init_player(track,title) {
$('.open #player').scPlayer({
links: [{url: track, title: title}],
beforeRender : function(tracksData) {
$scplayer = $(this);
$('.sc-trackslist li, .sc-trackslist li a').data({ id: track});
}
}
When the user wants to change to another section of music, I then have another function which empties the container div, appends #player to it (because it was overwritten by the soundcloud player), and re runs the above function.
My issue is on the second time the init_player function is run, I get the error.
Sorry for the delayed response!
This line is wrong:
trackId = $track.data('sc-track').id,
I can't help you more then that because I need the rest of the code...
So, I am building a web app that has a div with text that changes on various user actions (it's stepping through an array of pieces of text). I'm trying to add audio to it, so I made another array with the sound files in the appropriate positions:
var phrases=['Please hand me the awl.','etc1','etc2','etc3'];
var phrasesAudio=['awl.mp3','etc1.mp3','etc2.mp3','etc3.mp3'];
And on each action completion, a 'counter' variable in incremented, and each array looks for the object at that counter
var audio = document.createElement("audio"),
canPlayMP3 = (typeof audio.canPlayType === "function" &&
audio.canPlayType("audio/mpeg") !== "");
function onAction(){
correct++;
document.getElementById('speech').innerHTML=phrases[correct];
if(canPlayMP3){
snd = new Audio(phrasesAudio[correct]);
}
else{
snd = new Audio(phrasesAudioOgg[correct]);
}
snd.play();
}
(the text replaces a div's HTML and I use .play() for the audio object)...usually works okay (and ALWAYS does in a 'real' browser), but on the iPad (the actual target device) after a few successful iterations, the TEXT continues to progress accurately, but the AUDIO will hiccup and repeat a sound file one or more times. I added some logging and looking there it reports that it's playing screw.mp3 (just an example, no particular file is more or less error prone), but in actuality it plays screwdriver.mp3 (the prior file, if there is an error, the audio always LAGS, never LEADS)...because of this I am thinking that the problem is with my use of .play()...so I tried setting snd=null; between each sound, but nothing changed...Any suggestions for how to proceed? This is my first use of audio elements so any advice is appreciated. Thanks.
edit: I've also tried setting the files with snd.src (based on https://wiki.mozilla.org/Audio_Data_API) and this caused no audio to play
for iPad you need to call snd.load() before snd.play() - otherwise you get "odd" behaviour...
see for some insight:
http://jnjnjn.com/187/playing-audio-on-the-ipad-with-html5-and-javascript/
Autoplay audio files on an iPad with HTML5
EDIT - as per comment from the OP:
Here https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox you can find a tip on halting a currently playing piece of media with
var mediaElement = document.getElementById("myMediaElementID");
mediaElement.pause();
mediaElement.src = "";
and, following that with setting the correct src, load(), play() works great