jCrop (jQuery) sometimes fails to load image/cropper area - javascript

I've got a pretty simple problem, but I've become clueless on what is causing the problem. In one of my applications I'm using jCrop as a small add-on to crop images to fit in banners/headers etc. These steps will be taken:
1) Select an image (using CKFinder for this, CKFinder returns the image path to an input field)
2) Click a button to load the image
3) Crop the image
4) Save the image
in about 75% of the cases everything goes according to plan, however the in the other 25% of the cases jCrop fails to load the cropping area and leaves it blank. Here's the jQuery code I'm using:
jQuery('#selectimg').live('click', function(e) {
e.preventDefault();
var newsrc = jQuery('#img2').val();
jQuery('#cropbox').attr('src', newsrc);
var jcrop_api = jQuery.Jcrop('#cropbox', {
boxWidth: 700,
boxHeight: 700,
onSelect: updateCoords,
onChange: updateCoords
});
//Some other JS code come's here for buttons (they work all the time)
});
I noticed that when I left the part away where #cropbox is being transformd in a cropable area, that the image is loading just fine, so the mistake lies with the var = jcrop_api part, but I slowsly start to think that there is no solution for this...
This is what I've tried so far:
Making a div <div id="cropper-box"></div> and use jQuery('#cropper-box').append('<img src="" id="cropbox" />'); and afterwards set the value. I tried the same thing but setting the image src in 1 step instead of afterwards.
I tried to put a placeholder on the page <img src="placeholder.png" id="cropbox" /> and change the source upon clicking the button. This works, but the cropperarea stays the size of the image (300x180px or something) and doesn't get bigger as it should.
// Edit:
Trying some more showed me that the image source is being replaced properly(! using Firefox to show the source for the selected text), I double checked the URL but this was a correct URL and a working image.
At the place where the cropper should be, there's an about 10x10 pixel white spot where the cropper icon (a plus sign) is popping up.. but as said before: the image isn't shown.
// Edit 2:
So I've took the sources for both the 1st and the 2nd try for the same image. As told before the first try the image won't load properly and the 2nd try it does (only when the 2nd try is the same image(!!)).
The selected page source shows 1 difference which is, first try:
<img style="position: absolute; width: 0px; height: 0px;" src="http://95.142.175.17/uploads/files/Desert.jpg">
second try:
<img style="position: absolute; width: 700px; height: 525px;" src="http://95.142.175.17/uploads/files/Desert.jpg">
I guess this is the image that's being replace by jCrop, but it's a complete riddle why it puts 0 heigth/width in there the first and the proper sizes the second time.

Okay guys, in case anyone else runs into this problem:
jCrop kinda gets messed up if the actions of loading an image and applying jCrop to it are queued too fast after eachother. I still find it strange that a second attempt works perfect, but I think that has something to do with cached image dimensions which are recognized by the DOM of the page or something.
The solution I came up with was by creating a function that converts the #cropbox into a jCrop area and then setting a 2 second interval, just to give jCrop some time to recognize the image and it's dimensions and then convert the element.
This is the part of html I used (with a preloader):
<div id="cropper-loading" style="display: none;"><img src="images/analytics/ajax-loader.gif" /></div>
<img id="cropbox" src="images/placeholder.png" style="display: none;" />
As you can see both the cropbox image and cropper-loading div are hidden as they are not needed instantly. You could display the placeholder if you wanted though.. Then this HTML form is used:
<input name="image2" id="img2" type="text" readonly="readonly" onclick="openKCFinder(this)" value="click here to select an image" style="width: 285px;" /> <button class="button button-blue" type="submit" name="load" id="selectimg">Load Image in cropper</button>
In my case I've been using KCFinder to load the images (it's part of CKEditor, really worth watching into!), KCFinder handles uploads, renaming etc and after choosing it returns the chosen image path (relative/absolute is configurable) to the input field.
Then when clicking #selectimg this code is called:
jQuery('#selectimg').click(function(e) {
e.preventDefault();
jQuery('#cropper-loading').css('display', 'block');
var newsrc = jQuery('#img2').val();
jQuery('#cropbox').attr('src', newsrc);
jQuery('#img').val(newsrc);
function createJcropArea() {
jQuery('#cropper-loading').css('display', 'none');
jQuery('#cropbox').css('display', 'block');
var jcrop_api = jQuery.Jcrop('#cropbox', {
boxWidth: 700,
boxHeight: 700,
onSelect: updateCoords,
onChange: updateCoords
});
clearInterval(interval);
}
var interval = setInterval(createJcropArea, 2000);
});
At first I prevent the link too be followed as it normally would (or button action) and after that the loading div is displayed (that's my reason for hiding the placeholder image, otherwise it would look messed up).
Then the image location is being loaded from the input field and copied into another (#img), this field is used to process the image afterwards (PHP uses the value of #img to load this image). Also simultaneously the #cropbox src is being set to the new image.
And here comes the part which solved my problem:
Instead of directly activating jCrop, I've made a function that:
1) hides the loading icon
2) displays the image
3) converts #cropbox into a jCrop area
4) clean the interval (otherwise it would loop un-ending)
And after this function you can see that, just to be save, I took 2 seconds delay before the jCrop area is being converted.
Hope it helps anyone in the future!
Cheers and thanks for thinking #vector and whoever else did ;-)

