getElementById() is null? - javascript

So I am trying to make a JavaScript program that will take a URL for an image and then put it onto the page while creating an <img> tag so that I can just continue pasting as many photos as I want. Here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Low-Budget Online Album</title>
<meta charset="utf-8">
<script>
function init() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
window.onload = init;
function buttonClick() {
var imageSource = document.getElementById("imageInput").value;
if (imageSource == "") {
alert("Please enter the source for an image.");
}
else {
var newImage = document.createElement("img");
var newSrc = document.getElementById("newImage").src= imageSource;
imageInput.value = "";
}
}
</script>
</head>
<body>
<input type="text" id="imageInput" size="40" placeholder="Image Source">
<input type="button" id="addButton" value="Add Image">
<img id="images" src="">
</img>
</body>
</html>
My problem is, is that when I put int a URL (or picture src from my PC) it says that TypeError: document.getElementById(...) is null, and points to line 20, being my
var newSrc = document.getElementById("newImage").src= imageSource;
line. Any ideas?

Use this
else {
var newImage = document.createElement("img"); //this line creates element <img> element in the dom.
newImage.setAttribute("id", "newImage");
newImage.src= imageSource;
document.body.appendChild(newImage);//adds element <img src="a.jpg" id='newImage'>to the dom.
imageInput.value = "";
}
Understand what mistake you have done above:
1.First you created element and assign to a variable newImage
var newImage=document.createElement("img");
2.You are calling
document.getElementById('newImage');
Here newImage as element that you created and in the dom there is no element with id as newImage so you were getting null.

do you mean something like this:
function init() {
var button = document.getElementById("addButton");
button.onclick = buttonClick;
}
window.onload = init;
function buttonClick() {
var imageSource = document.getElementById("imageInput").value;
if (imageSource == "") {
alert("Please enter the source for an image.");
}
else {
var newImage = document.createElement("img");
newImage.src= imageSource;
newImage.setAttribute("id", "newImage");
imageInput.value = "";
document.body.appendChild(newImage);
}
}
Demo:: jsFiddle

var newImage = document.createElement("img");
var newSrc = document.getElementById("newImage").src= imageSource;
Become:
var newImage = document.createElement("img");
newImage.setAttribute('id','newImage');
var newSrc = document.getElementById("newImage").src = imageSource;

in mdn you can see that createElement only create element and not add it to DOM. So if you want add created element you need change your code like this
var newImage = document.createElement("img");
newImage.id = "newImage";
document.body.appendChild(newImage);
after this line will work
var newSrc = document.getElementById("newImage").src= imageSource;
but you don't need get find it if you already have this image in newImage variable, so this line you can change like
var newSrc = newImage.src= imageSource;
UPDATE
Possibly you need use className instead of id because id should be unique on page, but as i understand you want add many images

Related

Trying to grab a random pic through JS but dosen't work properly

Hi guys I am a django developer and trying to grab a random img through JS in html like below
img works and it would randomly pick one from the ImageArray.
However, the path will be <img src= '/static/%22%20%2B%20img%20%2B%22'>.
Rather than something I want like <img src= "{% static 'img/indexBg_1.png' %}" >
And the error msg is : GET http://192.168.7.64:8000/static/img/%22%20%2B%20pic%20%2B%20%22%20 404 (Not Found)
Could anyone enlighten me to resolve this problem? Thx!
<script type="text/javascript">
window.onload=function(){
ImageArray = new Array();
ImageArray[0] = 'img/indexBg_1.png';
ImageArray[1] = 'img/indexBg_2.png';
ImageArray[2] = 'img/indexBg_3.png';
var num = Math.floor( Math.random() * 3);
var img = ImageArray[num];
var path = " <img src= '{% static '" + img +"'%}'>"
console.log(img)
console.log(path)
}
</script>
if you want the path, it should be something like:
var path = window.location.href +'/static/'+ img;
but if you want to add image with that path inside div:
var element = document.getElementById("div1");
element.innerHTML=`<img src=${path} />`;
even better to do:
var path = window.location.href +'/static/'+ img;
var myimg = document. createElement("img");
myimg.src = path;
var element = document.getElementById("div1");
element.appendChild(myimg);

