Replace image in javascript rather than add to list - javascript

I have a script that allows the user to upload images and preview them. It's a very basic script and although I have managed to get it to do more or less everything I need I am stuck on one last thing.
As it stands once the user has uploaded an image it is displayed but if they upload another one it displays both, I would like the new image to replace the old image so only one is visible.
I don't have issues with the php side of things, the problem lies in the part where the script appends the new image to list and displays the list rather than just the new image and unfortunately my javascript knowledge is quite limited at the moment.
This is the script:
$(function(){
var btnUpload=$('#upload');
var status=$('#status');
new AjaxUpload(btnUpload, {
action: 'upload-file.php',
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
// extension is not allowed
status.text('Only JPG, PNG or GIF files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(file, response){
//On completion clear the status
status.text('');
//Add uploaded file to list
if(response==="success"){
$('<li></li>').appendTo('#files').html('<img src="upload/'+file+'" alt="" /><br />'+file);
} else{
$('<li></li>').appendTo('#files').text(file);
}
}
});
});
And the images are displayed here:
<ul id="files" ></ul>
Any help will be gratefully received

Instead of:
$('<li></li>').appendTo('#files')
Try:
$('<li></li>').appendTo($('#files').empty())
This will empty the #files element before appending new content.

Related

Creative SDK Image Editor (Web) loads image, waits, then image disappears (no live preview)

late night here and at the end of my tether:
Incorporating Creative SDK to edit photos that were uploaded to the server via the previous page in the workflow -
I have tried every one of the parameters on the SDK documentation to find where is the fault in keeping the loaded image active for previewing edits, but in sequence,
Plugin Initialises (onLoad -> Ok)
Image loads (onReady -> Ok)
The Wait icon spins, then
The image disappears from the edit window
onError() does not pick this up.
Edits are functioning, onSave() fires and I can copy the image
(sending the adobe URL via AJaX) to a specified location (file output) on my
webspace, BUT, no live preview. Also the image does not update the original as is hard-coded in my script, and it gives an error as though unsaved on closing (isDirty).
My webspace is covered with an SSL certificate, but tried loading the image with relative and absoulte URLs, via http and https - nada.
I am calling version 3 as per the documentation, but people have said try version 4.3.1.29..?
I would like to presevere with this editor for live image editing, but only need it for cropping, adjusting brightness, contrast, rotation etc. and at the moment it is working, but 'blind' - anyone come across this? And how do I fix it...? :)
This is the source, pretty much as specified in the documentation, but with a working AJaX call while 'onSave()':
<script type="text/javascript" src="http://feather.aviary.com/imaging/v3/editor.js"></script>
<!-- Instantiate Feather -->
<script type='text/javascript'>
var featherEditor = new Aviary.Feather({
apiKey: 'my-key',
theme: 'dark', // Check out our new 'light' and 'dark' themes!
tools: 'all',
displayImageSize: 'true',
appendTo: '',
onSave: function(imageID, newURL) {
var img = document.getElementById("image1");
img.src = newURL;
var ph = document.getElementById("new_image_placeholder_div");
ph.innerHTML = '<img src="'+img.src+'" height="100">';
var xmlhttp_c;
if (window.XMLHttpRequest){xmlhttp_c=new XMLHttpRequest();} else {
xmlhttp_c=new ActiveXObject("Microsoft.XMLHTTP");}
alert("Passing the URL "+newURL+" to the PHP page...");
xmlhttp_c.open("GET", "feather_save_handler.php?newURL="+encodeURI(newURL), true);
xmlhttp_c.onreadystatechange=function() { if (xmlhttp_c.readyState==4 && xmlhttp_c.status==200) {
alert(xmlhttp_c.responseText);
alert("Saved!");
} else {
}
}
xmlhttp_c.send();
// end save AJaX call..
},
onError: function(errorObj) {
alert(errorObj.args);
}
});
function launchEditor(id, src) {
featherEditor.launch({
image: id,
url: src
});
return false;
}
</script>
The function is kicked off from a form button:
<form name="feather_editor" onSubmit="no_submit();">
<input type='image' src='http://images.aviary.com/images/edit-photo.png' value='Edit photo' onclick="return launchEditor('image1', 'http://mywebsitename.com/image_name.jpg');" >
</form>
It turns out that this is an issue in your CSS, and should be a fairly simple fix.
The issue
In daFooz_main.css, you have a canvas selector that includes:
z-index: -1;
That's causing the image in the Image Editor to effectively disappear from view since it is a canvas element.
The fix
The fix could be as simple as removing the line above from your CSS.
If you need that line for other areas of your site, try finding a way to be more specific with your selector, perhaps by using classes to target canvas elements that you do want to alter the z-index of.

