How can I make an element not visible after refresh - javascript

Basically I put a lightbox with a video in my website which shows at the beginning, you can skip it using a button or pressing "Esc" key, but what i want is it only shows once, I mean if I do a refresh on the site, or if I go back the the Home page, I want the div of the video no longer displays.
Here's what i tried to do
<article id="video_holder">
<iframe src="https://player.vimeo.com/video/123859666?autoplay=1&color=3551a4&title=0&byline=0&portrait=0&controls=0" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<a class="close_video"> <i class="fa fa-angle-double-right"></i> Saltar Video </a>
</article>
<script>
$('.close_video').click(function(){
$("#video_holder").fadeOut(500, function() {
// Here I tried to remove the window forever
$(this).remove();
});
});
</script>
Anyone knows how can I achieve it?

As other have suggested, the correct way to do this is with a cookie. Use the following functions to set and read the cookie:
function read_video_cookie(){
var name = "skip_video=";
var all_cookies = document.cookie.split(';');
for(var i = 0; i < all_cookies.length; i++){
var c = all_cookies[i];
while(c.charAt(0) == ' ')
c = c.substring(1);
if (c.indexOf(name) == 0)
return JSON.parse(c.substring(name.length, c.length));
}
return false;
}
function set_video_cookie(){
$skip_video = true;
var d = new Date();
d.setTime(d.getTime() + (365*24*60*60*1000)); // Cookie expires in 1 year
var expires = "expires=" + d.toUTCString();
document.cookie = "skip_video=" + "true" + "; " + expires + ";";
$('.close_video').click(function(){
$("#video_holder").fadeOut(500, function() {
$(this).remove();
});
});
}
Then, in your document ready function, check the value of the cookie and insert the video element if needed:
var $skip_video;
$(function(){
$skip_video = read_video_cookie();
if(!$skip_video){
$("#video_holder").append('<iframe src="https://player.vimeo.com/video/123859666?autoplay=1&color=3551a4&title=0&byline=0&portrait=0&controls=0" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe><a class="close_video"> <i class="fa fa-angle-double-right"></i> Saltar Video </a>');
} else {
$("#video_holder").fadeOut(500, function() {
$(this).remove();
});
}
set_video_cookie();
});
Updated:
This method should remove the delay you're dealing with. You should also change your markup to:
<article id="video_holder"></article>

I'd suggest sessionStorage which acts like a document store on the user's browser. So you'd do:
$('.close_video').click(function(){
$("#video_holder").fadeOut(500, function() {
sessionStorage.setItem('viewed_my_video', true);
$(this).remove();
});
});
I would also encourage you to use javascript to render the video in as oppose to removing it from the dom. which will allow you to do something like:
if(!sessionStorage.getItem('viewed_my_video')) {
$('#video-holder').append('<iframe src="https://player.vimeo.com/video/123859666?autoplay=1&color=3551a4&title=0&byline=0&portrait=0&controls=0" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>');
}
There are betters ways of rendering html via javascript but figure that is outside the scope of this question. ( But if you're curious checkout underscore / lodash / handlebars ).
As others suggested cookies are another way to go about this. I favor sessionStorage over cookies because it's easier to use vs parsing out a long string. Here's a great StackOverflow answer on the differences: What is the difference between localStorage, sessionStorage, session and cookies?

Since you're using jquery already, there's a plugin which makes getting and setting cookies much easier:
https://github.com/carhartl/jquery-cookie
To set the cookie:
$.cookie('myCookie', 'value');
To then, get the cookie:
$.cookie('myCookie');
Then, on page load, you can show your video if it's set; this would require you to keep the video hidden by default. Using an inline style (if you want): style="display:none":
Then, on document ready, you should show it if the cookie's not set:
$( document ).ready(function() {
if( !$.cookie('myCookie') ){
$("#video_holder").show();
$.cookie('myCookie', 'watched');
}
}
Also, you'll probably want to set autoPlay in your vimeo URL to false. I'm not sure how it behaves if the container isn't visible.

Related

Add video to page on Button click

I am a beginner JS user, and I am trying to get a video to play on fullscreen and replace an invisible div further down on the page. I started with a guide from Chris Ferdinandi.
In his guide, the video replaces the image that is clicked. I would like to have the div later down on the page to be replaced on the click.
Any guidance would be great!
HTML
<a data-video="480459339" class="stylsheetref" href="#" target="">Watch the Tour</a>
<div id="video-replace"></div>
Javascript (modified from this guide)
<script>
if (!Element.prototype.requestFullscreen) {
Element.prototype.requestFullscreen = Element.prototype.mozRequestFullscreen || Element.prototype.webkitRequestFullscreen || Element.prototype.msRequestFullscreen;
}
// Listen for clicks
document.addEventListener('click', function (event) {
//Set invisible Div (new code added by me)
var videonew = '#video-replace');
// Check if clicked element is a video link
var videoId = event.target.getAttribute('data-video');
if (!videoId) return;
// Create iframe
var iframe = document.createElement('div');
iframe.innerHTML = '<p>x</p><iframe width="560" height="960" src="https://player.vimeo.com/video/' + videoId + '?rel=0&autoplay=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>';
var video = iframe.childNodes[1];
// Replace the image with the video
event.target.parentNode.replaceChild(video, videonew);
// Enter fullscreen mode
video.requestFullscreen();
}, false);
</script>
There are problems in your code.
var videonew = '#video-replace'); there's an orphan ), since you are using this in the `replaceChild``method I assume you want the variable to reference to an element.
So change it to
var videonew = document.querySelector('#video-replace');
Pro tip: Using the Developer console during development can help you figure out such errors in your code.

