change src of an img from an XMLHttpRequest - javascript

Using the following script, how can i change the src="#" to src='Poster'
var xhttp1 = new XMLHttpRequest();
xhttp4.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var fullMovie = JSON.parse(xhttp.responseText)
var movie = { poster: fullMovie.Poster};
document.getElementById('Cover').innerHTML = movie.poster;
}
};
xhttp4.open("GET", "http://www.omdbapi.com/?i=tt3460252&plot=full&r=json", true);
xhttp4.send();
Using this script how can i change the src from the following html?
<label for="img1" class="container1">
<img id="Cover" src="" alt="" class="container1">
</label>

document.getElementById('Cover').src = movie.poster
Change the src property of the element - you will need to construct a valid url from the data you have if movie.poster is not already a link

using jquery it can be done very easily as:
<script>
$('#Cover').attr('src','Poster');
</script>
It will change the value of src attribute of element with id 'Cover'.
But in order to use jquery in your application, you will have to include
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
in head tag.
For more information about jquery visit http://www.w3schools.com/jquery/default.asp

Related

How to render HTML file using JavaScript [duplicate]

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"/>

Fetch and add img attributes to string

I have a string like this.
x = '<div class="sample">
<img src="http://www.example.com/i/java.png">
</div>
<div class="sample_another">
<img src="/i/somedir/python.png">
</div>'
I want to convert to this
x = '<div class="sample">
<img src="http://www.example.com/i/java.png" height="200px" width="100px">
</div>
<div class="sample_another">
<img src="/i/somedir/python.png" width="150px" height="150px">
</div>'
input string will be a html doc. for all the images in the doc, i want to add the height and width property. and to get the height and width property i have to use something like this
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = 'http://www.example.com/intl/logo.gif';
p.s. i tried using this solution but the problem i face is that the string might have the script tag and DOM parses it as a closing script tag. I cant find much for regex either. So is there any other way to obtain this result ?
Thanks.
If you can remove scripts than go with this code:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
var string ="<script type"text/javascript"></script><img alt=''
src='http://api.com/images/UID' /><br/>Some plain text<br/><a
href='http://www.google.com'>http://www.google.com</a>";
var elem= document.createElement("div");
$(string).find('script').remove();
elem.innerHTML = string;
var images = elem.getElementsByTagName("img");
for(i=0; i<images.length; i++){
images[i].width = "150";
images[i].height = "250";
}
string = elem.innerHTML;
Problem you are facing with is that it turns out that HTML5 does not allow script tags to be dynamically added using the innerHTML property. So you will need to add them dynamically on some other way.
This is some code that might help you:
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src','http://example.com/site.js');
document.head.appendChild(my_awesome_script);

On image click set input value jquery

Hi im trying to set an image from an input box and if i click another image the box change his value and then the first image change his src but i dont know why is not working.This is my script
$(document).ready(function() {
$("#skin").change(function() {
var inputVal = $(this).val();
$("#container").attr("src", inputVal);
});
});
$(document).ready(function() {
$("#container2").click(function() {
var source = document.getElementById("container2").src;
$("#skin").val(source)
});
});
<input type="text" id="skin">
<img id="container" width="200px" height="200px" border-radius="50%">
<img id="container2" src="http://i.imgur.com/xt0IkTL.png">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
First of all, you are using jQuery.
So you don't have to use native javascript dom selector.
Second; you have already defined your document ready function. You don't need to call that again.
Wrap your code between the first document ready function.
I strongly recommend you to change your on change method to something else like pressing a button or trigger with something else.
After all these recommendation;
Here how you can do this:
<input id="source-changer" type="text" placeholder="Image url huh?" />
<img id="container" width="200px" height="200px" border-radius="50%"><img id="container2" src="https://i.ytimg.com/vi/PjDtgj7qR94/maxresdefault.jpg" width="100">
<!-- sample address here: https://pp.vk.me/c622424/v622424967/39c6c/6poIwEXow7U.jpg -->
<script>
$(document).ready(function() {
var firstImage = $('#container');
var secondImage = $('#container2');
$('input#source-changer').blur(function(){
var value = $(this).val();
if(value !== "") {
firstImage.attr('src', value);
}
});
secondImage.click(function(){
firstImage.attr('src', $(this).attr('src'));
});
});
</script>
Test here:
https://jsfiddle.net/upLdgb8y/1/

adding piece of HTML code using JS based on URL accessed

