Using JavaScript Variables in HTML code - javascript

I'm pretty new to JavaScript.
I'm trying to make a YouTube 2.0 html thing, (interesting learning experience). I want it to be so that you click on the "load video" link and it asks you the link to the actual youtube video. Then, when you paste it in, it displays the video on the page.
My code is
<h1 style="background-color: red; color: white; font-family: helvetica; padding: 20px 20px 20px 20px;">Youtube 2.0</h1>
Load video
<script>
var theVideoLink;
var openVideo = function() {
var videoLink = prompt("Video link on YouTube.com");
theVideoLink = videoLink;
};
window.onload = function() {
document.getElementById("myLink").innerHTML=theVideoLink;
}
</script>
<iframe width="1120" height="630" src="myLink" frameborder="0" allowfullscreen></iframe>
If you have any ideas on how I can insert the JavaScript variable into my iframe src tag, please tell me. Thanks!

You can't change iframe src but we can replace your iframe with new one.
Note, I have set your iframe ID as myLink, replacing the src attribute.
<h1 style="background-color: red; color: white; font-family: helvetica; padding: 20px 20px 20px 20px;">Youtube 2.0</h1>
Load video
<iframe width="1120" height="630" id="myLink" frameborder="0" allowfullscreen></iframe>
<script>
openVideo = function() {
var videoLink = prompt("Video link on YouTube.com");
var iframe=document.getElementById('myLink');
var new_iframe = document.createElement("iframe");
new_iframe.src=videoLink;
let attr;
let attributes = Array.prototype.slice.call(iframe.attributes);
while(attr = attributes.pop()) {
if (attr.nodeName!='src')
new_iframe.setAttribute(attr.nodeName, attr.nodeValue);
}
iframe.parentNode.replaceChild(new_iframe, iframe);
}
</script>
Make sure to embed the embed link, in this format:
https://www.youtube.com/embed/MEVYajbHmb4
Working JS fiddle :
https://jsfiddle.net/aa0kzqsz/2/

In your code, the iframe is wrong. You need to specify "myLink" as id not as src.
Then you need to transform the youtube link (which is like "https://www.youtube.com/watch?v={videoId}") into the iframe link (which is like "https://www.youtube.com/embed/{videoId}"). To achieve this you need to learn about regexp. The following will work:
var ytLink = prompt('Give me a youtube link please !');
var iframe = document.getElementById('youtube');
var ytId = ytLink.match(/v=([-A-Za-z]+)/)[1];
iframe.src = 'https://www.youtube.com/embed/' + ytId;
<iframe width="560" height="315" src="" id="youtube" frameborder="0" allowfullscreen></iframe>
I recommend you to learn more about regex on the MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

This code navigates the <iframe> to URL that typed in prompt dialog.
<h1 style="background-color: red; color: white; font-family: helvetica; padding: 20px 20px 20px 20px;">Youtube 2.0</h1>
Load video
<script>
var openVideo = function() {
var videoLink = prompt("Video link on YouTube.com");
window.open(videoLink, "myLink");
}
<iframe width="1120" height="630" name="myLink" frameborder="0" allowfullscreen></iframe>
Update: This code only navigates <iframe> to given URL. You should probably use Youtube embed options instead of this.

You must use embed link instead of full link
like: https://www.youtube.com/embed/videoID
var openVideo = function() {
var videoID = prompt("Video id on YouTube.com");
var embed = 'https://www.youtube.com/embed/'
document.getElementById("myFrame").src=embed+videoID;
};
<h1 style="background-color: red; color: white; font-family: helvetica; padding: 20px 20px 20px 20px;">Youtube 2.0</h1>
Load video
<iframe id=myFrame width="1120" height="630" src=# frameborder="0" allowfullscreen></iframe>

Related

Loading new iframe into javascript collapse without toggling