Youtube Script Delay

I have a script that will pull the latest video from a youtube channel and embed it to my school page. It works but there are two issues.
One it doesn't immediately identify a recently posted video. Is there a delay from youtube before it syncs and the new posts can register?
Two the script runs but it does stop other video content on the page from displaying. Any idea why that might be?
I've looked it over and over and exhausted any searches I could think of.
Thanks for the help! Here is the code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<iframe id="youtube_video" width="400" height="215" frameborder="0" allowfullscreen></iframe>
<script>
var channelID = "UC0gcWgeEVOE7TDEKtLNnSuA";
$.getJSON('https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.youtube.com%2Ffeeds%2Fvideos.xml%3Fchannel_id%3D'+channelID, function(data) {
var link = data.items[0].link;
var id = link.substr(link.indexOf("=")+1);
$("#youtube_video").attr("src","https://youtube.com/embed/"+id + "?controls=1&showinfo=0&rel=0");
});
</script>
I am not 100% clear on what you are trying to achieve - but if you are trying to display MORE than 1 video, you currently only have a single #youtube_video element. Rather you would likely need to create an element for each index of the data array and create unique IDs such as
#youtube_video + link[i]
here's a Fiddle:
https://jsfiddle.net/e620tuy8/
var channelID = "UC0gcWgeEVOE7TDEKtLNnSuA";
$.getJSON('https://api.rss2json.com/v1/api.json?rss_url=https%3A%2F%2Fwww.youtube.com%2Ffeeds%2Fvideos.xml%3Fchannel_id%3D' + channelID, function(data) {
var container = $('.container');
for (var i = 0; i < data.items.length; i++) {
var link = data.items[i].link;
var id = link.substr(link.indexOf("=") + 1);
var iframe = '<iframe id="youtube_video_id_' + i + '" src="https://youtube.com/embed/' + id + '?controls=1&showinfo=0&rel=0" width="400" height="215" frameborder="0" allowfullscreen></iframe>'
container.append(iframe)
}
});
Found, the answer with a little more digging.
Thanks to Frank's answer here https://stackoverflow.com/a/43873099/5943182
Thank you to anyone who viewed.
I still don't know why the most recent wasn't being pulled in the above code, but the alternative method works wonderfully for me.

how to show the content of other websites in my website

