Javascript Variable for img src? - javascript

I can't find the problem with this code and I've been having way too much trouble with it tonight, can anyone help me out?
<html>
<script type="text/javascript">
var image = new Array ();
image[0] = "header1.png";
image[1] = "header2.png";
image[2] = "header3.png";
image[3] = "header4.png";
var size = image.length
var x = Math.floor(size*Math.random())
var backgroundImageFile = image[x];
var backgroundImageUrl = "url('" + backgroundImageFile + "')";
$('#header-image').css('background-image', 'backgroundImageUrl');
function op()
{
document.getElementById('header-image').innerHTML=backgroundImageUrl;
}
</script>
<body onload="op();">
<img src="backgroundImageFile">
</body>
</html>

You may try for this:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var image = new Array ();
image[0] = "https://www.w3schools.com/angular/pic_angular.jpg";
image[1] = "https://www.w3schools.com/images/colorpicker.gif";
image[2] = "https://www.w3schools.com/angular/pic_angular.jpg";
image[3] = "https://www.gstatic.com/images/branding/googlelogo/2x/googlelogo_dark_color_84x28dp.png";
var size = image.length
var x = Math.floor(size*Math.random());
var backgroundImageFile = image[x];
$('#imageId')[0].setAttribute('src',backgroundImageFile);
});
</script>
</head>
<body>
//displays circle with dimensions
image here:
<img src="backgroundImageFile" id="imageId">
</body>
</html>

Please find the solution: I think you are looking for same.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<script type="text/javascript">
var image = new Array ();
image[0] = "header1.png";
image[1] = "header2.png";
image[2] = "header3.png";
image[3] = "header4.png";
var size = image.length
var x = Math.floor(size*Math.random())
var backgroundImageFile = image[x];
var backgroundImageUrl = "url('" + backgroundImageFile + "')";
$('#header-image').css('background-image', 'backgroundImageUrl');
function op()
{
document.getElementById('header-image').innerHTML=backgroundImageUrl;
}
</script>
<body onload="op();">
<img src="backgroundImageFile">
<div id="header-image"></div>
</body>
</html>

Related

How to add the returned value from a JavaScript function into an HTML element [duplicate]

I am looking for a way to call a javascript number in the body of an html page. This does not have to be long and extravagant just simply work, I just want something like:
<html>
<head>
<script type="text/javscript">
var number = 123;
</script>
</head>
<body>
<h1>"the value for number is: " + number</h1>
</body>
</html>
Try This...
<html>
<head>
<script>
function myFunction() {
var number = "123";
document.getElementById("myText").innerHTML = number;
}
</script>
</head>
<body onload="myFunction()">
<h1>"The value for number is: " <span id="myText"></span></h1>
</body>
</html>
Use document.write().
<html>
<head>
<script type="text/javascript">
var number = 123;
</script>
</head>
<body>
<h1>
the value for number is:
<script type="text/javascript">
document.write(number)
</script>
</h1>
</body>
</html>
<html>
<head>
<script type="text/javascript">
var number = 123;
var string = "abcd";
function docWrite(variable) {
document.write(variable);
}
</script>
</head>
<body>
<h1>the value for number is: <script>docWrite(number)</script></h1>
<h2>the text is: <script>docWrite(string)</script> </h2>
</body>
</html>
You can shorten document.write but
can't avoid <script> tag
<script type="text/javascript">
function get_param(param) {
var search = window.location.search.substring(1);
var compareKeyValuePair = function(pair) {
var key_value = pair.split('=');
var decodedKey = decodeURIComponent(key_value[0]);
var decodedValue = decodeURIComponent(key_value[1]);
if(decodedKey == param) return decodedValue;
return null;
};
var comparisonResult = null;
if(search.indexOf('&') > -1) {
var params = search.split('&');
for(var i = 0; i < params.length; i++) {
comparisonResult = compareKeyValuePair(params[i]);
if(comparisonResult !== null) {
break;
}
}
} else {
comparisonResult = compareKeyValuePair(search);
}
return comparisonResult;
}
var parcelNumber = get_param('parcelNumber'); //abc
var registryId = get_param('registryId'); //abc
var registrySectionId = get_param('registrySectionId'); //abc
var apartmentNumber = get_param('apartmentNumber'); //abc
</script>
then in the page i call the values like so:
<td class="tinfodd"> <script type="text/javascript">
document.write(registrySectionId)
</script></td>
Here is another way it can be done .
function showData(m)
{
let x ="<div> added from js ";
let y = m.toString();
let z = "</div>";
let htmlData = x+y+z ;
content.insertAdjacentHTML("beforeend",htmlData);
}
You can do the same on document ready event like below
<script>
$(document).ready(function(){
var number = 112;
$("yourClass/Element/id...").html(number);
// $("yourClass/Element/id...").text(number);
});
</script>
or you can simply do it using document.write(number);.
<?php
$x1='<span id="x1"></span><script>document.getElementById("x1").innerHTML = x1;</script>';
$x2='<span id="x2"></span><script>document.getElementById("x2").innerHTML = x2;</script>';
$x3='<span id="x3"</span><script>document.getElementById("x3").innerHTML = x3;</script>';
?>
<html><body>
<script> var
x1="123",
x2="ABC",
x3=666;
</script>
<?php echo $x1 ?><br>
<?php echo $x2 ?><be>
<?php echo $x3 ?><be>
</body></html>
Index.html:
<html>
<body>
Javascript Version: <b id="version"></b>
<script src="app.js"></script>
</body>
</html>
app.js:
var ver="1.1";
document.getElementById("version").innerHTML = ver;
You cannot add JavaScript variable to HTML code.
For this you need to do in following way.
<html>
<head>
<script type="text/javscript">
var number = 123;
document.addEventListener('DOMContentLoaded', function() {
document.getElementByTagName("h1").innerHTML("the value for number is: " + number);
});
</script>
</head>
<body>
<h1></h1>
</body>
</html>

