Image appears then disappears when submitted - javascript

I have an input box that accepts a url of an image, when the submit button is clicked the url is got by a javascript function, which updates a canvas and an image object on the page.
The image is located fine, and it appears in the image object and canvas object, but very shortly after is disappears.
<canvas id = "edit_canvas" width = "600" height = "600"></canvas>
<img src= "images/placeholder.png" alt="Image Cannot Be Displayed" id = "edit_pic">
<form onsubmit = "submitImage()">
Custom Picture: <input type="url" name="pic_url" id ="input_url"><br>
<input type="submit">
</form>
<script type="text/javascript">
function submitImage(){
var img = new Image();
var url = document.getElementById("input_url").value;
img.src = url;
img.onload = function(){
alert("img has loaded");
updateCanvas(img);
document.getElementById("edit_pic").src = url;
};
}
function updateCanvas(img){
alert("updateCanvas called");
var c =document.getElementById("edit_canvas");
var ctx=c.getContext("2d");
ctx.drawImage(img,0,0);
}
</script>
I have used the updateCanvas() function elsewhere, where it works fine and the image stays. Both of the alerts in the javascript functions appear as expected, but the image does not stay in the canvas/image object.

You're submitting the form, that involves re-loading the page, so I guess it shows the image briefly, and then reloads, emptying the canvas.
Use onclick on the button instead of onsubmit on the form to avoid reloading, and make the button not submit the form by changing from an input type="submit" to a button type="button":
<button type="button" onclick="submitImage()">Submit</button>

Either you can prevent the submit action of the form or change the input type
to button and attach submitImage function to the click event of the button and remove the submitImage from form submit
{code}
function submitImage(){
var img = new Image();
var url = document.getElementById("input_url").value;
img.src = url;
img.onload = function(){
alert("img has loaded");
updateCanvas(img);
document.getElementById("edit_pic").src = url;
};
return false;
}
{code}

Related

JS function when clicking parent element but return false when clicking child element

I have an image gallery on my site and when you click on it, it opens into a lightbox kind of effect.
I want them to be able to click off of the preview image on the lightbox background and close the preview but not if they click on the actual preview image itself.
function get_image_preview(){
var lightbox = document.getElementById("lightbox");
var image_src = document.getElementById("gallery_image").src;
lightbox.style.display = "block";
lightbox.setAttribute("onclick", "end_image_preview()");
var new_image = document.createElement("img");
new_image.setAttribute("id", "preview_image");
new_image.setAttribute("src", image_src);
new_image.setAttribute("onclick", "return false");
lightbox.appendChild(new_image);
}
function end_image_preview(){
var lightbox = document.getElementById("lightbox");
lightbox.style.display = "none";
lightbox.innerHTML = "";
}
So basically this line:
lightbox.setAttribute("onclick", "end_image_preview()");
does what it is supposed to do and close the preview.
However, the preview is a child of this and I want them to be able to click on the image without ending the preview, so I tried this:
new_image.setAttribute("onclick", "return false");
I think you mignt want to use event.stopPropagation():
function new_image_click(e) {
e.stopPropagation();
}
new_image.setAttribute("onclick", "new_image_click(event)");
in your end image preview click listener make sure that the element does not have in its ancestor the preview element it self, lets say that you gave the preview element the id "preview"
in end_image_preview
function end_image_preview(e) {
if (e.closest('#preview')) {
return
}
// here do what you already doing
}

Upload image with a single button in html

I'm a newbie in html/javascript and made two buttons that can upload image (choose file button and upload button).
However, I want to make it to just a single button and don't know how to combine those two button. I already searched on google, they said we can use onchange to combine submit button but I already have onchange function that can show image right away after choosing image file to iframe.
Here is my html code for <form>
<form action="/upload", method="post", enctype="multipart/form-data">
<div style='height:0px; width:0px; overflow:hidden;'><input type="file" name="upFile" id="upFile" onchange="getCmaFileView(this, 'name').submit()" target="dropzone_1"/></div>
</form>
Also, here is my script and button
<script type = "text/javascript">
function getFile(){
document.getElementById("upFile").click();
}
</script>
...
<li><a onclick="getFile()" style="cursor:pointer; color:#000000;">Choose File</a></li>
I tried with adding .submit() in onchange, but it didn't work.
Does anybody have an idea for this?
Please please help me out here!
Thanks in advance.
EDIT
function getCmaFileInfo(obj,stype) {
var fileObj, pathHeader , pathMiddle, pathEnd, allFilename, fileName, extName;
var file;
var img, reader;
// file = upload.files[0];
upload = document.getElementsByTagName('input')[0];
holder = document.getElementById('dropzone');
reader = new FileReader();
file = upload.files[0];
var iupload, holder;
reader.onload = function (event) {
img = new Image();
//console.log(event.target.result);
img.src = event.target.result;
img.width = document.getElementById("dropzone").clientWidth;
img.height= window.innerHeight;
// note: no onload required since we've got the dataurl...I think! :)
holder.innerHTML = '';
holder.appendChild(img);
};
reader.readAsDataURL(file);
}
function getCmaFileView(obj,stype) {
getCmaFileInfo(obj,stype);
}
Can't you just add one more function/code in your getCmaFileView() - Which will just submit the form? Also it will be called after your image viewing part is done so that may solve your problem.
function getCmaFileView(obj,stype) {
getCmaFileInfo(obj,stype);
//form.submit() OR call_to_your_submit_function();
}

