How to prevent HTML code from running? - javascript

I seek to embed multiple iframes on a single page without slowing the page. When I embedded a single iframe, it was running smoothly; added a second and third, and all were slower - despite only one being displayed at a time (using JScript). I presume this is due to the iframe code still executing.
How can I execute code conditionally? In my case, whenever a button is clicked.
Help is appreciated. Fiddle for the exact code I use, with actual content replaced by IDs and iframes by p's: http://jsfiddle.net/aof89Ljt/55/
HTML for the iframes:
<p id="ifr1">
ifr1
</p>
<p id="ifr2" style="display:none;">
ifr2
</p>
<p id="ifr3" style="display:none;">
ifr3
</p>
UPDATE: New JFiddle link with JScript included. End-goal description: I click a button which displays a different embedded Desmos graph, then another graph, then the first graph - in a loop, one at a time (see code). Demonstration gif: https://puu.sh/Bjpil/da9a038e11.gif
UPDATE 2: Solution found; full code: https://jsfiddle.net/32uxrhmw/49/
UPDATE 3: Greatly optimized code: https://jsfiddle.net/32uxrhmw/92/

You need to add the onclick="<your function>" event trigger to the element(s) you want to "do something".
Simple example:
<button onclick="swap()">Button</button>
<iframe style="display: none;" data-url="https://www.example.com" id="iframe">
<p>Your browser does not support iframes.</p>
</iframe>
<script>
function swap() {
e = document.getElementById('iframe'); // get iframe
url = e.dataset.url; // get desired url attribute stored in data-url
e.setAttribute("src", url); // add the iframe src with desire url
e.removeAttribute("style"); // remove styling that hid it otherwise
}
</script>
UPDATED to better apply to question.
UPDATED again to also incorporate #Joe Fitzsimmons good suggestion re handling iframe sources (in his answer).
FINAL ADDITION SEEING YOUR CODE:
Looking at your last code, it seems what you want to do is:
load page with one iframe;
then change iframe displayed when the button is clicked.
If that is what you want, you might want to use this much simpler code:
(Note: I used your code sample as a base, but haven't inserted any src urls - yours may be private, but even if not they all showed the same result so it may confuse other readers)
<style>
.tdropbtn {
background-color: white;
font-size: 16px;
border: none;
cursor: pointer;
color: #0066CC;
}
</style>
<center>
<iframe id="frame" src="https://url1" width="500px" height="400px" frameborder=0></iframe>
</center>
<div style="display:inline;">
<center>
<button onclick="swap()" class="tdropbtn">[+]</button>
</center>
</div>
<script>
var counter = 1;
var firstFrame = "https://url1";
var secondFrame = "https://url2";
var thirdFrame = "https://url3";
var e = document.getElementById("frame");
function swap() {
if (counter == 0){
e.src = firstFrame;
counter++;
}
else if (counter == 1){
e.src = secondFrame;
counter++;
}
else if (counter == 2){
e.src = thirdFrame;
counter = 0;
}
}
</script>

One idea would be to load/remove the source of the iframe onClick.
This is a rough idea of what you could do:
function Swap(id, url) {
document.getElementById(id).src = url;
}
You'd have to show and hide the iFrames as well. Hopefully this could get you on your way. I'm not exactly sure what your end goal is.

Related

how to convert an html script into a .js file script

would like to place the script into a .js file that opens already with
$(document).ready(function() {
});
I have tried but it feel slike because im putting the onMouse over command into the html I don't think it will be possible?
<head>
<style>
div > p {
cursor: pointer;
}
</style>
<script>
var monkeySrc = "http://icons.iconarchive.com/icons/martin-berube/animal/256/monkey-icon.png";
var lionSrc = "http://icons.iconarchive.com/icons/martin-berube/animal/256/lion-icon.png";
var treeSrc = "http://totaltreeworks.co.nz/wp-content/uploads/2011/02/Tree-256x256.png";
var falconSrc = "http://icons.iconarchive.com/icons/jonathan-rey/star-wars-vehicles/256/Millenium-Falcon-01-icon.png";
function changeImage(src){
document.getElementById("myImage").src = src;
}
</script>
</head>
<body>
<div class="images">
<img id="myImage" width="256" height="256">
</div>
<div>
<p onmouseover="changeImage(monkeySrc)">Monkey are funny!</p>
</div>
<div>
<p onmouseover="changeImage(lionSrc)">Lions are cool!</p>
</div>
<div>
<p onmouseover="changeImage(treeSrc)">Trees are green!</p>
</div>
<div>
<p onmouseover="changeImage(falconSrc)">Falcons are fast!<p>
</div>
</body>
</html>
If you were to take your existing JavaScript and place it in an external file, it would work just fine. It would work because all of your variables and your function would be in the global scope.
Going one step further you'll want to move those onmouseover event handlers into the JavaScript itself.
Given a small change to your current HTML and assuming jQuery you could do something like the following:
<p data-kind="monkey">Monkey are funny!</p>
then
var urlMap = {
monkey : 'http://icons.iconarchive.com/icons/martin-berube/animal/256/monkey-icon.png'
...
};
$('p').on('mouseover', function () {
var kind = $(this).data('kind');
var url = urlMap[kind];
changeImage(url);
});
which you would then be able to wrap in the $(document).ready, the shorthand for which is just $(function () { /* The code from above here */ });
You would need to bind the event handlers programmatically from within the .js file. jQuery would make this very simple and allow you to use arbitrary CSS selectors, but you can do the same in pure JS using e.g. document.getElementById and document.addEventListener.
You can bind the function to the event using Javascript addEventListner
1- Add id attribute to each of your paragraphs tags
<p id="p1"> .....</p>
2- Grab a variable that points to each of those
var p1 = document.getElementById('p1');
3- add event listner
p1.addEventListener("mouseover", changeImage(monkeySrc));
If you put your javascript code in another file and replace <script>...</script> with <script src="javascriptcodefilename.js"></script> in your HTML file, it still works as intended.
Example: http://codepen.io/anon/pen/waLqxz
It might be cleaner to add all of your urls to an array where the key is the name of the link, so you would have something like urls['lionSrc'] = "www.xyz.com";...
then in your changeImage function you would do document.getElementById("myImage").src = url[src];
this way you could even check to see if the image exists already, and if not, show an "image not found" icon.

javascript replace code within source tag

Looking for a way to integrate two plugins so that I can have a HTML5 video player with a clickable html playlist. In order to do this, I need to alter one of the plugins so that instead of declaring:
var html = '';
html += '<video width...>'
html += '<source... /source>'
html += '<.video>'
return html
and then refilling on each click, it leaves the current contents alone, only replacing the content of the source tags. I'm trying something like:
html.replace(/'<source>'.*'</source>'/ , '<source> + myNewContent + '</source>');
return html;
I worry that my syntax for .replace() is wrong, or that replace can't handle strings like that.
As a side note, I know I'll need to re-run the function in order for it to reload with the new source, it's just that one plugin is deleting the content of the other, so I don't even have a chance.
Just select it with jquery and overwrite the source. (You could do it without jQ, but nevertheless)
var s = "newSourceString";
$(".videoClass source").html(s);
Now put the classname in your video attributes and fire away.
Just copy paste from the player documentation:
<script>
// JavaScript object for later use
var player = new MediaElementPlayer('#player',/* Options */);
// ... more code ...
player.pause();
player.setSrc('mynewfile.mp4'); /*********** this is what you want ***********/
player.play();
</script>
mediaelementjs.com
EDIT
Answer to the question:
var source = '<source>1 1bla bla bla xx uu dfhf</source>'
var startStr = source.indexOf('<source>') + 8;
var endStr = source.indexOf('</source>');
var oldSrc = source.substring(startStr, endStr);
console.log(oldSrc);
source = source.replace(oldSrc, 'new source');
console.log(source);
I believe this answers your original question.
Many thanks to Rudy for his answer, it put me on the right track, though I changed it to handle a dynamic source (his probably could too).
When you replace youtube videos in mediaelement.js you have to redeploy the plugin, so I ended up emptying the plugin container, storing all the hrefs as a data attribute in the list and then refilling the container with the appropriate html, and recalling the function at the end.
Here's the code:
HTML:
<div class="youtube-slide">
<div id="ytvideo">
<!--here's the initial video source-->
<video width="100%" height="100%" id="player1" preload="none" type="video/youtube" src="http://www.youtube.com/watch?feature=player_embedded&v=JUQXileHPQs" />
</div>
<!--the list of videos, each with a 'data-href' attribute storing a link, and the first one already activated as 'currentvideo'-->
<ul class="vidlist">
<li id="vid1" class="currentvideo" data-href="http://www.youtube.com/watch?feature=player_embedded&v=JUQXileHPQs"> <h3> "Cereus Bright"</h3> unplugged, anthemic ballad<br />recorded live in concert</li>
<li id="vid2" class data-href="http://www.youtube.com/watch?v=0RMtebCrJhY"> <h3> "Winds of Change" </h3>upbeat, funky, with upright bass<br />recorded live in studio </li>
<li id="vid3" class data-href="http://www.youtube.com/watch?v=7Ndm2o6p0A8"> <h3>"Some Strange Hold" </h3> melodic song of heartbreak <br /> recorded live (takeaway style)
</li>
</ul>
</div>
JAVASCRIPT:
<script>
//call function the first time
var player = new MediaElementPlayer('#player1');
$('ul.vidlist li').click(function() {
//clear the div of the player
$('div#ytvideo').empty();
//switch the currentvideo classes, to allow styling
$('.currentvideo').removeClass('currentvideo');
$(this).addClass('currentvideo');
//refill the player div, and call the plugin again
$('div#ytvideo').html('<video width="100%" height="100%" id="player1" preload="none" type="video/youtube" src="' + $(this).attr('data-href') +'"/>');
var player = new MediaElementPlayer('#player1');
});
</script>

How do I load a nested web page in a <div> tag using only javascript and html?

I have a home page with multiple <div> tags. One of the <div id="top_bar"> contains a link. If I click on the link, a new web page should load on one of the other <div id="content"> in home page. How do I do that?
More over, if the newly loaded page on one of the other <div id="content"> contains a link, and clicking on the link helps the 2nd new web page load in the <div id ="content"> tag replacing the first content of the div , the question is how do I do that?
This is an assignment given to me and the rules are:
I have to use Javascript, CSS and HTML only.
I can't use <iframe> tag.
I can't use <table> tag either to load page in a row/column.
I need help and advice about how to do it.
home.html
<body>
<div id="topBar">
HOME
<a href="#" onclick="load_about()" > ABOUT </a>
SONG LIST
</div>
<div id ="content"> </div>
</body>
I want the music.html to open in side the < div id="content" > which all ready does. but in music.html there is a button. I want to open Songlist.html in < div id="content" > by clicking on that button. code for
music.html :
<body >
<form name="flyrics" method="get" >
Lyrics: <input type ="text" name ="lyrics"/>
Artist Name:<input type ="text" name ="artist" />
<input type="submit" id="x" value="Search" />
</form>
</body>
javascript:
function load_home(){ document.getElementById("content").innerHTML='<object type="type/html" data="home.html" id="link_pages" ></object>'; }
function load_about(){ document.getElementById("content").innerHTML='<object type="type/html" data="about.html" id="link_pages" ></object>'; }
function load_search(){ document.getElementById("content").innerHTML='<object type="type/html" data="music.html" id="link_pages" ></object>'; }
function validation(){
var x=document.forms["flyrics"]["lyrics"].value;
if (x==null || x=="")
{
alert("Search without Lyrics?");
return false;
}
var y=document.forms["flyrics"]["artist"] value;
if (y==null || y=="")
{
alert("Search without Artist Name?");
return false;
}
window.open("songList.html", "currentWindow");
}
AJAX is what your assignment is looking for.
Simple Example
HTML:
<button id="nav">load</button>
<div id="page"></div>
JS:
document.getElementById('nav').onclick = function(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4)
{
document.getElementById("page").innerHTML = xhr.response;
}
}
xhr.open("GET", "http://www.codecademy.com/", false);
xhr.send();
}
fiddle: http://jsfiddle.net/DZmBG/3/
In one of your comments, you mentioned using <object> tags to embed external HTML files.
Here is an example using that method:
HTML:
<div id="links">
stuff
fun
bing
</div>
<div id="container"></div>
CSS:
div#container {
width:500px;
height:500px;
overflow:hidden;
}
JS:
function go(obj) {
var page=obj.href;
document.getElementById('container').innerHTML='<object data="'+page+
'" type="text/html"><embed src="'+page+'" type="text/html" /></object>';
return false;
}
http://jsfiddle.net/sAcCV/
EDIT:
This being said, I recommend using AJAX to load external content, instead:
http://www.javascriptkit.com/dhtmltutors/ajaxincludes.shtml
See Relfor's answer.
Iframe is the obvious answer. That's what it was made for. But since your requirements state you can't use it....
Any site that's not within your domain is going to violate the same origin policy, and Javascript in the remote page is not going to run as you probably would think it would inside a div on your site. You'd probably have to examine a CURL get approach or something similar to do it with a straight div and javascript.
AJAX is definitely the way to go if you are not able to use iframes. I would suggest using jQuery for this example to save some time. Their AJAX handling is pretty straightforward and you are gonna want to use their .live() or .on() event handlers to track the click events inside the containers.
Additionally, you may run into issues if you are loading sites on different domains. AJAX calls are typically meant for same-domain responses. You can get around this using JSONP. However, your web service must support method injection for this to work. In not, you may want to see if you can work around the iframe barrier with your host/webmaster.
You can not. You are asking for something that can not be done. For such situation you must use iframe.