I have two links - each should load a different HTML file respectively into an iframe. They will be loaded into the same javascript collapse area. I want each link to load the designated file into the iframe when clicked.
My problem is that IF one html file is loaded into the open (show) collapse area, the collapse area will toggled closed if I click on the second link. I suppose I need an if/then js script but am unsure of the proper logic and syntax?
It should operate logically as expected:
1) If the collapse area is closed (which it is by default), when any link is clicked, it should OPEN and then load in the iframe contents (HTML file)
2) If I click the second link while the collapse is open, it should STAY open (not toggle closed) and simply load in the second iframe contents (HTML file)
What I have below works fine for 'loading' the proper content, but it toggles by default. So if I have the area open with content loaded, it closes if I click the second link.
here are my snippets:
LINK 1
LINK 2
<div id="content" class="collapse">
<p><iframe id="process_frame" overflow="hidden" scrolling="no" frameborder="0" height="280" width="100%"></iframe></p>
</div>
Any suggestions or samples would be helpful... Thank You
I'm going to use websites to demo a solution for your question. The snippet doesn't display the results but you can view a fiddle here. A second solution is here (shown in second snippet); it is specific to your two files. You may have to add a path.
These are fairly primitive solutions but as you are only switching between two files, perhaps this may suffice for your needs.
(I set a background colour for the div (not the iframe).. remove this if you wish..)
function togglediv(filename) {
var frme = document.getElementById("process_frame");
var file2 = filename;
if (file2 == " " || filename == undefined) {
frme.src = "http://www.richmondinnireland.com";
file2 = frme.src;
} else {
frme.src = filename;
file2 = frme.src;
}
//console.log(file2)
// display frame is hidden
if (frme.style.display == 'none') {
frme.style.display = 'block';
frme.src = file2;
}
}
#content {
background-color: lightgrey;
height: 280px;
overflow: auto;
}
#process_frame {
height: 280px;
overflow: auto;
width: 100%;
z-index: 0;
}
LINK 1
LINK 2
<br><br>
<div id="content" class="collapse">
<iframe id="process_frame" overflow="hidden" scrolling="no" frameborder="0" height="280" width="100%"></iframe>
</div>
<script>
</script>
#process_frame {
height: 280px;
overflow: auto;
width:100%;
}
#file1,
#file2 {
display: inline-block;
margin: 5px;
}
File 1
File 2
<div id="content" class="collapse">
<iframe id="process_frame" overflow="hidden" scrolling="no" frameborder="0" height="280" width="100%"></iframe>
</div>
<script>
function togglediv(num) {
var frme = document.getElementById("process_frame");
var fileid = num;
var filename = "html_file_";
var filetoget = '"' + filename + num + ".php" + '"';
console.log(filetoget);
// check if frame is hidden
if (frme.style.display == 'none') {
frme.style.display = 'block';
frme.src = getfile;
} /*else {
//frme.style.display = 'none';
}*/
}
</script>

Loading bar for iframe while reloading via location.href

I have an iframe which is refreshed at button press while reading from a kendo datepicker the information to decide what data needs to be loaded.
The iframe has an onlaod gif showing that it is still loading data at initialisation, which can take up to 20 seconds in this example.
The same loading bar I want to use while getting new data/refreshing the iframe. Any idea how to achieve this behaviour? Like calling onload again
<iframe id="iframeExample"
frameborder="0"
border="0"
marginwidth="0"
marginheight="0"
style="border: none; margin-left: 10px; padding: 1px; margin-top: 5px; display: block;"
height="500px"
width="98%"
runat="server"
src='#Url.Action("Action","Controller", new { Id1= #Model.Id1, Id2 = #Model.Id2 })'
onload="document.getElementById('loadImg').style.display='none';"></iframe>
The image for the onload
<div id="loadImg"><img id="image" src="~/Content/Kendo/2018.1.117/Bootstrap/loading-image.gif" /></div>
and the following for refreshing the iframe
var ActionUrl = "#Html.Raw(#Url.Action("Action", "Controller", new { Id1 ="_PLACEHOLDER_ID1_", Id2= "_PLACEHOLDER_ID2_" }))";
function refreshIFrame() {
debugger;
var Id1= $("#Id1").val();
var dtId2 = $("#Id1").getKendoDatePicker().value();
var Id2 = kendo.toString(dtId2, "yyyy-MM-dd");
document.getElementById("iframeExample").contentDocument.location.href = ActionUrl.replace("_PLACEHOLDER_ID1_", Id1).replace("_PLACEHOLDER_ID2_", Id2);
}
Thank you for any hints and tipps