I am looking for a code which does a simple task. below is the task
let's say my site is http://www.url.com
I want when my user go to this site they see a box on top of the page which shows my site name and also my contact details and also a countdown timer.
below this line I want to show the exact same website of few different URL and I want to set a timer as well so that these few websites rotate and that timer on top shows how long it is until the next refresh and next website. I want only this part of the webpage to refresh and I want the top line to be still.
http://i58.tinypic.com/s6t84h.jpg
you can see what I want in the image above.
I was told that it can be done using iframe but I don't know how to do it and I also don't want scroll
I appreciate if you could help me
I found this solution and it seems to be working. I just need the countdown timer and also I want to crop out let's say 200px of top of each website and like shift it up because one page doesn't show all the content I want unless using scrolling and I don't want that.
<!DOCTYPE html>
<html>
<body>
<div align="center" style="border:4px solid red ">
<div style="color:#0000FF">
<h3>some content<color:#0000FF/h3>
<h3>some more content<color:#0000FF/h3>
</div>
</div>
<iframe id="rotator" src="http://www.zcast.ir" width="100%" height="600" scrolling="no" border="0" ></iframe>
<script>
// start when the page is loaded
window.onload = function() {
var urls = [
"http://www.zcast.ir",
"http://www.tgju.org",
"http://www.on3.ir",
"http://www.goldinfo.ir",
"http://www.zarban.ir",
];
var index = 1;
var el = document.getElementById("rotator");
setTimeout(function rotate() {
if ( index === urls.length ) {
index = 0;
}
el.src = urls[index];
index = index + 1;
// continue rotating iframes
setTimeout(rotate, 5000);
}, 5000); // 5000ms = 5s
};
</script>
</body>
</html>
Yes absolutely you can do that using iframe
1) set iFrame scrolling attribute to no:
<iframe src="/default.asp" width="200" height="200" scrolling="no">
</iframe>
read more: iFrame attr (w3Schools)
2) setTimeout for the timer: - see more
3) Reload the iframe from parent window - see more
You can use style position:fixed; and top:0; to place the div on top of your page:
<div style="position:fixed;top:0;"> some content here </div>
so thats it! :)
You can use iframe but, be sure that target website may disallow iframe embed. You can use following code;
var websites = new Array(
"http://www.hurriyet.com",
"http://www.milliyet.com",
"http://www.amazon.com"
);
var counter = 0;
var sTimeOut = setInterval(function () {
var index = counter%(websites.length);
$("#website_div").html($('<iframe src="' + websites[index] + '" width="500" height="500" border="0" scrolling="no"/>' ));
counter++;
}, 5000);
Put your websites in list, and it will rotated.
Here is a working demo: Demo

JQuery Replaces Iframe Multiple Times