Creating an 'Image' object and setting up the 'src' attribute does not apply that you can treat the image like it had already been loaded.
Also, giving any fixed timeout interval does not guaranty the image has already been loaded.
Instead, you should set up an 'onload' callback for the Image Object - which will then initialize the Jcrop Object:
var src = 'https://example.com/imgs/someimgtocrop.jpg';
var tmpImg = new Image();
tmpImg.onload = function() {
//This is where you can safely create an image and a Jcrop Object
};
tmpImg.src = src; //Note that the 'src' attribute is only added to the Image Object after the 'onload' listener was defined

Try the edge library on the repo here: https://github.com/tapmodo/Jcrop
This should solve your problem. The lines that are changed to solve your problem:
// Fix size of crop image.
// Necessary when crop image is within a hidden element when page is loaded.
if ($origimg[0].width != 0 && $origimg[0].height != 0) {
// Obtain dimensions from contained img element.
$origimg.width($origimg[0].width);
$origimg.height($origimg[0].height);
} else {
// Obtain dimensions from temporary image in case the original is not loaded yet (e.g. IE 7.0).
var tempImage = new Image();
tempImage.src = $origimg[0].src;
$origimg.width(tempImage.width);
$origimg.height(tempImage.height);
}

Don't call this function onChange : updateCoords
Try it without and it will run smooth on mobiles.
You can create base64 directly and show them as an image wherever you want.