Google Maps iFrame not loading when using javascript variables on "src"

I have an html file with javascript used to get the exif data out of an image, more specifically GPS latitude and longitude.
That data is the converted to a format readable by a Google Maps iFrame to then show where that photo was taken...
The problem I'm having at the moment is on the use of JavaScript variables that contain the values of the latitude and longitude on the "src" of the iFrame.
If I use the specific values on the source, the iFrame loads correctly on that specific location... but if I replace them with the variables that DO have the same exact values, nothing loads... the iFrame stays blank.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>EXIF</title>
<style>
img{
width: 500px;
max-height: auto;
}
</style>
</head>
<body>
<img src="https://c1.staticflickr.com/5/4867/30883801817_bf122bc498_o.jpg" id="img1" />
<iframe id="mapa_google" src="" width="640" height="480"></iframe>
<h1>Latitude Exif</h1>
<p id="local_lat"></p>
<h1>Longitude Exif</h1>
<p id="local_lon"></p>
<h1>Latitude Final</h1>
<p id="local_lat_final"></p>
<h1>Longitude Final</h1>
<p id="local_lon_final"></p>
<script src="exif.js"></script>
<script>
var toDecimal = function (number) {
var d = Math.floor(number[0]);
var m = Math.floor(number[1]);
var s = ((number[1]%1)*60);
var dms= d+(m/60)+(s/3600);
return dms
};
window.onload=getExif;
function getExif() {
img1 = document.getElementById("img1");
EXIF.getData(img1, function() {
latitude = EXIF.getTag(this, "GPSLatitude");
longitude = EXIF.getTag(this, "GPSLongitude");
local_lat = document.getElementById("local_lat");
local_lon = document.getElementById("local_lon");
local_lat.innerHTML = `${latitude}`;
local_lon.innerHTML = `${longitude}`;
latitude_final = toDecimal(latitude);
local_lat_final = document.getElementById("local_lat_final");
local_lat_final.innerHTML = `${latitude_final}`;
longitude_final = toDecimal(longitude);
local_lon_final = document.getElementById("local_lon_final");
local_lon_final.innerHTML = `${longitude_final}`;
});
}
getExif();
document.getElementById("mapa_google").src = "https://www.google.com/maps/embed/v1/place?key=AIzaSyDQSbRMCIv1gDsT2qRsY8HvLyZP11hte_Y&q="+latitude_final+"+"+longitude_final;
/* IF I USE THE CODE BELOW WITH THE SPECIFIC LATITUDE AND LONGITUDE, THE iFrame works perfectly but id I use the one above, with the variables that contain those same values, nothing loads on that iFrame... it stays blank*/
document.getElementById("mapa_google").src = "https://www.google.com/maps/embed/v1/place?key=AIzaSyDQSbRMCIv1gDsT2qRsY8HvLyZP11hte_Y&q=41.38448666666667+2.1066883333333335";
</script>
</body>
</html>
The getExif() function is asynchronous. You need to use the results of the asynchronous load of the <img> inside the callback function, once the image has loaded.
function getExif() {
img1 = document.getElementById("img1");
EXIF.getData(img1, function() {
latitude = EXIF.getTag(this, "GPSLatitude");
longitude = EXIF.getTag(this, "GPSLongitude");
local_lat = document.getElementById("local_lat");
local_lon = document.getElementById("local_lon");
local_lat.innerHTML = `${latitude}`;
local_lon.innerHTML = `${longitude}`;
latitude_final = toDecimal(latitude);
local_lat_final = document.getElementById("local_lat_final");
local_lat_final.innerHTML = `${latitude_final}`;
longitude_final = toDecimal(longitude);
local_lon_final = document.getElementById("local_lon_final");
local_lon_final.innerHTML = `${longitude_final}`;
document.getElementById("mapa_google").src = "https://www.google.com/maps/embed/v1/place?key=AIzaSyDQSbRMCIv1gDsT2qRsY8HvLyZP11hte_Y&q=" + latitude_final + "+" + longitude_final;
});
proof of concept fiddle
code snippet:
img {
width: 500px;
max-height: auto;
}
<script src="https://cdn.jsdelivr.net/gh/exif-js/exif-js#2.3.0/exif.js"></script>
<img src="https://c1.staticflickr.com/5/4867/30883801817_bf122bc498_o.jpg" id="img1" onload="getExif();" />
<iframe id="mapa_google" src="" width="640" height="480"></iframe>
<h1>Latitude Exif</h1>
<p id="local_lat"></p>
<h1>Longitude Exif</h1>
<p id="local_lon"></p>
<h1>Latitude Final</h1>
<p id="local_lat_final"></p>
<h1>Longitude Final</h1>
<p id="local_lon_final"></p>
<script>
var toDecimal = function(number) {
var d = Math.floor(number[0]);
var m = Math.floor(number[1]);
var s = ((number[1] % 1) * 60);
var dms = d + (m / 60) + (s / 3600);
return dms
};
// window.onload = getExif;
function getExif() {
img1 = document.getElementById("img1");
EXIF.getData(img1, function() {
latitude = EXIF.getTag(this, "GPSLatitude");
longitude = EXIF.getTag(this, "GPSLongitude");
local_lat = document.getElementById("local_lat");
local_lon = document.getElementById("local_lon");
local_lat.innerHTML = `${latitude}`;
local_lon.innerHTML = `${longitude}`;
latitude_final = toDecimal(latitude);
local_lat_final = document.getElementById("local_lat_final");
local_lat_final.innerHTML = `${latitude_final}`;
longitude_final = toDecimal(longitude);
local_lon_final = document.getElementById("local_lon_final");
local_lon_final.innerHTML = `${longitude_final}`;
document.getElementById("mapa_google").src = "https://www.google.com/maps/embed/v1/place?key=AIzaSyDQSbRMCIv1gDsT2qRsY8HvLyZP11hte_Y&q=" + latitude_final + "+" + longitude_final;
});
}
// getExif();
</script>

Javascript Warp Time with Warp js

I'm working on a project where I need to manipulate time speed forward and backward. This module seems like what I need but I can't get it working:
https://github.com/mattbradley/warpjs/blob/master/README.md
Any help appreciated
<html>
<head>
</head>
<body>
<script src="jquery.min.js"></script>
<script src="warp.js"></script>
<div id="container"></div>
<span id="info"></span><br>
<span id="time"></span>
<span id="time2"></span>
<script>
setInterval(function() {
var now = new Date;
now = Date.warp.clock(true);
//now = Date.warp.speed(2); // DOESNT WORK?
var dateD = [now.getMonth() + 1,now.getDate(),now.getFullYear()];
var dateE = [now.getHours(),now.getMinutes(),now.getSeconds()];
var MDY = dateD.join("/");
var HMS = dateE.join(":");
time.innerHTML = (MDY);
time2.innerHTML = (HMS);
}, 20);
</script>
</body>
</html>
The wrap is a static method, it doesn't return any value(undefined is returned)
setInterval(function() {
Date.warp.speed(3);
var now = new Date;
var dateD = [now.getMonth() + 1, now.getDate(), now.getFullYear()];
var dateE = [now.getHours(), now.getMinutes(), now.getSeconds()];
var MDY = dateD.join("/");
var HMS = dateE.join(":");
time.innerHTML = (MDY);
time2.innerHTML = (HMS);
}, 1000);
Demo: Fiddle

Array sort build in function

I was wondering what's wrong with my program. Am i having a syntax error or am i missing something in my build in array sort?. I'm pretty sure the problem lies within the "for" loop but i cant seem to find it. Some suggestion or help would be great.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function leaderboard()
{
var temp1;
var temp2;
var temp3;
var temp4;
var temp5;
temp1 = 10
temp2 = 20
temp3 = 30
temp4 = 40
temp5 = 50
var leader = new Array(5);
leader[0] = temp1;
leader[1] = temp2;
leader[2] = temp3;
leader[3] = temp4;
leader[4] = temp5;
leader.sort(function(a,b){return b-a});
var myContent = '';
for (var d=0;d<5;d++)
{
myContent += "score: " + leader[d] + "<BR>";
}
document.getElementById("leaderboard").innerHTML = myContent;
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> leaderboard() </SCRIPT>
</BODY>
</HTML>
You are trying to write the o/p to an element with id leaderboard which is not present in the page. Which is giving an error Uncaught TypeError: Cannot set property 'innerHTML' of null - it is not a syntax error.
So just create an element with the id leaderboard as shown below
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function leaderboard()
{
var temp1;
var temp2;
var temp3;
var temp4;
var temp5;
temp1 = 10
temp2 = 20
temp3 = 30
temp4 = 40
temp5 = 50
var leader = new Array(5);
leader[0] = temp1;
leader[1] = temp2;
leader[2] = temp3;
leader[3] = temp4;
leader[4] = temp5;
leader.sort(function(a,b){return b-a});
var myContent = '';
for (var d=0;d<5;d++)
{
myContent += "score: " + leader[d] + "<BR>";
}
document.getElementById("leaderboard").innerHTML = myContent;
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<div id="leaderboard"></div>
<SCRIPT LANGUAGE = "Javascript"> leaderboard() </SCRIPT>
</BODY>
</HTML>
Demo: Fiddle

Same random image on push with a button

I am trying to make this code to generate a random number of 10 images, so every time I click the button I will get a random number of images and I just want this 1 image and the button doesn't disappear so I can try again.
<!DOCTYPE html>
<html>
<body>
<input class="randombutton" type="button" value="Randomize" onclick="randomImg1()"/>
<script type="text/javascript">
function randomImg1() {
myImages1 = "Myimage.jpg";
var rnd = Math.floor( Math.random() * 10 );
document.write(myImages1[rnd]);
}
</script>
</body>
</html>
myImages1 is a string an not an array. And you need to multiple the random() by the number of elements in the array.
function randomImg1() {
var myImages1 = ['Myimage.jpg'];
var rnd = Math.floor(Math.random() * myImages1.length );
document.write(myImages1[rnd]);
}
You'll need to update the content dynamically, not using document.write. In addition, myImages1 must be an array.
<!DOCTYPE html>
<html>
<body>
<input class="randombutton" type="button" value="Randomize" onclick="randomImg1()"/>
<script type="text/javascript">
function randomImg1() {
myImages1 = new Array();
myImages1[0] = "Myimage.jpg";
myImages1[1] = "Myimage1.jpg";
var rnd = Math.floor( Math.random() * myImages1.length ); //incorporated other solution
document.getElementById("image").innerHTML = "<img src='" + myImages1[rnd] + "' alt='image'></img>";
}
</script>
<div id="image"></div>
</body>
</html>

Categories