CKEditor - image preview without uploading to server

I am using Upload Image plugin to implement "drag drop to insert image" functionality. When I drop image into edit area, image is getting uploaded to server and then using the returned url to show preview.
But I need to show image preview in edit area without uploading to server. When I click on custom submit button I want save entire content including images to server.
Please let me know if anybody has done/any ideas on this.
Thanks in advance.
Siva
That is pretty simple. UploadWidget is a helper to create content from dropped images: http://docs.ckeditor.com/#!/api/CKEDITOR.fileTools-method-addUploadWidget
There is the definition property loadMethod which can be load - which is exactly the option you need:
http://docs.ckeditor.com/#!/api/CKEDITOR.fileTools.uploadWidgetDefinition-property-loadMethod
Then, you can overwrite the upload image widget or create your own widget, based on the fileReader example from UploadWidget.
The code should look like:
CKEDITOR.fileTools.addUploadWidget( editor, 'imageReader', {
loadMethod: 'load',
supportedTypes: /image\/(jpeg|png|gif|bmp)/,
fileToElement: function( file ) {
var img = new CKEDITOR.dom.element( 'img' );
img.setAttribute( 'src', loadingImage );
return img;
},
onLoaded: function( loader ) {
this.replaceWith( '<img src="' + loader.data + '" '>' );
}
} );
// Black rectangle which is shown before the image is loaded.
var loadingImage = 'data:image/gif;base64,R0lGODlhDgAOAIAAAAAAAP///yH5BAAAAAAALAAAAAAOAA4AAAIMhI+py+0Po5y02qsKADs=';
The only part which may not work is notification integration that listens on the upload event as far as I remember. If you need notifications, you need to add them manually.

Using JavaScript to dynamically change display style in img tags

I show links to 240 images on a page. The real images are uploaded by users. I tried to avoid showing an empty image if users did not upload it yet. jQuery did not work for me because of conflicts, so I have to do it in pure JavaScript.
image(s) links:
<img class="photo240" src="http://www.example.com/i/%%GLOBAL__AuthorID%%/p/b01.jpg" onerror="imgError()">
My JavaScript:
function imgError()
{
alert('The image could not be loaded.');
var _aryElm=document.getElementsByTagName('img'); //return an array with every <img> of the page
for( x in _aryElm) {
_elm=_aryElm[x];
_elm.className="photo240off";
}
}
The style photo240off equals to display:none.
Right now, whenever an image misses, all the images are turned to style photo240off and I want only the missing image to be hidden. So there is something wrong with my script.
(the overall script works well, because I get the alert).
Use this to get the image with the error.
Change to:
onerror="imgError(this)"
Then the function can be:
function imgError(el) {
alert('The image could not be loaded.');
el.className = "photo240off";
}
You need to reference the image from your onerror call and change the class only for that one.
Something like this:
HTML
<img class="photo240" src="example.jpg" onerror="imgError(this)">
JS
function imgError(el) {
el.className="photo240off";
}

How can I let users browse there computer to choose a background image in HTML JAVASCRIPT

I'm trying to allow users to browse their documents and choose a picture to set as a background image. I have already found out how a user can change the background image using a URL. Please find the demo below:
DEMO: http://goo.gl/253IN
Username: demo
Password: demo1
I dont know how to get it to work with the
File Field
I have found the following Example which I would like to use. Found question here
JavaScript:
$(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);
}
HTML:
<input id="test" type="file" onchange="loadImageFile(this)" />
However I cant get it to work with my current code (Please refer to demo)
Thanks in advance
PS I am not an expert (yet :D) on HTML and Javascrpit so I will not be able to understand really complex code
In short, you cannot use the file input in this way. JavaScript does not have access to the users direct machine for security reasons. This input simply allows a file to be passed across the web stream in the body of an HTTP POST request.
To accomplish what you are wanting, you would have to upload the file server side using a server side language such as PHP or ASP.NET. You could then save it off and store it, allowing it to be displayed as the users background whenever they visited.
not impossible at all!
you can actually add this functionality to you website using this plugin
https://github.com/CybrSys/custom-background.js

select an image and manipulate it in javascript (no form submission)