Here my weird but fantastic solution:
if (obj.tagName == 'IMG') {
var tempImage = new Image();
tempImage.src = $origimg[0].src;
$origimg.width(tempImage.width);
$origimg.height(tempImage.height);
if ($origimg[0].width > 1 && $origimg[0].height > 1) {
$origimg.width($origimg[0].width);
$origimg.height($origimg[0].height);
} else {
var tempImage = new Image();
tempImage.src = $origimg[0].src;
$origimg.width(tempImage.width);
$origimg.height(tempImage.height);
//console.log('error'+$origimg[0].width + $origimg[0].height);
}

I know this is old, but it was happening randomly to my install recently. Found that it was due to images not being full loaded before before jCrop intialized.
All it took to fix it was wrapping the jCrop initialization stuff inside of a
$(window).on("load", function () { //jcrop stuff here });
And it has been working well since.

Related

JavaScript - onclick image change using 'if'

I tried js image changing example using two different if methods.
<img id="myImage" onclick="changeImage()" src="s.png">
Click image
<script>
function changeImage() {
var image = document.getElementById('myImage');
if (image.getAttribute('src')=='s.png')
image.src="m.png";
else
image.src="s.png";
}
</script>
Above method works totally fine no matter how many times clicked on the image or no matter which image is compared inside the 'if' part.
But below method which is given in w3c doesn't work as expected.
function changeImage(){
var image = document.getElementById('myImage');
if (image.src.match("s"))
{image.src ="m.png";}
else
{image.src ="s.png";}
This second method works only at first click. And also when the image compared inside the 'if' part is swapped with other image, it doesn't work at all even at the first click. Can someone please explain me, why second 'if' method doesn't work properly while first 'if' method works finely?
The reason why your code is not working is that web browser automatically adds site path to your image url because you are using relative image url. So you will have 's' character in every url (because s letter is in site url). And every .match('s') will always return true.
The solution is just to find out another checking of current image.
Here is example which logs out image src, so it should help you to understand the problem: https://jsfiddle.net/0yL0fwpL/4/
Html:
<img id="myImage" onclick="changeImage();" src="s.png">
Click image
Javascript:
changeImage = function() {
var image = document.getElementById('myImage');
if (image.getAttribute('src')=='s.png') {
image.setAttribute('src', "m.png");
} else {
image.setAttribute('src', "s.png");
}
}
Working example: https://jsfiddle.net/0yL0fwpL/2/

content editable div html

<div contenteditable="true" class="dropZone"></div>
<div class="imageHolder">
<div class="droppedImage"></div>
</div>
I have the above html. There maybe a few 'dropZone' divs on the page. But each is has the following event bound:
$('#lightbox').find('.dropZone').each(function(){
$(this).mouseover(function(){
// check the asset is an image
if( $(this).find('img').length > 0 ){
var src = $(this).find('img').first().attr('src'),
masterTestVal = 'mydomain';
$(this).empty();
// check the asset is from the image bin
if(src.search(masterTestVal) > 0){
var that = $(this).siblings('.imageHolder').find('.droppedImage'),
img = '<img src="'+src+'"/>';
that.html(img);
} else {
alert('Only images from your image bin are accepted here.');
}
} else {
if($(this).html().length > 0){
alert('Only images from your image bin are accepted here.');
$(this).empty();
}
}
});
});
The idea is simple, a user can drag and drop an image from their 'image bin' another div loaded on the page populated with some preloaded images. When the user drags an image over a 'drop zone' div the above js kicks in, if the image is from my domain then the said image is copied into the 'droppedImage' div.
This works perfectly well, but in chrome and safari the user can only do this action once. In firefix I can repeat the action endlessly. But in chome and safari is seems after one drop the attr contenteditable is lost or something?
Does anyone have any ideas?
Thanks,
John
js fiddle - http://jsfiddle.net/n6EgH/1/
Instead of $(this).mouseover, try to bind mouseover on that div. I think this would work. Use $(this).bind('mouseover',function()..
Kooilnc
Your answer definitely feels right, using the drag drop behaviour, however as of yet i have yet to find the time to understand the drag drop events properly.
As a bodge fix, i have found a work around although it does feel messy. I have simply removed the drop-zone div in Q and replaced with a new version plus rebound the events after an img drop. So kind of just starting it all over again :S
// check the asset is from the image bin
if(src.search(masterTestVal) > 0){
var that = $(this).siblings('.imageHolder').find('.droppedImage'),
img = '<img src="'+src+'"/>';
that.html(img);
$(that).attr('contenteditable','true')
var newDropBin = $('<div contenteditable="true">'); // <= replacing the original drop zone here
$(this).replaceWith(newDropBin);
$(newDropBin).addClass('drop-zone');
dropImg.init();
}
http://jsfiddle.net/n6EgH/4/

Dynamically change image src using Jquery not working in IE and firefox

I am implementing a captcha for a email. when click on linkEmail button email modal will open.
there i have to set captcha image generated by a handler (CaptchaGenerator.ashx) on click of linkEmail button click. Here is the code for that.
$(".linkEmail").click(function () {
//Load captcha image
$('.imgCaptcha').attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx');
$('#emailModal').modal();
});
Above code is working fine in crome but not working in IE and firefox.
Although i have tried followings there is no luck.
HTML:
<p id="captchacontainerp" class="captchacontainer"></p>
-------------------------------------------------------------
$('#captchacontainerp').prepend($("<img id='imCaptcha' class='imgCaptcha' src='/Custom/AppCode/Utilities/CaptchaGenerator.ashx'></img>"));
-------------------------------------------------------------
var img = $('<img id="imCaptcha" class="imgCaptcha">');
img.attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx');
$('#captchacontainerp').empty();
img.appendTo('#captchacontainerp');
---------------------------------------------------------------
$('#captchacontainerp').empty();
$('#captchacontainerp').append($("<img id='imCaptcha' class='imgCaptcha' src='/Custom/AppCode/Utilities/CaptchaGenerator.ashx'></img>"));
IE caching all GET request, so add a timestamp to your request URL e.g :
$(".linkEmail").click(function () {
//Load captcha image
$('.imgCaptcha').attr('src', '/Custom/AppCode/Utilities/CaptchaGenerator.ashx?'+new Date().getTime());
$('#emailModal').modal();
});
Have you tried setting the src attribute to '' before changing it again?
Also, what are the caching settings you are using (both locally, and on the server)
If you specify any inline style attribute, Height or Width like,
<img src="themes/images/01.png" height="100" width="100" />
<img src="themes/images/01.png" style="height:100px; width=100px;" />
then first remove it and try again.
Even if you externally specify style using style tag,
#imageId{
height : 100px;
width : 100px;
}
then also first remove it and try.
After you remove the style attribute from the images, it will display image.
Height attribute is may work with IE but width attribute not working.
If the above solution doesn't work, then :
Sometime PNG files are not displaying as well. So try to use their JPG image.
I had the same problem when trying to call re captcha button.
After some searching, now function works fine in almost all the famous browsers(chrome,Firefox,IE,Edge,...):
function recaptcha(theUrl) {
$.get(theUrl, function(data, status){});
document.getElementById("captcha-img").src = "";
setTimeout(function(){
document.getElementById("captcha-img").src = "captcha?"+new Date().getTime();
}, 0);
}
'theUrl' is used to render new captcha image and can be ignored in your case. The most important point is generating new URL which forces FF and IE to rerender the image.

How to reset the Jcrop plugin? I.e. How to allow changing the source of the target image?

The application I'm working on allows users to add an unlimited number of images onto a viewport. With those images, a series of operations are allowed: resize, drag, rotate, and crop. For the cropping feature, I'm using the Jcrop plugin.
When clicking on the control icon for cropping, a lightbox appears, that shows the selected image (the <img> element is one and the same, only the src attribute value changes each time) and allows the user to crop it. The event handler associated triggered when the crop icon is clicked is:
$(document).on("click", "div.cropper", function(){
var ctrl = $(this),
ref = ctrl.attr("reference"),
obj = returnObj(objects,ref),
target = $("#crop-target")
crop_params = {};
target.attr("src",obj.src);
target.Jcrop({
onSelect: function(c){
crop_params = c;
}
});
});
Given the code above, the cropping works perfectly, but ONLY with the first image I try it on. When I click on the "cropper" icon for any other images after that, the first image is shown.
How can I work around this problem?
PS: I've searched through the already existing questions about Jcrop and couldn't find an answer to my particular problem.
You just need to create a new img tag and start jCrop with that.
$('#parent_tag #img_to_crop').remove();
$('#parent_tag').html('<img id="img_to_crop"></img>');
$('#parent_tag #img_to_crop').Jcrop({ options ... });

How to show a spinner while loading an image via JavaScript

I'm currently working on a web application which has a page which displays a single chart (a .png image). On another part of this page there are a set of links which, when clicked, the entire page reloads and looks exactly the same as before except for the chart in the middle of the page.
What I want to do is when a link is clicked on a page just the chart on the page is changed. This will speed things up tremendously as the page is roughly 100kb large, and don't really want to reload the entire page just to display this.
I've been doing this via JavaScript, which works so far, using the following code
document.getElementById('chart').src = '/charts/10.png';
The problem is that when the user clicks on the link, it may take a couple of seconds before the chart changes. This makes the user think that their click hasn't done anything, or that the system is slow to respond.
What I want to happen is display a spinner / throbber / status indicator, in place of where the image is while it is loading, so when the user clicks the link they know at least the system has taken their input and is doing something about it.
I've tried a few suggestions, even using a psudo time out to show a spinner, and then flick back to the image.
A good suggestion I've had is to use the following
<img src="/charts/10.png" lowsrc="/spinner.gif"/>
Which would be ideal, except the spinner is significantly smaller than the chart which is being displayed.
Any other ideas?
I've used something like this to preload an image and then automatically call back to my javascript when the image is finished loading. You want to check complete before you setup the callback because the image may already be cached and it may not call your callback.
function PreloadImage(imgSrc, callback){
var objImagePreloader = new Image();
objImagePreloader.src = imgSrc;
if(objImagePreloader.complete){
callback();
objImagePreloader.onload=function(){};
}
else{
objImagePreloader.onload = function() {
callback();
// clear onLoad, IE behaves irratically with animated gifs otherwise
objImagePreloader.onload=function(){};
}
}
}
You could show a static image that gives the optical illusion of a spinny-wheel, like these.
Using the load() method of jQuery, it is easily possible to do something as soon as an image is loaded:
$('img.example').load(function() {
$('#spinner').fadeOut();
});
See: http://api.jquery.com/load-event/
Use the power of the setTimeout() function (More info) - this allows you set a timer to trigger a function call in the future, and calling it won't block execution of the current / other functions (async.).
Position a div containing the spinner above the chart image, with it's css display attribute set to none:
<div> <img src="spinner.gif" id="spinnerImg" style="display: none;" /></div>
The nbsp stop the div collapsing when the spinner is hidden. Without it, when you toggle display of the spinner, your layout will "twitch"
function chartOnClick() {
//How long to show the spinner for in ms (eg 3 seconds)
var spinnerShowTime = 3000
//Show the spinner
document.getElementById('spinnerImg').style.display = "";
//Change the chart src
document.getElementById('chart').src = '/charts/10.png';
//Set the timeout on the spinner
setTimeout("hideSpinner()", spinnerShowTime);
}
function hideSpinner() {
document.getElementById('spinnerImg').style.display = "none";
}
Use CSS to set the loading animation as a centered background-image for the image's container.
Then when loading the new large image, first set the src to a preloaded transparent 1 pixel gif.
e.g.
document.getElementById('mainimg').src = '/images/1pix.gif';
document.getElementById('mainimg').src = '/images/large_image.jpg';
While the large_image.jpg is loading, the background will show through the 1pix transparent gif.
Building on Ed's answer, I would prefer to see something like:
function PreLoadImage( srcURL, callback, errorCallback ) {
var thePic = new Image();
thePic.onload = function() {
callback();
thePic.onload = function(){};
}
thePic.onerror = function() {
errorCallback();
}
thePic.src = srcURL;
}
Your callback can display the image in its proper place and dispose/hide of a spinner, and the errorCallback prevents your page from "beachballing". All event driven, no timers or polling, plus you don't have to add the additional if statements to check if the image completed loading while you where setting up your events - since they're set up beforehand they'll trigger regardless of how quickly the images loads.
Some time ago I have written a jQuery plugin which handles displaying a spinner automatically http://denysonique.github.com/imgPreload/
Looking in to its source code should help you with detecting when to display the spinner and with displaying it in the centre of the loaded image.
I like #duddle's jquery method but find that load() isn't always called (such as when the image is retrieved from cache in IE). I use this version instead:
$('img.example').one('load', function() {
$('#spinner').remove();
}).each(function() {
if(this.complete) {
$(this).trigger('load');
}
});
This calls load at most one time and immediately if it's already completed loading.
put the spinner in a div the same size as the chart, you know the height and width so you can use relative positioning to center it correctly.
Aside from the lowsrc option, I've also used a background-image on the img's container.
Be aware that the callback function is also called if the image src doesn't exist (http 404 error). To avoid this you can check the width of the image, like:
if(this.width == 0) return false;
#iAn's solution looks good to me. The only thing I'd change is instead of using setTimeout, I'd try and hook into the images 'Load' event. This way, if the image takes longer than 3 seconds to download, you'll still get the spinner.
On the other hand, if it takes less time to download, you'll get the spinner for less than 3 seconds.
I would add some random digits to avoid the browser cache.

Categories