How to pick element inside iframe using document.getElementById

I have a iframe like this
<iframe name="myframe1" id="myframe1" width="100%" height="100%" src="a.html">
<html>
<head></head>
<frameset name="myframe2" cols="0%, 100%" border="0" frameBorder="0" frameSpacing="0">
<frame name="page1" src="c.html" scrolling="no"></frame>
<frame name="page2" src="d.html" >
<html>
<head></head>
<body id="top">
<div id="div1">
<div id="div2">
<div id="div3">
<ul id="x">
<li>a</li>
<li>b</li>
</ul>
</div>
</div>
</div>
</body>
</html>
</frame>
</frameset>
</html>
</iframe>
I want to refer to the element "x". I tried in several ways but I couldn't find a solution.
document.getElementById('myframe1').contentWindow.document.getElementById('x')
Fiddle
contentWindow is supported by all browsers including the older versions of IE.
Note that if the iframe's src is from another domain, you won't be able to access its content due to the Same Origin Policy.
use contentDocument to achieve this
var iframe = document.getElementById('iframeId');
var innerDoc = (iframe.contentDocument)
? iframe.contentDocument
: iframe.contentWindow.document;
var ulObj = innerDoc.getElementById("ID_TO_SEARCH");
(this is to add to the chosen answer)
Make sure the iframe is loaded before you
contentWindow.document
Otherwise, your getElementById will be null.
PS: Can't comment, still low reputation to comment, but this is a follow-up on the chosen answer as I've spent some good debugging time trying to figure out I should force the iframe load before selecting the inner-iframe element.
You need to make sure the frame is fully loaded
the best way to do it is to use onload:
<iframe id="nesgt" src="" onload="custom()"></iframe>
function custom(){
document.getElementById("nesgt").contentWindow.document;
}
this function will run automatically when the iframe is fully loaded.
In my case I was trying to grab pdfTron toolbar, but unfortunately its ID changes every-time you refresh the page.
So, I ended up grabbing it with this one-liner:
const pdfToolbar = document.getElementsByTagName('iframe')[0].contentWindow.document.getElementById('HeaderItems');
As in the array written by tagName you will always have the fixed index for iFrames in your application.
Apologies I don't have enough reputations to add a comment but maybe writing an answer is ok in this case. I've been looking to change the css of some html in an Iframe. I have a bookmarklet code which works outside an iframe so I'm nearly there:
javascript:(function(){ var style = document.createElement('style'), styleContent = document.createTextNode('.notifications-list--cMVsqVbKkaXV4SQ {zoom: 0.8!important;}'); style.appendChild(styleContent); var caput = document.getElementsByTagName('head'); caput[0].appendChild(style); })();
my iframe is called xm-feed-iframe
so I guessed you'd change the code to
document.getElementById('xm-feed-iframe').contentWindow.document.getElementById('x')
But I needed to work with a class in order to change the css styles. So I guess it might be as simple as changing
var caput = document.getElementsByTagName('head')
to
var caput = document.getElementById('xm-feed-iframe').contentWindow.document.getElementsByTagName('head')
so the final code would be
javascript:(function(){ var style = document.createElement('style'), styleContent = document.createTextNode('.notifications-list--cMVsqVbKkaXV4SQ {zoom: 0.8!important;}'); style.appendChild(styleContent); var caput = document.getElementById('xm-feed-iframe').contentWindow.document.getElementsByTagName('head'); caput[0].appendChild(style); })();
And hey presto it worked. I can now delve a little deeper and add some counters hopefully to the list which appears in the iframe! :)
Any comments about the code would be most appreciated as I'm self taught!
Hope this helps someone else
Thanks
UPDATE:
Here we are - I know have a numbered list using a bookmarklet. My life will be so much easier now as I will no longer loss track of all the items I need to download. :D