Is there by any chance a way of letting the user select an image from his hard drive and without submitting it to the server use this image in the browser?
I need this because I want the users to be able to crop an image before sending this cropped image to the server (thus saving a post and some bytes of data).
What I tried to do is using an input type file and then capturing the submit event, but the value from the input is just a fake path (useless).
Any help would be greatly appreciated.
Here is a very basic example (with many globals, without input validation...) of image scaling: http://jsfiddle.net/89HPM/3/ . It's using the File API and a canvas element.
As #anu said the save can be done using toDataUrl method of the canvas.
In similar way you can achieve crop.
JavaScript
(function init() {
document.getElementById('picture').addEventListener('change', handleFileSelect, false);
document.getElementById('width').addEventListener('change', function () {
document.getElementById('canvas').width = this.value;
renderImage();
}, false);
document.getElementById('height').addEventListener('change', function () {
document.getElementById('canvas').height = this.value;
renderImage();
}, false);
}());
var currentImage;
function handleFileSelect(evt) {
var file = evt.target.files[0];
if (!file.type.match('image.*')) {
alert('Unknown format');
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
currentImage = e.target.result;
renderImage();
};
})(file);
reader.readAsDataURL(file);
}
function renderImage() {
var data = currentImage,
img = document.createElement('img');
img.src = data;
img.onload = function () {
var can = document.getElementById('canvas'),
ctx = can.getContext('2d');
ctx.drawImage(this, 0, 0, can.width, can.height);
};
}​
HTML
<input type="file" name="picture" id="picture" /><br />
<input type="text" id="width" value="200" />
<input type="text" id="height" value="200" /><br />
<canvas width="200" height="200" style="border: 1px solid black;" id="canvas"></canvas>​
Here is a blog post which I made about that basic example: blog.mgechev.com
New HTML5 File API is probably the closest solution to what your looking for:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
It allows you to browse for and read files within Javascript. Do whatever processing you like, and then upload to the server. Anything besides this is going to be very tricky indeed, and probably an unavoidable trip to the server and back.
Downside here is browser support.....as always
I am not sure which browsers work perfectly but HTML5 got DnD and File API. Let me give you steps which can work for you using FileAPI.
DnD API: Starts with the drop event when the user releases the mouse and the mouse-up event occurs.
DnD API: Get the DataTransfer object from the drop event
File API: Call DataTransfer.files to get a FileList, representing the list of files that were dropped.
File API: Iterate over all the individual File instances and use a FileReader object to read their content.
File API: Using the FileReader.readAsDataURL(file) call, every time a file is completely read, a new “data URL” (RFC 2397) formatted object is created and an event wrapping it is fired to the onload handler on the FileReader object.
FYI: The “data URL” object is Base64-encoded binary data, with a spec-defined header sequence of chars. Browsers understand them.
HTML5 DOM: set the image href to the File Data URL
You can't, for the following reasons:
For the reasons stated in this post: Full path from file input using jQuery
The fact that if you even try to create an img element loading a
local file path you'll get the error Not allowed to load local
resource: in your browser's console.
The fact that once you have an image in place you can only alter it's
appearance on screen and not alter the file on the system or send the altered image up to the server
You've stated that you need cross browser support, so HTML5 File API and Canvas API are out, even though they would only allow part of the functionality anyway.
I've just solved a problem closed to yours.
As everybody said you can't got the real image file address. But, you can create a temporary path and show the image in your page without submiting it to server. I'll show how easy it is, next to next paragraph.
Once you show it you can use some javascripts events to "pseudo-crop-it" and get the crop params (corners). Finaly you can add the params to some hidden field and submit the form. As a result you may use som php to crop the submited image at server and to save the result using a number of image formats as .png, jpg, gif, etc. Sorry if i do not write a complete solution, have not enough time.
/* some scripting to bind a change event and to send the selected image
to img element */
$(document.ready(function(){
$("input:file").each(function(){
var id = '' + $(this).attr('id');
var idselector = '#'+id, imgselector=idselector+'-vwr';
$(idselector).bind("change", function( event ){
(imgselector).fadeIn("fast").attr('src',
URL.createObjectURL(event.target.files[0]));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<!-- create a img element to show the selected image and an input file element to select the image.
ID attribute is the key to have an easy and short scripting
note they are related suffix -vwr makes the difference
-->
<img src="" id="image-input-vwr" alt="image to be cropped">
<input type="file" id="image-input" name="image_input">
Hope it help some body as it is a very old question.
Luis G. Quevedo

Categories

Resources