What I am trying to achieve is if a particular page is loaded in the browser for e.g www.domain.com/page then the following piece of code should be added in the page dynamically using JS (similar to how we load the Google Analytics code)
<div id="something">
<img src="http://domain.com/images/someImage.jpg">
</div>
I am trying to figure the script which will load the above mentioned HTML code (anywhere of the page - www.domain.com/page)
Edit 1:
what I am trying to achieve is when the user goes to www.domain.com/page.html I am calling another page lets say page1.html which should contain the script which insert the HTML code I posted above. So I simply want to insert the function which should be enclosed in the tag inside page1.html. Unfortunately I can not edit www.domain.com/page.html
If you want to PLACE that code anywhere in your page using javascript, you first need to identify that PLACE in DOM Using an "id" attribute. Here's an example:
HTML:
<html>
<body>
<div id="target1"></div>
<div id="target2"></div>
</body>
</html>
JS:
var html = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
document.getElementById('target1').innerHTML = html;
document.getElementById('target2').innerHTML = html;
You can try something like this :
$(document).ready(function () {
var url = window.location.href;
$("#something").append("<img src='"+ url +"' />");
});
$(".documentholder").load("code.html");
If you a specific id of something
$(".documentholder").load("code.html #someid");
If you a specific tag and id of something
$(".documentholder").load("code.html #someid");
Here you are,
just change this part if (getFileName() == "js") with if (getFileName() == "page")
I added js because that is what is returning in the code snippet :)
function getFileName() {
var url = document.location.href;
url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));
url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));
url = url.substring(url.lastIndexOf("/") + 1, url.length);
return url;
}
var div = '<div id="something"><img src="http://domain.com/images/someImage.jpg"></div>';
if (getFileName() == "js") {
$('body').append(div);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
let's say you save this code in a html-file named something.html
$(".documentholder").load("something.html");
in this case the class "documentholder" is the container you put the code in

How can I use a variable from an external .js file in my HTML?

I've got a function that I've written that populates a URL (that contains an image) based on the browser language. This subsequent URL is then written to a variable. All the images are based on language, so for germany it will be "de.gif", France would be "fr.gif" and so on.
My question is how can I call this variable in my HTML page?
To help me to better illustrate this problem here is the JavaScript, please note this is an EXTERNAL .js file called in the of this HTML page:
function IABEU_moused_detect() {
(function IAB_lang_detect() {"use strict";
var IAB_lang_map = {"de-at": "at","nl-be": "be-nl","fr-be": "be-fr","da": "den","de": "de","hu": "hu","en-ie": "ie","ga": "ie","es": "es","fr": "fr","it": "it","nl": "nl","no": "nor","pl": "pl","en": "uk","en-GB": "uk","en-US": "uk","en-gb": "uk","en-us": "uk"},
IAB_lang = (navigator && navigator.browserLanguage) || (window.navigator && window.navigator.language) || "en-GB";
IAB_url = ("http://www.someurl.com/" + IAB_lang_map[IAB_lang]);
IAB_img = ("http://www.myimagesarehere.com/" + IAB_lang_map[IAB_lang]+".gif");
}());}
So it's the IAB_img variable that I want to call in my HTML page (it's a global variable in the .js file)
The HTML is here:
<div>
<img src="HERE IS WHERE I WANT TO call the variable 'IAB_img'">
</div>
Thanks
EDIT: So I still can't solve this, is there a way for me to use the value in "IAB_img" as the image src in my HTML file?
I would start by giving the image an id.
<div>
<img id="TheImage" src="HERE IS WHERE I WANT TO call the variable 'IAB_img'">
</div>
Then in your JavaScript function, just assign the src of the image like so:
function IABEU_moused_detect() {
(function IAB_lang_detect() {"use strict";
var IAB_lang_map = {"de-at": "at","nl-be": "be-nl","fr-be": "be-fr","da": "den","de": "de","hu": "hu","en-ie": "ie","ga": "ie","es": "es","fr": "fr","it": "it","nl": "nl","no": "nor","pl": "pl","en": "uk","en-GB": "uk","en-US": "uk","en-gb": "uk","en-us": "uk"},
IAB_lang = (navigator && navigator.browserLanguage) || (window.navigator && window.navigator.language) || "en-GB";
IAB_url = ("http://www.someurl.com/" + IAB_lang_map[IAB_lang]);
IAB_img = ("http://www.myimagesarehere.com/" + IAB_lang_map[IAB_lang]+".gif");
var image = document.getElementById('TheImage');
image.src = IAB_img;
}());}
Are you rendering the html page via a template? If so, you could include a javascript snippet with a variable setup to be read further on:
<script type="text/javascript">
var IAB_img = {{value}};
</script>
Just put this before you load your other script, and then the IAB_img will already be defined for you.
Something like this:
<div>
<img src="javascript:document.write(IAB_img);" />
</div>

Categories

Resources