Changing background images with JavaScript

I'm fairly new to JavaScript and HTML and I can't seem to figure out want is wrong. This is part of an assignment I have for class so the structure/code is formatted the same way as an example the professor provided.
I'm trying to rotate between different background images.
This is what I have for the script:
var bakground = [];
background[0] = new Image();
background[0].src = "Images/blue.jpg";
background[1] = new Image();
background[1].src = "Images/chalkboard_web.jpg";
background[2] = new Image();
background[2].src = "Images/computer-scince-education.jpg";
background[3] = new Image();
background[3].src = "Images/universidad.jpg";
var i = 0;
var temp = new Image();
function wallpaper()
{
temp = background[i].src;
i++;
if(i == background.length)
i = 0;
document.body.background = 'temp';
return false;
}
This is where I'm calling the function:
<P/> <b> test changing document body background:</b>
<INPUT TYPE="button" NAME="button2" value="set background to an image"
onClick="wallpaper()" >
</P>
You are not using the "temp" variable you defined above but a string instead!
function wallpaper()
{
temp = background[i].src;
i++;
if(i == background.length)
i = 0;
document.body.background = temp;
return false;
}
Should work
There are several things.
Bugs:
type in background
you are setting document.body.background to the string 'temp' and not to your image.
you are using a closing p-tag to open the paragraph. Should be <p> instead of </P>
Other improvements:
you don't even need to create new Image(), the string of where to get the image should suffice.
you don't need to have temp as a global variable.
you can more easily modulo the iterator rather then re-setting it to 0
tags and attributes are case insensitive. It's common to use lowercase, though.
elements like input can / should have closing tags or be self-closing.
See example here:
<html>
<head>
<script>
var background = [
"https://source.unsplash.com/random",
"Images/wall.jpg",
"Images/1road.jpg"
];
var i = 0;
function wallpaper() {
document.body.background = background[i++];
i = i % background.length; // will wrap around the length. look up 'modulo' unsure
return false;
}
</script>
</head>
<body>
<p/>
<b> test changing document body background:</b>
<input type="button" name="button2" value="set background to an image"
onClick="wallpaper()" />
</p>
</body>
</html>

create the variable link as a hyperlink javascript

