I'm supposed to display an image after the user inserts its URL. It works fine on the first click, but instead of replacing the previous image with the new URL when the user input a new one, it just creates a new image below the previous.
That's my function so far:
HTML:
<p id="tt">Display an image using the image's URL</p>
<label>URL:
<textarea rows="1" cols="40" placeholder="Image URL" id="url"></textarea>
</label><br>
<label>Caption:
<textarea rows="1" cols="40" placeholder="Image caption" id="caption"></textarea>
</label><br>
<button id="btn">Add Image</button>
<br>
<div id="imgDiv"></div>
JS:
var getBtn = document.getElementById("btn");
getBtn.addEventListener('click', function() {
var figure = document.createElement("figure");
var image = document.createElement("IMG");
var figcaption = document.createElement("figcaption");
//attributing the input value in the first textarea as source for the image to be displayed
var url = document.getElementById("url").value;
image.src = url;
image.height = "200";
image.id = "newImage";
figure.appendChild(image);
//making the image a link to its url
var a = document.createElement("a");
a.href = url;
a.appendChild(image);
figure.appendChild(a);
//creating a Node and setting the input value from the second textarea as caption
var caption = document.getElementById("caption").value;
var text = document.createTextNode(caption);
document.getElementById("imgDiv").appendChild(figure);
figure.appendChild(figcaption);
figcaption.appendChild(text);
document.getElementById("menu").add(option);
//clear textarea after submitting url and caption
document.getElementById("url").value = "";
document.getElementById("caption").value = "";
});
EDIT - JSFiddle: https://jsfiddle.net/hpnLycer/4/
Can someone give me a hint how to solve this?
I tried understanding by reading "similar" questions, but I didn't find any that would solve my case.
Thank you anyway.
Hope this snippet will be useful
HTML
<input type ="text" id="imageIp" placeholder="New Image url"> <button id ="changeDisplay" > Change Display </button>
<div class ="demoDiv" id = "demoDiv">
</div>
CSS
.demoDiv{
margin-top:10px;
height:300px;
width:300px;
background-image: url("http://freebigpictures.com/wp-content/uploads/shady-forest.jpg");
JS
var getButton = document.getElementById("changeDisplay");
getButton.addEventListener('click',function(){
var getNewImage = document.getElementById("imageIp").value;
console.log(getNewImage);
document.getElementById("demoDiv").style.backgroundImage = "url('"+getNewImage+"')";
})
WORKING EXAMPLE
EDIT
In the latest snippet you have not defined these two arrays
imageArray
captionArray
You need to define them before you can push content in it.I have initialized that at the beginning but you can put them accordingly.But they must be initialized before you can put content in it.
var getBtn = document.getElementById("btn");
var imageArray = []; // Initializing imageArray
var captionArray=[]; // Initializing captionArray
getBtn.addEventListener('click', function() {
// rest of code
))
NOTE:Also in your snippet there is no HTML element with id menu,so when I run this code it thrown an error.
WORKING EXAMPLE WITH SUPPLIED CODE
Related
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 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/
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>
I am developing a small web application specifically for IE8 (I know you all feel the pain already). In this application, I have an Update "button" that (when clicked) generates a box where they user can click Yes or No. I used JavaScript to generate the box and the input tag with type="submit".
Here is a snippet of the code:
HTML
<form action="." method="POST" id="yield_curve_form" enctype="multipart/form-data">
<div class="fileUploadDiv">
<img id="yieldCurve" src="../img/market/yield_curve.jpg" alt="ZBPF Bond Market" >
<div class="fileUploadButton">
<span>Upload New Image</span>
<input type="file" name="image_file" accept="image/*" class="uploadInput">
</div>
<div class="fileUploadReq">
<p>Image Requirements:</p>
<ul>
<li>Format: .png, .jpg, .jpeg, .bmp, .tif, .tiff</li>
<li>Resolution: 650 x 383</li>
<li>Maximum size: 2.0 MB</li>
</ul>
</div>
</div>
<button type="button" class="marketUpdateButton" onclick="confirmUpdate('yield_curve');">Update</button>
JS
function confirmUpdate(name)
{
// Create a div element
var div = document.createElement('div');
// Give it an ID
div.id = 'preSubmitAlert';
// Create a child h2 tag
var h2 = document.createElement('h2');
h2.innerHTML = 'This is a permanent change';
// Create a child p tag
var pMessage = document.createElement('p');
pMessage.innerHTML = 'Did you double check the data? It is important the data is accurate before you submit it.';
// Create child input tags
var inputYes = document.createElement('input');
var inputNo = document.createElement('input');
// Set parameters for input tags
inputYes.type = 'submit';
inputYes.name = name + '_update';
inputYes.value = 'Yes. Update the data.';
inputYes.id = 'inputYes';
inputNo.type = 'button';
inputNo.value = 'No. Take me back, please.';
inputNo.id = 'inputNo';
// Append the children to
div.appendChild(h2);
div.appendChild(pMessage);
div.appendChild(inputYes);
div.appendChild(inputNo);
// Create the background for transparency (needed for IE8 support)
var bg_div = document.createElement('div');
bg_div.id = 'bg_div';
// Create a screen and append the above div to it
var screenDiv = document.createElement('div');
screenDiv.id = 'screenDiv';
// Appending div and bg_div to screenDiv
screenDiv.appendChild(div);
screenDiv.appendChild(bg_div);
// Appending screenDiv to the body tag
document.body.appendChild(screenDiv);
// This line needs a reference to the #screenDiv is, which is inserted in the DOM only in the above line.
inputNo.onclick = function(){destroyElement(document.getElementById('screenDiv'))};
inputYes.setAttribute('form', name + '_form');
}
Question
Why isn't the the <input type="submit" ...> not submitting the data when clicked?
Obs.: This piece of code works on every other browser, including higher versions of IE.
Thank you in advance.
Change this...
document.body.appendChild(screenDiv);
To this...
document.getElementById(name + '_form').appendChild(screenDiv);
I doubt very much that IE8 supports the HTML5 form attribute so you'll need to make the submit button a descendant of the form.
I can't find any official documentation on this though and I doubt anybody is going to the trouble of researching it properly.
hope someone can help a noob. Many thanks in advance.
I have an index page with links to hundreds of other pages holding song words.
I have built each song page but it would be MUCH simpler to have one MASTER page that took a variable from the index page and found the corresponding words (which exist as png graphics.)
I have sorted Step 1 - I can pass a variable from the index page to the master page using:
<a href="javascript: window.open('MUSIC/beatles/mastertest2.html?song=ER', '_parent')">
where song=ER is the variable to display the words for Eleanor Rigby. For Step 2, I can also retrieve that information in the master page with:
var imageSrc = (qs("song")+".png"); document.write(imageSrc);
which will display the text ER.png which is the name of the image I want to display.
For Step 3 I am trying to get this same variable read into:
<input type="image" src="imageSrc;">
to display the picture. I have searched this and other forums for days now and nothing suggested works for me. I could be missing out an essential early step in the coding?
Update:
My master html file has this code to retrieve the variable:
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
And it uses this code to disply the variable (appended with .png) just to prove to me that it is getting through:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
Then I am trying to feed the variable into a routine to display the png selected. The next script doesn't work but I am thrashing about trying anything right now:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
<input type="image" src="#imageSrc;" border="0" value="Notes" onClick="placeIt(); showIt()">
<input id="song-image" type="image">
var imageSrc = 'ER.png';
var input = document.getElementById('song-image');
input.src = imageSrc;
If you have already <input type="image"> in your HTML page, you must add an id and then set it's src attribute with
HTML:
<input id="song-image" type="image">
JS:
var imageSrc = 'http://www.lorempixel.com/200/100';
var input = document.getElementById('song-image');
input.src = imageSrc;
JSFiddle for testing.
If I understood you right, its very simple. Are you looking for this?
var input = document.createElement('input');
input.type = 'image';
input.src = imageSrc;
document.body.appendChild(input);
If you can print the variable imageSrc using document.write, then you can use it like shown above.