How to display JavaScript variables in a HTML page without document.write

I am trying to display some JavaScript variable on my HTML page.
I was first using document.write() but it use to overwrite the current page when the function was called.
After searching around, the general consensus was that document.write() isn't liked very much. What are the other options?
I found a page suggesting using .innerHTML but that was written in 2005.
A jsFiddle illustrating my problem http://jsfiddle.net/xHk5g/
Element.innerHTML is pretty much the way to go. Here are a few ways to use it:
HTML
<div class="results"></div>
JavaScript
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';
// Using the jQuery library
$('.results').html('Hello World!');
If you just want to update a portion of a <div> I usually just add an empty element with a class like value or one I want to replace the contents of to the main <div>. e.g.
<div class="content">Hello <span class='value'></span></div>
Then I'd use some code like this:
// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';
// Using the jQuery library
$(".content .value").html("World!");
Then the HTML/DOM would now contain:
<div class="content">Hello <span class='value'>World!</span></div>
Full example. Click run snippet to try it out.
// Plain Javascript Example
var $jsName = document.querySelector('.name');
var $jsValue = document.querySelector('.jsValue');
$jsName.addEventListener('input', function(event){
$jsValue.innerHTML = $jsName.value;
}, false);
// JQuery example
var $jqName = $('.name');
var $jqValue = $('.jqValue');
$jqName.on('input', function(event){
$jqValue.html($jqName.val());
});
html {
font-family: sans-serif;
font-size: 16px;
}
h1 {
margin: 1em 0 0.25em 0;
}
input[type=text] {
padding: 0.5em;
}
.jsValue, .jqValue {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Setting HTML content example</title>
</head>
<body>
<!-- This <input> field is where I'm getting the name from -->
<label>Enter your name: <input class="name" type="text" value="World"/></label>
<!-- Plain Javascript Example -->
<h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>
<!-- jQuery Example -->
<h1>jQuery Example</h1>Hello <span class="jqValue">World</span>
</body>
</html>
You can use javascript to access elements on the page and modify their contents. So for example you might have a page with some HTML markup like so:
<div id="MyEdit">
This text will change
</div>
You can use javascript to change the content like so...
document.getElementById("MyEdit").innerHTML = "My new text!";​
Here is a working example
You can also look at using the JQuery javascript library for DOM manipulation, it has some great features to make things like this very easy.
For example, with JQuery, you could do this to acheive the same result...
$("#MyEdit").html("My new text!");
Here is a working example of the JQuery version
Based on this example you provided in your post. The following JQuery would work for you:
var x = "hello wolrd";
$("p").html(x);
Here is the working version
Using a P tag like this however is not recommended. You would ideally want to use an element with a unique ID so you can ensure you are selecting the correct one with JQuery.
there are different ways of doing this.
one way would be to write a script retrieving a command.
like so:
var name="kieran";
document.write=(name);
or we could use the default JavaScript way to print it.
var name="kieran";
document.getElementById("output").innerHTML=name;
and the html code would be:
<p id="output"></p>
i hope this helped :)
You could use jquery to get hold of the html element that you want to load the value with.
Say for instance if your page looks something like this,
<div id="FirstDiv">
<div id="SecondDiv">
...
</div>
</div>
And if your javascript (I hope) looks something as simple as this,
function somefunction(){
var somevalue = "Data to be inserted";
$("#SecondDiv").text(somevalue);
}
I hope this is what you were looking for.
If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.
​var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);​​​​​​
innerHTML is fine and still valid. Use it all the time on projects big and small. I just flipped to an open tab in my IDE and there was one right there.
document.getElementById("data-progress").innerHTML = "<img src='../images/loading.gif'/>";
Not much has changed in js + dom manipulation since 2005, other than the addition of more libraries. You can easily set other properties such as
uploadElement.style.width = "100%";
hi here is a simple example: <div id="test">content</div> and
var test = 5;
document.getElementById('test').innerHTML = test;
and you can test it here : http://jsfiddle.net/SLbKX/
Add an element to your page (such as a div) and write to that div.
HTML:
<html>
<header>
<title>Page Title</title>
</header>
<body>
<div id="myDiv"></div>
</body>
</html>
jQuery:
$('#myDiv').text('hello world!');
javascript:
document.getElementById('myDiv').innerHTML = 'hello world!';
Similar to above, but I used (this was in CSHTML):
JavaScript:
var value = "Hello World!"<br>
$('.output').html(value);
CSHTML:
<div class="output"></div>

Categories

Resources