create a hyperlink with the variable link
<html>
<body>
<center><h1> retrive data</h1></center>
<h1 id="head1"> </h1>
<input type="text" placeholder="enter your unique id" id="pass"/>
<input type = "button" value = "submit" id="but" onclick="myfunction();"/>
<script>
var pass;
function myfunction()
{
pass = document.getElementById("pass").value;
document.writeln(pass);
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
document.writeln("<br>");
var passwordToLookFor = pass;
var ref = firebase.database().ref("users");
var query = ref.orderByChild("password").equalTo(passwordToLookFor);
query.once("value").then(function(snapshot) {
snapshot.forEach(function(child) { // loop over the results
console.log(child.key);
console.log(child.val().user_name);
var link = child.val().user_name;
document.writeln(link);
});
});
}
</script>
</body></html>
i want to create the value of link as a hyperlink
i want the hyperlink to be created once when the function is called
Are you just looking for how to make it an anchor tag?
<script>
var pass;
function myfunction()
{
...
var link = child.val().user_name;
document.writeln("<a href='"+link+"' target='_blank'>"+link+"</a>");
});
});
}
</script>
</body></html>
You can create an a dom element like this:
let link_el = document.createElement('a')
link_el.href = link // assuming link holds the value of the href you want
Then insert it into the dom wherever you want.
If I understand correctly and the link variable contains the actual address you want to navigate to, then this will work. First simply set an ID on the div you want to populate with links:
<div id="target-div"></div>
Then populate it like so (I just created an array for demo purposes, but this would be your snapshot.forEach:
var links = ['link1', 'link2', 'link3']
var targetDiv = document.getElementById("target-div");
links.forEach(function(link) {
var anchor = document.createElement('a');
anchor.href = link;
anchor.innerText = link;
targetDiv.appendChild(anchor);
var br = document.createElement('br');
targetDiv.appendChild(br);
});
Demo: https://jsfiddle.net/csnuh7rd/2/

How to display dynamic url image in html from which created by javascript

I am trying to display the image directly in HTML through a dynamic link I generated by Javascript.
function dynamicUrl() {
var url = "http://xxx.xxx.xxx" + dynamic_variables + ".jpg";
return url;}
Most of my research, people display image by click on buttons
or what I can do for now is link to the image.
test
Anyone know how to directly display the image using the dynamic URL?
Thanks!
Dynamic create DOM for example:
function dynamicUrl() {
var url = "https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg";
return url;
}
var img = document.createElement("img");
img.src = dynamicUrl();
document.body.appendChild(img);
Manipulate DOM to dynamic change img url:
function dynamicUrl() {
var url = "https://www.62icon.com/client/assets/img/like-icon.svg";
var img = document.getElementById('imageid');
img.src = url;
}
<div>
<p>Image goes here</p>
<button onclick="dynamicUrl()">Change Image</button>
</div>
<img id="imageid" src="https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg" />
Adding a id for the link element
<a id="link" href="">test</a>
Using click event of link element
var link = document.getElementById("link");
link.onclick = function goToDynamicUrl() {
var url = "https://image.flaticon.com/teams/new/1-freepik.jpg";
window.location.href = url;
}
Here is another method:
<div id="dimg">Here add image</div>
<script>
var dimg = document.getElementById('dimg');
function addImg(dv){
dimg.innerHTML ='<img src="http://xxx.xxx.xxx'+ dv +'.jpg'" >';
}
addImg('imgname');
</script>

Name an id dynamically with javascript?

How can I dynamically name id's using javascript?
Something like this:
js:
var idName = "fruit";
html:
<img id="javascript:idName" src="banana.jpg">
var bananaImage = new Image();
bananaImage.id = "fruit";
bananaImage.src = "banana.jpg";
Using the jQuery framework you could do something like:
<img class="idName" src="banana.jpg"/>
<img class="idName" src="cherry.jpg"/>
The script ...
var idName = 'fruit';
$(function() {
$('img.idName').each(function(i) {
$(this).attr({id: idName+i});
});
});
... which results in:
<img id="fruit0" class="idName" src="banana.jpg"/>
<img id="fruit1" class="idName" src="cherry.jpg"/>
You can dynamically create elements, such as <img>, and set their attributes using JavaScript's DOM API.
or you can get the element any other way IE
imgs = container.getElementsByTagName("img");
foreach(imgs as img){
if(imgs.src == "banana.jpg") img.id = "fruit";
}
Note: foreach doesn't work in JS you'll need a for loop, but I'm too lazy :P
I think this is what your looking for. You need some sort of event to trigger the JavaScript. Since IMG doesnt have it, except for user events, you need something like:
<head>
<script language="JavaScript" type="text/javascript">
function nameMyIds() {
var idToName = "firstImageId";
var theImage = getImageBySrc("banana.jpg");
if (theImage!=null)
theImage.id = idToName;
}
function getImageBySrc(src) {
// using DOM, using jQuery would make this easier
var allImages = document.body.getElementsByTagName("IMG");
for (var i=0; i<allImages.length; i++ ) {
var img = allImages[i];
var i = img.src.indexOf(src);
if (img.src == src || img.src.indexOf(src) > 0) { return img };
}
}
</script>
</head>
<body onload="nameMyIds()">
<img src="banana.jpg">
</body>

Categories