youtube - cannot swipe past iframe in carousel / slider

I have a responsive site with a carousel. The user can embed a youtube video as one of the slides. On desktop this works fine. On mobile however the iframe apparently eats all the swipe events and you cannot swipe past the video. We had to hack around this by substituting an image of the video and then using window.open() open a new window with the video.
It sucks.
Is there a good way to overcome this?
In short, I discovered I was doing it wrong.
The slider script works very well on both desktop. On mobile it works except you cant swipe past the iframe that embeds the video.
My example iframe is:
<iframe width="1280" height="720" src="//www.youtube.com/embed/Lzbr6fPDmkE" frameborder="0" allowfullscreen></iframe> (fyi, its a funny video if you're an Army vet)
I discovered the (somewhat obvious) fact that youtube has a thumbnail url as well. So on mobile I add the following img tag:
<img src="http://i.ytimg.com/vi/Lzbr6fPDmkE/hqdefault.jpg" alt="1300x650" />
I found the answer in this article
The url I used is different than theirs because I ripped it off of an imbedded youtube thumbnail inside a gmail message.
Its mandatory to include below attribute in URL.
rel=0&enablejsapi=1
Note: Go through comment lines and add those slider library files in head section and save it. once everything added you have to open the file in browser. You can able to see the slider. If find any issue please comment below.
$('.slider').click();
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('videoSwipe', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(e) {
$('.youTubeVideo').find('.video').addClass('video-overlay');
}
function OverlayOnVideo(playerStatus) {
if (playerStatus == 2) {
$('.youTubeVideo').find('.video').addClass('video-overlay');
var iframeHeight=$('#videoSwipe').height()-40;
var overlayHeight=$(document).find('.video-overlay');
if ( overlayHeight.length >= 1 ) {
overlayHeight.css('height', iframeHeight+'px');
}else{
$('.youTubeVideo .tube').removeAttr( 'style' );
}
}
}
function onPlayerStateChange(e) {
OverlayOnVideo(e.data);
}
$(document).on("click", ".video-overlay", function() {
if (player) {
player.playVideo();
$('.youTubeVideo').find('.video').removeClass('video-overlay');
$('.youTubeVideo .tube').removeAttr( 'style' );
}
});
.youTubeVideo {
position: relative;
}
#wrapper {
width: 30%;
margin: auto;
}
.slick-list draggable {
margin-top: 3%;
}
body {
outline: none;
background: black;
}
:focus {
outline: none;
}
.slick-list.draggable {
margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<div class="slider">
<div><img src="http://placekitten.com/500/480" alt="" width="500" height="400"></div>
<div class="youTubeVideo">
<div class="video tube"></div>
<iframe id="videoSwipe" width="465" height="400" src="https://www.youtube.com/embed/exUQkIkyBBI?rel=0&enablejsapi=1"></iframe>
</div>
<div><img src="http://placekitten.com/500/480" alt="" width="500" height="400"></div>
<div><img src="http://placekitten.com/500/460" alt="" width="500" height="400"></div>
<div><img src="http://placekitten.com/500/440" alt="" width="500" height="400"></div>
<div><img src="http://placekitten.com/500/420" alt="" width="500" height="400"></div>
</div>
</div>

I can't get my Jquery to work: Need to add img tag dynamically upon click

For the below code, I am trying to get an img tag to load somewhere on the page when you click on a button. This is just for testing purposes, but I need to get it to work. The img tag is a 1 by 1 pixel that is supposed to track that something was clicked on. I know that an a tag would be better suited for this purpose, but for reasons I can't explain here, this cannot be used.
Any advice you can give to get the below code working would be great. I will test in Fiddler to confirm.
If you need more information or clarification, please let me know.
I appreciate your help!
Thanks,
<html>
<style type="text/css">
#button {
display: inline-block;
height: 20px;
width: 150px;
background-color:orange;
font-family:cursive, arial;
font-weight:bold;
color: brown;
border-radius:5px;
text-align:center;
margin-top:2px;
}
#output {
font-family:garamond;
color:black;
height:450px;
width:320px;
border-radius:2px;
border-color:black;
background-color:white;
overflow: auto;
float: left;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('#button').click(function(){
document.getElementById('output').innerHTML +=('<img height="1" width="1" src="http://view.atdmt.com/action/AAA_ImageTest"/>');
});
});
</script>
<body>
<div id="button">Test</div>
<div id="output"></div>
</body>
</html>
Replace this:
$(document).ready(function() {
$('#button').click(function(){
document.getElementById('output').innerHTML +=('<img height="1" width="1" src="http://view.atdmt.com/action/AAA_ImageTest"/>');
});
});
With this:
$(document).ready(function() {
$('#button').click(function(){
$('#output').append('<img height="1" width="1" src="http://view.atdmt.com/action/AAA_ImageTest"/>');
});
});
Using .append("<img..) will add another img every time you click. If this is not what you're expecting then edit your question with more details about how you want it to work.
$('#output').prepend('<img height="1" width="1" src="http://view.atdmt.com/action/AAA_ImageTest"/>');
$(function() {
$('#button').on('click',function(e) { //.on() preferred, click() is a short-hand for this
e.preventDefault(); //if you change from div to `A` someday
var timestamp = Math.round(new Date().getTime() / 1000);
//creating IMG on-the-fly, adding css and appending it
$('<img />', {
'src': 'http://view.atdmt.com/action/AAA_ImageTest?ts='+timestamp
}).css({
'width':'1px',
'height':'1px',
'border':0
}).appendTo('#output');
});
});
Instead of making the HTML on had and adding as HTML, I'm creating the img on-the-fly, adding it's CSS and appending to #output.
e.preventDefault it's just for blocking default behavior of an item. That's just a bonus if someday you change from <div id="button">Test</div> to an actual anchor <a id="button" href="#">Test</a>.
Update:
#Kamui To prevent image caching (thus not making a second call when adding another one), I've added a timestamp on the image URL.
If you want to append the pure-jQuery way:
jQuery("#output").append(
jQuery("<img>")
.attr("height", "1")
.attr("width", "1")
.attr("src", "http://view.atdmt.com/action/AAA_ImageTest")
);
This will create an img object in the jQuery world, then append it to your output div. This method (as opposed to writing one big long string) is nice because it keeps everything clean - no worrying about escaping quotes, and it would be very easy to add dynamic values in there for some of the attributes.

How to add CSS class and control elements inside of the Iframe using javaScript.?

How to add CSS class and control elements inside of the Iframe using javaScript.
<iframe width="340" scrolling="no" height="37" src="http://www.indiansplash.com/business/include/dash11i.php" id="ifr" hspace="0" marginwidth="0" marginheight="0" vspace="0" style="width: 585px; height: 47px; border: #dddddd 1px solid"></iframe>
Here is my code. http://jsfiddle.net/wV8gF/
Here i want to hide first column which are having BSE logo and i want to change the color of values.
Try this. It may useful.
http://jsfiddle.net/wV8gF/3/
The DOM includes a frames collection you can access with JavaScript:
You'd need a name attribute on your iframe tag
<iframe name = "myFrame"
width="340" scrolling="no" height="37"
src="http://www.indiansplash.com/business/include/dash11i.php"
id="ifr" hspace="0" marginwidth="0" marginheight="0" vspace="0"
style="width: 585px; height: 47px; border: #dddddd 1px solid">
</iframe>
Then you can access it like this:
var myFrame = frames["myFrame"]
You can apply a new stylesheet to the content by following the example here: How to apply CSS to iframe?
UPDATE
Following the example in the reference i cited above:
var cssLink = document.createElement("link")
cssLink.href = "iframeStyles.css"; /* change this to the url for a stylesheet targetting the iframe */
cssLink .rel = "stylesheet";
cssLink .type = "text/css";
frames['myFrame'].document.body.appendChild(cssLink);
Then in iframeStyles.css:
td{border:1px solid red;} /*or whatever*/
You may need a selector with stronger specificity, or apply !important to styles to overide already existing declarations.
Try to use the following code:
var my_td = $("#table_id tr td", $("#iframe_ID").contents());
Hope this works... Muhammad.

Categories

Resources