If you take a look at this page here, you'll see that I've created a bit of a Youtube video gallery. When it works, it should replace the video in the main section of the page (at the top) with the thumbnail that is clicked and the text on the right is also replaced with text related to that video.
The text replacement seems to be working perfectly but I'm experiencing an issue where during the swap, the iFrame seems to be getting placed multiple times and so the video plays 2-3 times.
The Javascript is below -- is this something I've missed?
<script>
function replaceVideo(id) {
originalSrc = jQuery("iframe", "#" + id).attr("src");
autoPlay = originalSrc + "&autoplay=1";
jQuery("iframe", "#" + id).attr("src", autoPlay);
video = jQuery(".video-wrap", "#" + id).html();
jQuery(".flex-video").html(video);
text = jQuery(".video-description", "#" + id).html();
jQuery(".vid_desc").html(text);
jQuery("iframe", "#" + id).attr("src", originalSrc);
}
jQuery(".video-list li").click(function() {
id = jQuery(this).attr("id");
replaceVideo(id);
});
jQuery(window).load(function() {
if(window.location.search.substring(1)) {
element = window.location.search.substring(1).split('&');
if (document.getElementById(element[0])) {
document.onload = replaceVideo(element[0]);
}
}
});
</script>
Thanks!
Run jQuery(".flex-video") this in your javascript console. You'll see there are THREE divs that have that class. So jQuery(".flex-video").html(video); this line of JS changes the inner HTML of 3 elements to be the iframe.
<div class="flex-video widescreen">
<iframe width="583" height="328" src="http://www.youtube.com/embed/TWmFCX40BQc?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>
</div>
You need to make the above div distinguishable from the other flex-video frames. Give the parent div an id or another class or something to query off of. Do that, and then you'd be fine.
EDIT: By the way, this code is wrong:
if(window.location.search.substring(1))
{
element = window.location.search.substring(1).split('&');
if (document.getElementById(element[0])) {
document.onload = replaceVideo(element[0]);
}
}
setting document.onload to a function call will call replaceVideo and set the onload property to whatever it returns, which is nothing. It may appear to work because the video plays, but that's just because you're calling the replaceVideo method. Setting your if to this, will probably be sufficient for you (unless you can explain why you're setting it to onload)
if(document.getElementById(element[0]))
replaceVideo(element[0]);

Rendering Youtube Video in a WYSIWYG

I am creating a custom WYSIWYG from scratch using JavaScript. All of it is working fine (like inserting pictures), but when I click on submit and the content gets added to my database, the YouTube video gets inserted like this:
<div><br></div><div><br><div><br></div></div>
I have created a JavaScript file that the WYSIWYG parses to:
function iImage(){
var imgSrc = prompt('Enter image location', '');
if (imgSrc != null){
richTextField.document.execCommand('insertimage', false, imgSrc);
}
}
function iVideo(){
var urlPrompt = prompt("Enter Youtube Url:", "http://");
var urlReplace = urlPrompt.replace("watch?v=", "embed/");
var embed = '<iframe src="'+urlReplace+'" allowfullscreen="true" width="480" frameborder="0" height="390">';
if($.browser.msie){
richTextField.document.createRange().pasteHTML(embed);
}else{
richTextField.document.execCommand("Inserthtml", false, embed);
}
}
function submit_form(){
var theForm = document.getElementById("blogForm");
theForm.elements["blogbody"].value = window.frames['richTextField'].document.body.innerHTML;
theForm.submit();
}
You can see that my iImage function works, but not my iVideo.
Can anyone help?
Just to let you know i have edited my script to this...
function iVideo(){
var urlPrompt = prompt("Enter Youtube Url:", "http://");
var urlReplace = urlPrompt.replace("http://www.youtube.com/watch?v=", "http://www.youtube.com/embed/");
var embed = '<iframe src="'+urlReplace+'" allowfullscreen="true" width="480" frameborder="0" height="390"></iframe>';
if($.browser.msie){
richTextField.document.createRange().pasteHTML(embed);
}else{
richTextField.document.execCommand("Inserthtml", false, embed);
}
}
but still no joy
I have got it. This is the code below
function iVideo(){
var urlPrompt = prompt("Enter Youtube Url:", "http://");
var urlReplace = urlPrompt.replace("watch?v=", "embed/");
var embed = '<iframe title="YouTube video player" src="'+urlReplace+'" allowfullscreen="true" width="480" frameborder="0" height="390">';
if(embed != null){
richTextField.document.execCommand("Inserthtml", false, embed);`
}
}
It working on my sites right now.
Ultimate
The reason you don't see a Youtube.com is because it will be added by you upon uploading. In the form where you write content you intend to upload to your site, You are to click on a Add Video link which will tricker off the first line in the code to popup a window requesting you to submit your Youtube video link, which looks something like http://youtube.com/theVideoLink. The link you add will then be placed where you have src="'+urlReplace+'" that is.
Well, I am a begginner at javascript, but I don't see anywhere were it adds youtube.com to it, all I see is the watch?v=.
As I said, a beginners opinion.
Are you able to first try a hardcoded/static version like below first?
- might be just syntax or one of your variables not set.
<script type="text/javascript">
function iVideo(){
var youtubeiframe='<iframe type="text/html" width="640" height="385" src="http://www.youtube.com/embed/AsbagZvkrbo" frameborder="0"></iframe>';
richTextField.document.execCommand ("insertHTML", false, youtubeiframe);
}
</script>

Categories