JavaScript function not working in HTML page

HTML code for browse file button
<input type="file" multiple="false" accept="image/*" id="filein" onclick="filo()">
JavaScript
function filo(){
var canin= document.getElementByID("c5");
var imgin = document.getElementById("filein");
var xct = canin.getContext("2d");
var img = new Image(filein);
xct.drawImage(canin);
}
There are several problems.
You need to use the onchange event not the click event
<input type="file" multiple="false" accept="image/*" id="filein">
You add the event listener using script rather than in line.
<script> // this script must be place after the element filein or use an onload event.
filein.onchange = filo();
</script>
The function getElementById returns an element not a string. You need to get the filename (URL) from the element's files property
Change the image construction as it does not take the image URL as an argument. You set the img.src to the url then wait for the image to load.
The function drawImage function requires the image and at least 2 arguments that are the location to draw at.
Example of changes.
function filo () {
// Get the filename of the input element
var imgin = document.getElementById("filein").files[0]; // <<Get the file URL
// Typo its getElementById not getElementByID
var canin= document.getElementById("c5");
var xct = canin.getContext("2d");
// Image does not take a URL via the constructor
var img = new Image();
// set the URK here
var img.src = imgin;
// you need to wait for the image to load then you can draw it
img.onload = function () {
// drawImage function requires the image and at least 2 arguments
// that are the location to draw at
xct.drawImage(this, 0, 0); // this is the image in the onload event
}
}

set and clear background image of html page

I am trying to customize this button that loads a background image in from the user input. Once they have added a background image, when they go to add another image (i.e. click Choose the second time), I want the first one to be removed from the background when the prompt re-opens to add another.
$(switchBackground);
var oFReader = new FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function(oFREvent) {
localStorage.setItem('b', oFREvent.target.result);
switchBackground();
};
function switchBackground() {
$('body').css('background-image', "url(" + localStorage.getItem('b') + ')');
}
function loadImageFile(testEl) {
if (! testEl.files.length) { return; }
var oFile = testEl.files[0];
if (!rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; }
oFReader.readAsDataURL(oFile);
}
<input id="test" type="file" onchange="loadImageFile(this)" />
Here is a JS Fiddle of this code.
The simplest way is to add a click listener to the same input, which means whenever the user clicks anywhere inside the input it will call to empty the background. In your JS Fiddle, it is setting the background on the body, so I'll go with that in this example: -
function emptyBg() {
document.body.style.backgroundImage = 'none';
}
Register the click event (using the same syntax you used - although this should be attached using JavaScript and not HTML, see DOM Event Listeners).
<input id="test" type="file" onchange="loadImageFile(this)" onclick="emptyBg()"/>

Javascript image upload and display

My basic task is select image and display it,without saving it in database.
For this
1.I have made a select tag in html,through which I can upload the image.
2.I have made a blank image tag in which at there is no image source,alternate is upload image.
3.select tag has onchange javascript event handler which calls javascript function changeimage.
<script>
function changeimage()
{
document.form_name.imagetag.src=document.form_name.filetag.value;
}
</script>
In above Code
form_name : Is the name of my form
<form name = "form_name">
imagetag : Is the name of my Img tag
<Img src=" " name = "imagetag">
filetag : Is the name of my
<input type="file" name = "filetag" onchange="changeimage()">
I have save file using php extension.And when I try to print the value of filetag it shows "C:\fakepath\image.png",display this address for all image.
I have save my php file in www location.
I am using window 7,wamp server and chrome latest version.
You may want to checkout this solution (where my code derives from). It involves a little bit of jQuery but if you truly must write it out in pure JS, here you go.
Note: I modified your tags to conform to the JS below. Also try to stay away from writing any inline scripts. Always good to keep your HTML and JS loosely coupled.
var fileTag = document.getElementById("filetag"),
preview = document.getElementById("preview");
fileTag.addEventListener("change", function() {
changeImage(this);
});
function changeImage(input) {
var reader;
if (input.files && input.files[0]) {
reader = new FileReader();
reader.onload = function(e) {
preview.setAttribute('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
<input type="file" id="filetag">
<img src="" id="preview">
You can also use the Image() constructor. It creates a new HTML Image Element.
Example -
document.getElementById("filetag").addEventListener("change", function(e) {
let newImg = new Image(width, height);
// Equivalent to above -> let newImg = document.createElement("img");
newImg.src = e.target.files[0];
newImg.src = URL.createObjectURL(e.target.files[0]);
output.appendChild(newImg);
});
Reference - https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
You need one input tag to upload file and a image tag to render on the site.
The HTML and Javascript should look like
const renderFile = () => {
const render = document.querySelector('img')
const file = document.querySelector('input[type=file]').files[0]
const reader = new FileReader();
reader.addEventListener('load' , ()=> {
render.src = reader.result;
}, false)
if(file){
reader.readAsDataURL(file);
}
}
<input type = 'file' onchange = 'renderFile()' >
<br>
<br>
<img src = "" alt='rendered image' id='rendered-image' >
Simply on every upload the web page will show the image uploaded
You can Style the height and width of the image according to the need

Categories

Resources