I have the HTML Code:
<div id=ytVid>
<iframe width="420" height="315" src="http://www.youtube.com/embed/5EdmHSTwmWY" frameborder="0" allowfullscreen></iframe>
<script type="text/javascript" src="js/youtube.js"></script>
</div>
At the moment and I have a set of paragraphs that are generated by jQuery using an array.
What I would like to happen is that when the user clicks one of the generated paragraphs, this will start this code from the youtube.js file:
$(document).ready(function() {
function openLink(evt) {
var search = evt.target.innerHTML;
var keyword= encodeURIComponent(search);
var yt_url='http://gdata.youtube.com/feeds/api/videos?q='+keyword+'&format=5&max-results=1&v=2&alt=jsonc';
$.ajax({
type: "GET",
url: yt_url,
dataType:"jsonp",
success: function(response) {
if(response.data.items) {
$.each(response.data.items, function(i,data) {
var video_id=data.id;
var video_frame="<iframe width='420' height='236' src='http://www.youtube.com/embed/"+video_id+"' frameborder='0' type='text/html'></iframe>";
$("#ytVid").html(video_frame);
});
} else {
$("#ytVid").html("<div id='no'>No Video</div>");
}
}
});
};
});
I do not know if the above code is correct but what it should do is take what is in the array(if possible) or what is in the paragraph to search youtube for a video to update the ytVid div.
Thanks
In your "simplified" copy of the JavaScript jsfiddle, you have the strings wrapped in brackets, which signifies they are arrays. You also didn't have jQuery selected to be included.
http://jsfiddle.net/PADL9/1/
And here's one with the JS from above added in
http://jsfiddle.net/PADL9/2/
(remove the alert/return for the AJAX to work)
Related
I want home.html to load in <div id="content">.
<div id="topBar"> HOME </div>
<div id ="content"> </div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?
I finally found the answer to my problem. The solution is
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Fetch API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function
Reference - davidwalsh
MDN - Using Fetch
JSFIDDLE demo
You can use the jQuery load function:
<div id="topBar">
HOME
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
Fetching HTML the modern Javascript way
This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.
/**
* #param {String} url - address for the HTML to fetch
* #return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentation for more details.
I saw this and thought it looked quite nice so I ran some tests on it.
It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.
I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.
In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.
Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
/**
* Test harness to find out the best method for dynamically loading a
* html page into your app.
*/
var test_times = {};
var test_page = 'testpage.htm';
var content_div = document.getElementById('content');
// TEST 1 = use jQuery to load in testpage.htm and time it.
/*
function test_()
{
var start = new Date().getTime();
$(content_div).load(test_page, function() {
alert(new Date().getTime() - start);
});
}
// 1044
*/
// TEST 2 = use <object> to load in testpage.htm and time it.
/*
function test_()
{
start = new Date().getTime();
content_div.innerHTML = '<object type="text/html" data="' + test_page +
'" onload="alert(new Date().getTime() - start)"></object>'
}
//1579
*/
// TEST 3 = use httpObject to load in testpage.htm and time it.
function test_()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
content_div.innerHTML = xmlHttp.responseText;
alert(new Date().getTime() - start);
}
};
start = new Date().getTime();
xmlHttp.open("GET", test_page, true); // true for asynchronous
xmlHttp.send(null);
// 1039
}
// Main - run tests
test_();
</script>
</body>
</html>
try
async function load_home(){
content.innerHTML = await (await fetch('home.html')).text();
}
async function load_home() {
let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> HOME </div>
<div id="content"> </div>
When using
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as argHtml
There is this plugin on github that load content into an element. Here is the repo
https://github.com/abdi0987/ViaJS
load html form a remote page ( where we have CORS access )
parse the result-html for a specific portion of the page
insert that part of the page in a div on current-page
//load page via jquery-ajax
$.ajax({
url: "https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript",
context: document.body
}).done(function(data) {
//the previous request fails beceaus we dont have CORS on this url.... just for illlustration...
//get a list of DOM-Nodes
var dom_nodes = $($.parseHTML(data));
//find the question-header
var content = dom_nodes.find('#question-header');
//create a new div and set the question-header as it's content
var newEl = document.createElement("div");
$(newEl).html(content.html());
//on our page, insert it in div with id 'inserthere'
$("[id$='inserthere']").append(newEl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>part-result from other page:</p>
<div id="inserthere"></div>
Use this simple code
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```
This is usually needed when you want to include header.php or whatever page.
In Javascript it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Javascript function in script tag.
In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php
i.e convert the php include function to Javascript function in script tag and place all your content in that included file.
I use jquery, I found it easier
$(function() {
$("#navigation").load("navbar.html");
});
in a separate file and then load javascript file on html page
showhide.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showHide(switchTextDiv, showHideDiv)
{
var std = document.getElementById(switchTextDiv);
var shd = document.getElementById(showHideDiv);
if (shd.style.display == "block")
{
shd.style.display = "none";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>";
}
else
{
if (shd.innerHTML.length <= 0)
{
shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
}
shd.style.display = "block";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
}
}
</script>
</head>
<body>
<a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
<span style="display: block; background-color: yellow">Show</span>
</a>
<div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
</body>
</html>
showhide_embedded.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function load()
{
var ts = document.getElementById("theString");
ts.scrollIntoView(true);
}
</script>
</head>
<body onload="load()">
<pre>
some text 1
some text 2
some text 3
some text 4
some text 5
<span id="theString" style="background-color: yellow">some text 6 highlight</span>
some text 7
some text 8
some text 9
</pre>
</body>
</html>
If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash
For ex : <iframe src="home.html" width="100" height="100"/>
In a class, I was asked to make a dynamic drop-down menu in a form using HTML5 and JavaScript. I did that here.
Now, I need to call data from a JSON file. I looked at other answers on SOF and am still not really understanding how to use JQuery to get info from the JSON file.
I need to have 2 fields: the first field is a Country. The JSON key is country and the value is state. A copy of the JSON file and contents can be found here. The second drop-down field adds only the values / arrays related to its associated Country.
Here is a copy of my HTML5 file:
<!DOCTYPE html>
<html lan="en">
<head>
<!-- <script type="text/javascript" src="sampleForm.js"></script>-->
<!-- <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> -->
<script type="text/javascript" src="getData.js"></script>
<script type="text/javascript" src="moreScript.js"></script>
<meta charset="UTF-8";
<title>Select Country and State</title>
<link rel="stylesheet" href="formStyle.css" />
</head>
<body>
<form id="locationSelector" enctype='application/json'>
<br id="selectCountry"></br>
<select id='country'></select>
<br id="selectState">=</br>
<select id='state'></select>
</form>
</body>
</html>
Here is a copy of the JS file I wrote so far that tries to get the data from the JSON file and fails:
$(document).ready(function() {
var data = "countryState.JSON";
var $selectCountry = $("#country");
$.each(data.d, function(i, el) {
console.log(el);
$selectCountry.append($("<option />", { text: el }));
});
});
Here is the content from the other JS file that adds the field instruction:
var selectYourCountry = document.getElementById('selectCountry');
selectYourCountry.innerHTML = "Select Your Country: ";
var selectYourState = document.getElementById('selectState');
selectYourState.innerHTML = "Select Your State";
This was supposed to at least add the values to the field, but nothing but empty boxes appear on the web page.
I then need to make a conditional statement like the one at here but calling or referencing data from the JSON file.
I have only taken some HTML and JavaScript courses, not JQuery and JSON. So, your help will greatly increase my knowledge, which I will be very grateful for.
Thank you!!
I found this SOF answer and changed my JS file to the following:
$(document).ready(function()
{
$('#locationSelector').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
url:"countryState.JSON",
dataType: "json",
success: function (data) {
$.each(data.country,function(i,obj)
{
alert(obj.value+":"+obj.text);
var div_data="<option value="+obj.value+">"+obj.text+"</option>";
alert(div_data);
$(div_data).appendTo('#locator');
});
}
});
});
});
And, I edited my HTML document as follows:
<form id="locationSelector" enctype='application/json'></form>
I removed and added back the <select> tags and with the following at least I get a blank box:
`<form id="locationSelector" enctype='application/json'>
<select id="locator"></select>
</form>`
I feel like I am getting closer, but am still lost.
Can you try this:
$.get("countryState.JSON", function( data ) {
var html = "";
$.each(data.d, function(i, el) {
console.log(el);
html += "<option value='"+Your value+"'>"+Your displayed text+"</option>";
});
$('#state').html(html);
});
I am trying to make a news preview from a separate file (text.html) I want to be able to just display the first 100 characters of a div (id="news"). I don't want to use Ajax or Php. Here is my code, not sure how to make it work, thanks guys.
<body onload="home()">
<div id="content"></div>
<script>
function home() {
var x = document.getElementById("content").innerHTML = '<object width="100%" height="100%" type="text/html" data="text.html"></object>';
var pre = x.substring(0,5);
alert(pre);
}
</script>
</body>
I'm using the following code to load a page into a <div>. It works fine except it's not supposed to load all links into the <div>.
<script type='text/javascript'>
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("a").click(function(){
$j.ajax({
url: $j(this).attr("href"),
success: function(response) {
$j("#output").html(response);
}
});
return false;
});
});
</script>
<div>[ <a href="execute.php?cmd=test1">link 1</a] [ <a
href="execute.php?cmd=test2">link 2</a] [ <a href="mypage.com">link
3</a>]</div>
<div id="output"></div>
When I click link 3, used to go to the homepage, it opens the homepage in <div id="output"></div>.
Any idea why this happens?
You are assigning the click event to the a element, so all links will load the url inside the output div. You need to specify which elements to assign the click event, maybe by specifying a class.
$j("a.loadindiv").click
<a class="loadindiv" href
Hope this helps...
Link 3 is making a request to "mypage.com" and taking the html that it returns and outputting it into the 'output' div. You are making an AJAX call to the homepage and it is serving up the page to you.
Rather than having all the elements use the AJAX function you might want to consider doing:
<script type='text/javascript'>
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j(".ajaxLink").click(function(){
$j.ajax({
url: $j(this).attr("href"),
success: function(response) {
$j("#output").html(response);
}
});
return false;
});
});
</script>
<div>[ <a href="execute.php?cmd=test1" class="ajaxLink">link 1</a] [ <a
href="execute.php?cmd=test2" class="ajaxLink">link 2</a] [ <a href="mypage.com">link
3</a>]</div>
<div id="output"></div>
I used to use this snippet to re-render a Tweet button.
var tweetButton = new twttr.TweetButton(twitterScript);
twttr.render();
But it looks like widgets.js (http://platform.twitter.com/widgets.js) has been modified so twttr.TweetButton is no longer a constructor.
Can anyone help with this issue?
I found the answer on the web. The idea is to re-request the Twitter javascript file. As it is cached, there is no download overhead.
$.ajax({ url: 'http://platform.twitter.com/widgets.js', dataType: 'script', cache:true});
For anyone stumbling onto this, there's a new, easier way to do it (as of 5/28/12 if not before). A quick glance didn't find it in the documentation, but you can do twttr.widgets.load(). That'll [re]load all the widgets on the page.
EDIT: It is documented, after all. Check out this page's "Optimization" section (which you can't link to directly)
you just need to call twttr.widgets.load() after your ajax call. no need to reload a script that is already loaded.
Looks like the twttr.TweetButton constructor was never supported, and now no longer works after the last API update:
http://groups.google.com/group/twitter-development-talk/browse_thread/thread/bcda486acdf4ab42/6a557050f850ccf2?lnk=gst&q=+twttr.TweetButton#6a557050f850ccf2
The supported method is to create an iframe-based Tweet button dynamically:
http://dev.twitter.com/pages/tweet_button#using-an-iframe
Although note #Runningskull’s answer for updated information.
First, make sure you have jQuery included in your document's head:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
Then create a link that has the same URL as the eventual tweet button, along with an empty div where your button will be rendered:
<div id="tbutton"></div>
At the bottom of your page, right above the /body tag, include the javascript from Twitter and the function that will render the button, as well as the listener that will activate the function when the desired event takes place:
<script type="text/javascript">
//async script, twitter button fashiolista.com style
(function() {
var s = document.createElement('SCRIPT');
var c = document.getElementsByTagName('script')[0];
s.type = 'text/javascript';
s.defer = "defer";
s.async = true;
s.src = 'http://platform.twitter.com/widgets.js';
c.parentNode.insertBefore(s, c);
})();
function renderTweetButton(tbutton,tlink){
var href = $("#"+tlink).attr('href'),
$target = $("#"+tbutton),
qstring = $.param({ url: href, count: "vertical" }),
toinsert = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?'+qstring+'" style="width:57px; height:70px;"></iframe>';
$target.html(toinsert);
}
$("#hoverlink").mouseenter(function() {
renderTweetButton("tbutton","tlink");
});
</script>
Lastly, add a link to your page somewhere that will activate the function above based on some event:
Hover here to render a tweet button to div#tbutton.
That's it.
If you want the entire test HTML page to see how I've got it working, see here:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery Twitter Button Render Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div id="tbutton"></div>
Hover here to render a tweet button to div#tbutton.
<script type="text/javascript">
//async script, twitter button fashiolista.com style
(function() {
var s = document.createElement('SCRIPT');
var c = document.getElementsByTagName('script')[0];
s.type = 'text/javascript';
s.defer = "defer";
s.async = true;
s.src = 'http://platform.twitter.com/widgets.js';
c.parentNode.insertBefore(s, c);
})();
function renderTweetButton(tbutton,tlink){
var href = $("#"+tlink).attr('href'),
$target = $("#"+tbutton),
qstring = $.param({ url: href, count: "vertical" }),
toinsert = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?'+qstring+'" style="width:57px; height:70px;"></iframe>';
$target.html(toinsert);
}
$("#hoverlink").mouseenter(function() {
renderTweetButton("tbutton","tlink");
});
</script>
</body>
</html>
I just had the same problem, this works in JQuery:
$.getScript('http://platform.twitter.com/widgets.js');
Try the #Anywhere library. Sample js code:
twttr.anywhere(function (T) {
T("#tweetbox").tweetBox({
counter: false,
defaultContent: "Default text in a Tweet box...",
label: "Share this page on Twitter"
});