I have the following code to create an image with JavaScipt, the image appear on a button click. The problem is when the image is created and i click again the button another one appear, and i don't want that.
How i can solve that?
var img = new Image();
var div = document.getElementById('Table');
img.onload = function() {
div.appendChild(img);
};
img.src = 'Images/Email.png';
You could use a flag, which indicate when the image has been created, loaded and added to your DOM:
var div = document.getElementById('Table');
var hasImage = false; // flag
var button = document.getElementById('button');
button.addEventListener('click', function(event){
createImage();
});
var createImage = function(){
if(!hasImage) {
var img = new Image();
img.src = 'http://pipsum.com/435x310.jpg';
img.onload = function() {
div.appendChild(img);
hasImage = true;
};
}else{
console.log('image is already present');
}
};
<button id="button" type="button">Click Me!</button>
<div id="Table"></div >
Check if the image is already added to the DOM. If not, do so. If already added, only update the source.
It could be something like this:
var img = new Image();
var div = document.getElementById('Table');
var appended = false;
function appendImage() {
appended = true;
div.appendChild(img);
img.removeEventListener('load', appendImage);
}
function onClick() {
if (!appended) {
img.addEventListener('load', appendImage);
}
img.src = 'Images/Email.png';
}
Related
What I'm trying to achieve: clicking on any image should either reveal a clear image if image is blurred or blur the image if image is clear
What's happening: clicking on blurred image clears the image, but clicking on it again does nothing. so, clicking on a clear image does not blur it (as it should).
Here's my code:
<script>
window.onload = init;
function init(e) {
var img = document.getElementsByTagName("img");
//var img = document.getElementById('pics');
img[0].onclick = unblur; // <- why not just img.onclick = unblur ??
img[1].onclick = unblur;
img[2].onclick = unblur;
console.log(img);
/*
var imageId = e.target.id; //zero
var img = document.getElementById(imageId);
*/
//img.onclick = unblur;
}
function unblur(e) {
var imageId = e.target.id; //zero
var img = document.getElementById(imageId);
var imageSource = img.src; //zeroblur.jpg
var clearImg = imageSource.substring(0, imageSource.length - 8);
var unblurredImg = imageId.concat('.jpg'); // zero.jpg
var blurredImg = imageId.concat('blur.jpg'); // zeroblur.jpg
console.log(imageSource);
console.log(img.src);
//console.log(imageSource);
if (img.src == unblurredImg) {
img.src = blurredImg;
} else {
img.src = unblurredImg; // image is clear, so hide the pic
}
/*
if (img.src == blurredImg) {
img.src = unblurredImg;
}
} */
//}
}
/*
//if (!(imageId instanceof img)) {
if (imageId !== "pics") {
if (img.src == blurredImg) {
img.src = unblurredImg;
} else if (img.src == unblurredImg) {
img.src = blurredImg;
} // image is blurred, so reveal the pic
else {
console.log("hi");
}
//debugger;
}
}
*/
/*
var img = document.getElementById('zero');
img.src = "zero.jpg";
*/
</script>
</head>
<body>
<div id="pics">
<img id="zero" src="zeroblur.jpg">
<img id="one" src="oneblur.jpg">
<img id="two" src="two.jpg">
</div>
</body>
</html>
I also noticed that if I switch the conditions in the function, unblur(e), to the following...
if (img.src == unblurredImg) {
img.src = blurredImg;
} else {
img.src = unblurredImg;
}
there's no response at all if a user clicks on a blurred image, whereas before (code above) the blurred image will at least reveal the cleared image.
Why is this happening? I see no difference between the two, besides just switching the order of the conditions.
There are various mistakes in your example. Take a look at the Code Snippet for a working example of what you are trying to achieve.
As for your comment:
// <- why not just img.onclick = unblur ??
Because document.getElementsByTagName returns an array of elements. Therefore, you must iterate through the elements to apply the onclick handlers to each one.
(function(document) {
var array = document.getElementsByTagName("img");
for (var i = 0; i < array.length; i++) {
array[i].onclick = toggleBlur;
}
function toggleBlur(event) {
var img = event.target;
var oldSrc = img.src; // Save to display in the console
if (img.src.endsWith("blur.jpg")) {
img.src = img.id + ".jpg";
} else {
img.src = img.id + "blur.jpg"
}
console.log(oldSrc + " -> " + img.src + " on element.id=" + img.id);
}
})(document);
<body>
<div id="pics">
<img id="zero" src="zero.jpg">
<img id="one" src="one.jpg">
<img id="two" src="twoblur.jpg">
</div>
</body>
I want to put next to each thumbnail a little cross to be able to remove them one by one. I am able to remove image by click on it but I would like to have seperate button "x" to remove it.
fileInput.addEventListener("change", function (e) {
var filesVAR = this.files;
showThumbnail(filesVAR);
}, false);
function showThumbnail(files) {
var file = files[0]
var image = document.createElement("img");
var thumbnail = document.getElementById("thumbnail");
image.file = file;
image.setAttribute('class', 'imgKLIK5');
thumbnail.appendChild(image)
var reader = new FileReader()
reader.onload = (function (aImg) {
return function (e) {
aImg.src = e.target.result;
};
}(image))
var ret = reader.readAsDataURL(file);
var canvas = document.createElement("canvas");
ctx = canvas.getContext("2d");
image.onload = function () {
ctx.drawImage(image, 100, 100);
}
}
});
Here is my code in JFIDDLE
Can You help me out, please?
see this example with close button:http://jsfiddle.net/kevalbhatt18/r0taz01L/1/
$('div').on('click', '.closeDiv', function () {
$(this).prev().remove();
$(this).remove();
$('#upload-file').val("");
});
And I made this changes in your showThumbnail function
function showThumbnail(files) {
var file = files[0]
var thumbnail = document.getElementById("thumbnail");
var pDiv = document.createElement("div");
var image = document.createElement("img");
var div = document.createElement("div");
pDiv.setAttribute('class', 'pDiv');
thumbnail.appendChild(pDiv);
image.setAttribute('class', 'imgKLIK5');
pDiv.appendChild(image)
div.innerHTML = "X";
div.setAttribute('class', 'closeDiv');
pDiv.appendChild(div).......
...................
Just add new button element on each preview with following style attributes,
float:right;
position:relative;
you can remove the img from div thumbnail on click the "x" button, check this fiddle
So i am trying to make it so if you click on the button it will switch the images placement. However it doesnt actually switch the placement but instead just changes the src of each image ID. It works when you click the button once, but after that the images no longer switch. This is my code
function swapImages(){
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src = '/jmurphy9/111/images/earthrise.jpg') {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src = '/jmurphy9/111/images/earth.jpg') {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
function init(){
var button1 = document.getElementById("btn1")
button1.onclick = swapImages;
}
window.onload = init;
The problem is the src property will have the absolute path to the image, not relative one as you are checking
One possible solution is to use .indexOf() as given below
function swapImages() {
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src.indexOf('/jmurphy9/111/images/earthrise.jpg')>-1) {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src.indexOf( '/jmurphy9/111/images/earth.jpg')>-1) {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
Or you can use .getAttribute()
if (image1.getAttribute('src') == '/jmurphy9/111/images/earthrise.jpg') {
}
But since you want to swap, you can just do
function swapImages() {
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
var src = image1.src;
image1.src = image2.src;
image2.src = src;
}
Demo: Fiddle
Note: In your if condition you are using assignment(=) operator instead of comparison operator(==), so image1.src = '/jmurphy9/111/images/earthrise.jpg' in the if should be image1.src == '/jmurphy9/111/images/earthrise.jpg'
Looks like your equality operator is missing an extra "=" on your if's e.g. if(image1.src == '/jmurphy9/111/images/earthrise.jpg') so when it tries to evaluate the expression it never goes in so it changes the first time 'cause it goes to the else and from there on it just keeps going to the else so nothing happens.
function swapImages(){
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src == '/jmurphy9/111/images/earthrise.jpg') {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src == '/jmurphy9/111/images/earth.jpg') {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
function init(){
var button1 = document.getElementById("btn1")
button1.onclick = swapImages;
}
window.onload = init;
The accepted answer, like yours, swaps the src attribute of the images.
Another method is to actually swap the img nodes themselves, which may be preferable if the images matter severally- eg., need special event handling or css considerations that depend on the actual image.
function swapNodes(a, b){
var p= b.parentNode, sib= b.nextSibling;
if(sib=== a) sib= sib.nextSibling;
a.parentNode.replaceChild(b, a);
return sib? p.insertBefore(a, sib): p.appendChild(a);
}
note that you can always swap img nodes, or any two like nodes, but there are some nodes that cannot be swapped, because the container node of one will not accept the other as a child.
You can swap them if they make valid html.
I want to receive the width of a JPG after dragging it into the browser window. The strange thing is, sometimes it works perfectly and sometimes a width of zero is returned.
fiddle
document.body.addEventListener('drop', function ( e )
{
e.stopPropagation();
e.preventDefault();
file = e.dataTransfer.files[0];
reader.readAsDataURL( file );
reader.onloadend = function()
{
var source = this.result;
var currentImg = new Image();
currentImg.src = source;
var someDiv = document.createElement("div");
someDiv.innerHTML = '<li>'+currentImg.width+'</li>';
document.getElementById("logs").appendChild(someDiv);
}
});
This happens because you probably get width before the image is loaded.
Put some code like this and you works correctly.
...
var currentImg = new Image();
currentImg.onload = function() {
var someDiv = document.createElement("div");
someDiv.innerHTML = '<li>'+currentImg.width+'</li>';
document.getElementById("logs").appendChild(someDiv);
}
currentImg.src = source;
...
put the onload before setting the sorce because onload is a callback function.
I'm using html5 to create drag and drop image upload functionality. This works great for me in firefox but in chrome the image onload event only fires the first time. If I drag multiple images in only the first works and if I drag a second in it fails. I believe the problem is with the image onload.
here is the way my code works I have removed the irrelevant sections:
var img = document.createElement("img");
var reader = new FileReader();
var canvas = document.createElement("canvas");
var canvasData;
var ctx = canvas.getContext("2d");
var myFiles;
var i = 0;
reader.onload = (function (aImg)
{
return function (e)
{
aImg.src = e.target.result;
};
})(img);
img.onload = function (){
//resizes image
//draws it to the canvas
//posts to server
i++;
if(i < myFiles.length){
processNext(i);
}
}
function processNext(filei) {
var file = myFiles[filei];
img.file = file;
reader.readAsDataURL(file);
}
i = 0;
myFiles = files;
processNext(0);
Does anyone know why this works in firefox but not chrome?
Explanation from chromium tracker:
This is not a bug. WebKit is just more strict. You must instantiate a new Image() object before the replacement, like this:
var photo = document.getElementById('image_id');
var img = new Image();
img.addEventListener('load', myFunction, false);
img.src = 'http://newimgsource.jpg';
photo.src = img.src;
source: http://code.google.com/p/chromium/issues/detail?id=7731#c12
This is strange, none of the above worked for me. I was defining the image variable as local and change it to global and it started working. Does this make sense? Can somebody explain it?
This didnt worked for me:
function loadImage() {
var ImageToLoad = new Image();
ImageToLoad.onload = function() {
console.log("finish loading");
};
ImageToLoad.src = "myimage.png";
}
This did work:
var ImageToLoad = new Image();
function loadImage() {
ImageToLoad.onload = function() {
console.log("finish loading");
};
ImageToLoad.src = "myimage.png";
}