Check my JS Fiddle: https://jsfiddle.net/oxfre6kj/1/
I have a button that creates as many images as you want, but when I refresh the page those images are gone, I want them to be still there after I click the save button.
Here is what I tried it works with variable but it doesn't work with "img"
<button onclick="createImage()">Create Image</button>
<button onclick="saveImages()">Save Images</button>
<div id="image"></div>
<script>
function createImage() {
var img = document.createElement('img');
img.src = 'http://via.placeholder.com/350x150';
document.getElementById('image').appendChild(img);
}
var image = localStorage.getItem('image');
alert(image);
function saveImage() {
localStorage.setItem("images", image);
}
</script>
is this how you want the page to work ?
HTML :
<button id="create_image">Create Image</button>
<button onclick="saveImages()">Save Images</button>
<label for="image_url">Image url :</label>
<input type="text" id="image_url" value="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded" placeholder="img url">
<div id="images"></div>
JAVASCRIPT :
document.getElementById("create_image").addEventListener("click", function() {
const url = document.getElementById("image_url").value;
createImage(url);
});
var images = localStorage.getItem('image');
loadImagesFromLocal();
function createImage(src) {
var img = document.createElement('img');
img.src = src;
img.onload = function() {
document.getElementById('images').appendChild(img);
}
}
function saveImages(img) {
const images = document.querySelectorAll(`div#images img`);
var savedImagesSrc = JSON.parse(localStorage.getItem("images")) || [];
savedImagesSrc = Array.from(savedImagesSrc);
for (var i = savedImagesSrc.length; i < images.length; i++) {
savedImagesSrc.push(images[i].src);
}
localStorage.setItem("images", JSON.stringify(savedImagesSrc));
}
function loadImagesFromLocal() {
const savedImagesSrc = JSON.parse(localStorage.getItem("images")) || [];
for (var i = 0; i < savedImagesSrc.length; i++) {
createImage(savedImagesSrc[i]);
}
}
Related
var squares = document.querySelectorAll('td');
var img1 = document.createElement("img");
img1.src = "Group 1.svg";
var img2 = document.createElement('img');
img2.src = "Ellipse 1.svg";
function changeMarker() {
if (this.textContent == '') {
this.appendChild(img1);
} else if (childElements[this].localName != null) {
this.appendChild(img2);
} else {
this.textContent = '';
}
}
for (var i = 0; i < squares.length; i++) {
squares[i].childNode.addEventListener('click', changeMarker);
}
The method .getElementsByTagName is available for you to use. Since we get the container first then call that element's copy of this method, we just look inside it and ignore the rest of the document.
<!doctype html>
<html>
<head>
<script>
"use strict";
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt)
{
let d1 = byId('div1');
let d2 = byId('div2');
let imgCount1 = d1.getElementsByTagName('img').length;
let imgCount2 = d2.getElementsByTagName('img').length;
d1.textContent += ` - Img Count: ${imgCount1}`;
d2.textContent += ` - Img Count: ${imgCount2}`;
}
</script>
</head>
<body>
<div id='div1'>No image</div>
<div id='div2'>2 images<img><img></div>
<img><img><img>
</body>
</html>
I have 2 image fields and I want to display a preview before submitting the form. In the form below, it works by displaying multiple images, but I want each input to show its images separately as:
Input1
Input 1 images
Input 2
Input2 images
How do I do this?
<input id="fileupload" type="file" name="img_slide" multiple>
<div id="dvPreview">
<input id="fileupload2" type="file" name="img_capa" multiple>
<div id="dvPreview2">
<script>
window.onload = function () {
var fileUpload = document.getElementById("fileupload");
fileUpload.onchange = function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = document.getElementById("dvPreview");
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for (var i = 0; i < fileUpload.files.length; i++) {
var file = fileUpload.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.height = "100";
img.width = "100";
img.src = e.target.result;
dvPreview.appendChild(img);
dvPreview.appendChild(textbox);
}
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
}
};
I tried this and works for me. Code:
<pre>Please enter your files:<input class="fileupload" type="file" name="img_slide" multiple>
<div id="dvPreview"></div></pre>
<input class="fileupload" type="file" name="img_capa" multiple>
<div id="dvPreview2"></div>
window.onload = function () {
var fileUpload = document.getElementsByClassName("fileupload");
for(var i = 0; i < fileUpload.length; i++){
fileUpload[i].onchange = showImgOnChange;
}
}
var showImgOnChange = function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = this.nextElementSibling;
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for (var i = 0; i < this.files.length; i++) {
var file = this.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.height = "100";
img.width = "100";
img.src = e.target.result;
dvPreview.appendChild(img);
dvPreview.appendChild(textbox);
}
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
}
Now i will explain that code:
i use a single class for every input of that type. Using that class i get all the elements input and at every input i assign onchange the function showImgOnChange (just a trick to associate the same function on change to multiple elements). After that, in the function, to generalize this:
var dvPreview = document.getElementById("dvPreview");
I used this:
var dvPreview = this.nextElementSibling;
This takes the next element to the this element in the DOM. Otherwise you can associate a class to divs wich you would display the images and search for the next elements to this having that class.
Hope it helps
I am trying to have a function which has functions that do the following.
One function to store the files i get with input into the parent functions loadedimages array(loadimages).
One function to show those files in the correct component(showLoadedImages).
And one function to make the correct img file appear on the correct component.
The last function is what i want it to be like(it does not work).
The other two seem ok.
The problem i have is how to make the last function work while using the loadedimages array. You can change what i store in the array , i wouldnt mind.
Here is the JS code:
function imgviewer() {
"use strict";
var loadedimages = [];
var lidivs = [];
function loadimages() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
break;
}
loadedimages.push(file);
}
}
function showLoadedImages(elem) {
loadimages();
var ld = loadedimages;
//var files = getLoadedImages(); //filelist obj
for (var i = 0; i < ld.length; i++) {
var file = ld[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement(
'span');
span.innerHTML = [
'<img class="tile" src="',
e.target.result,
'" title="', encodeURI(
file.name), '">'
].join('');
document.getElementById(elem).insertBefore(
span, null);
lidivs.push(span);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
function showImage(index, elem) {
var chosenFile = loadedimages[index];
document.getElementById(elem).src = chosenFile;
}
document.getElementById('images').addEventListener('change', function(){
showLoadedImages("main");
}, false);
}
And some HTML
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg" width="1200" height="832" alt=""/></div>
<div id="main"></div>
When i call showLoadedImages("main") the images are shown in main div. I want to be able to click those images so that they appear on "willchange" .
This does what you asked for. There are a number of other issues with your code that you might want to address, starting with the images are not thumbnails at all (and shrunken images take just as long to load as the original), but perhaps I'm missing something.
"use strict";
var loadedimages = [];
var lidivs = [];
function loadimages() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
continue;
}
loadedimages.push(file);
}
loadedimages.length || alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
}
function showLoadedImages(elem) {
loadimages();
var ld = loadedimages;
//var files = getLoadedImages(); //filelist obj
for (var i = 0; i < ld.length; i++) {
var file = ld[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement(
'span');
span.innerHTML = [
'<img data-index="',
lidivs.length,
'" class="tile" src="',
e.target.result,
'" title="', encodeURI(
file.name), '">'
].join('');
span.addEventListener("click", foo );
document.getElementById(elem).insertBefore(
span, null);
lidivs.push(span);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
function showImage(index, elem) {
document.getElementById(elem).src = lidivs[index].children[0].src;
}
function foo(event) {
showImage(event.target.dataset.index, "willchange");
}
function show() {
showLoadedImages("list");
}
function init() {
document.getElementById("images").addEventListener("change", show, false);
}
document.addEventListener( "DOMContentLoaded", init, false );
<body>
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg" width="1200" height="832" alt=""/></div>
</body>
I have to change the src of an image using java script and I am pretty sure i hit a road block, in the html I have 3 li elements and in the id is the source of the mouseenter img. I feel like I am close but so far. Heres my code so far. Thanks for any help!
Javascript:
var $ = function (id) {
return document.getElementById(id);};
window.onload = function () {
var links = document.getElementsByTagName("li"),
imgElements = document.getElementsByTagName("img"),
imgNode,
i,
URLone,
URLtwo,
link,
image;
for (i = 0; i < imgElements.length; i++) {
imgNode = imgElements[i];
}
imgNode.mouseenter = function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}
imgNode.mouseout = function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
};
//preload
for (i = 0; i < links.length * 2; i++) {
link = links[i];
image = new Image();
image.src = link.src;
image = new Image();
image.src = link.id;
}};
HTML ::
<body>
<section>
<h1>Ram Tap Combined Test</h1>
<ul id="image_rollovers">
<li><img src="images/h1.jpg" alt="" id="images/h4.jpg"></li>
<li><img src="images/h2.jpg" alt="" id="images/h5.jpg"></li>
<li><img src="images/h3.jpg" alt="" id="images/h6.jpg"></li>
</ul>
</section>
Working jQuery :
$(document).ready(function() {
$("#image_rollovers img").each(function() {
var oldURL = $(this).attr("src"); // gets the src attribute
var newURL = $(this).attr("id"); // gets the id attribute
// preload images
var rolloverImage = new Image();
rolloverImage.src = newURL;
$(this).hover(
function() {
$(this).attr("src", newURL); // sets the src attribute
},
function() {
$(this).attr("src", oldURL); // sets the src attribute
}
); // end hover
}); // end each
}); // end ready
for (i = 0; i < imgElements.length; i++) {
(function(imgNode) {
imgNode.addEventListener("mouseenter", function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}, false);
imgNode.addEventListener("mouseout", function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
}, false);
})(imgElements[i]);
}
A couple of problems in your code.
First for loop closing right away, instead should close after your
imgNode.mouseout function
for (i = 0; i < imgElements.length; i++) {
imgNode = imgElements[i];
imgNode.mouseenter = function () {
var img = this;
URLtwo = img.getAttribute('id');
img.src = URLtwo;
}
imgNode.mouseout = function () {
var img = this;
URLone = img.getAttribute('src');
img.src = URLone;
};
}
//preload
for (i = 0; i < links.length * 2; i++) {
link = links[i];
image = new Image();
image.src = link.src;
image = new Image();
image.src = link.id;
}};
Last for loop runs 6 times but there are only 3 tags in html. When it coming to loop no. 3 it doesn't get any value for link.src.
Also links variable provides a collection of 'li' tags and not 'img', last for loop requires src from link.src which doesn't have any value, need to change
var links = document.getElementsByTagName("li"),
to
var links = document.getElementsByTagName("img"),
Try that. Hopefully after correcting above errors your code should work.
How can I dynamically insert an IMG element into the DOM using Range.insertNode() ?
My HTML:
<div class="css_class_for_div" style="height: 250px;" contenteditable="true">
<img src="/path/to/my/image/myimage.png" alt="/myimage.png" title="/myimage.png" class="css_class_for_image" e_resid="/myimage.png" />
<br />
<br />
<span class="css_class_for_span"></span>
</div>
<input id="myButton" type="button" value="insert image" />
MY JS:
var button = document.getElementById("myButton");
button.addEventListener("click", function(e){
var src = "/path/to/my/other/image/image2.png";
var title = "/image2.png";
var cssClassname = "css_class_for_image";
var list = document.getElementsByClassName("css_class_for_div");
var el = list[0];
var selRanges = el.getSelection();
if (selRanges.rangeCount > 0) {
var curRange = selRanges.getRangeAt(0); // Range object
if (curRange.toString().length == 0) {
var imageNode = document.createElement('img');
imageNode.src = src;
imageNode.alt = title;
imageNode.title = title;
imageNode.className = cssClassname;
curRange.insertNode(imageNode);
}
}
},false);
[Link to fiddle]
The above code doesn't work. Any help is appreciated.
If you simply want to insert Image2 into the first occurrence of a div with classname = css_class_for_div using Range.InsertNode(), you can use the following code.
I had to use
var range = document.createRange();
range.selectNode(your div);
range.insertNode(your image);
Updated Fiddle
var button = document.getElementById("myButton");
button.addEventListener("click", function (e) {
debugger;
var range = document.createRange();
var list = document.getElementsByClassName("css_class_for_div");
if (list.length > 0) {
var el = list[0];
range.selectNode(el);
var imageNode = getImageNode();
range.insertNode(imageNode);
}
}, false);
function getImageNode() {
var src = "/path/to/my/other/image/image2.png";
var title = "/image2.png";
var cssClassname = "css_class_for_image";
var imageNode = document.createElement('img');
imageNode.src = src;
imageNode.alt = title;
imageNode.title = title;
imageNode.className = cssClassname;
return imageNode;
}