Jqueryfileupload BlueImp Multiple file uploads with sendAPI - php

I am trying to send multiple files with one ajax call .
THe problem is i cant get my progress work out getting this line
TypeError: data.context is undefined
data.context.find('input').val(progress).change();
Cant figure out how to manage progress for each tpl with sendAPI >?I searched a lot try out different thing the basic reason for doing this is i want one ajax request and to have control after that request completes .
MYHTML
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<div>
<div id="drop">
Drop Here <span style="color:white;text-transform:none;font-size: 13px"> OR <span>
<a>Browse</a>
<input type="file" name="upl[]" multiple/>
</div>
<ul>
<!-- The file uploads will be shown here -->
</ul>
</div>
</form>
MY JQUERY
// Initialize the jQuery File Upload plugin
$('#upload').fileupload({
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 100,
imageMaxHeight: 100,
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
dropZone: $('#drop'),
add: function(e, data) {
var type = data.files[0].type;
var size = data.files[0].size;
if ( type == 'image/jpeg' || type == 'image/png' || type == 'image/gif' ) {
if(size<=350000000)
{
// var preview = '<img src="' + URL.createObjectURL(data.files[0]) + '"/>';
var tpl = $('<li class="working"><input type="text" value="0" data-width="48" data-height="48"' +
' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><div class="preview"></div><p></p><span></span></li>');
tpl.find('p').text(data.files[0].name).append('<i>' + formatFileSize(data.files[0].size) + '</i>');
loadImage(data.files[0],
function(img) {
tpl.find('.preview').html(img);
},
{
minWidth: 80,
minHeight: 60, maxWidth: 80, maxHeight: 60, contain: true} // Options
);
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
// Initialize the knob plugin
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function() {
if (tpl.hasClass('working')) {
jqXHR.abort();
}
tpl.fadeOut(function() {
tpl.remove();
});
});
myfiles.push(data.files[0]);
} else{
noty({type:'error',text: 'file exceeds limit of 350Kb'});
}//check for file type
} else
{
noty({type:'error',text: 'Invalid file type.Please make sure image has valid extension jpeg|gif|jpg'});
}
// $('#post_picture').on('click',function(){
//
//
//
// var jqXHR = data.submit().success(function (result, textStatus, jqXHR) {ar.push(result)});
//
//
// tpl.fadeOut(function() {
// tpl.remove();
// });
// $('#post_picture').off('click');
//
//
//
// });
},
complete:function(e,data)
{
},
progress: function(e, data) {
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if (progress == 100) {
data.context.removeClass('working');
}
},
fail: function(e, data) {
// Something has gone wrong!
data.context.addClass('error');
}
});
$(document).on('click','#post_picture',function(){
alert('asdas');
$('#upload').fileupload('send', {files: myfiles});
});

This is how i did it Why do these days no body answers :)
var myfiles = [];
// Initialize the jQuery File Upload plugin
$('#upload').fileupload({
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 100,
imageMaxHeight: 100,
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
dropZone: $('#drop'),
add: function(e, data) {
var type = data.files[0].type;
var size = data.files[0].size;
if (type == 'image/jpeg' || type == 'image/png' || type == 'image/gif') {
if (size <= 350000000)
{
// var preview = '<img src="' + URL.createObjectURL(data.files[0]) + '"/>';
var tpl = $('<li class="working"><input type="text" value="0" data-width="48" data-height="48"' +
' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><div class="preview"></div><p></p><span></span></li>');
tpl.find('p').text(data.files[0].name).append('<i>' + formatFileSize(data.files[0].size) + '</i>');
loadImage(data.files[0],
function(img) {
tpl.find('.preview').html(img);
},
{
minWidth: 80,
minHeight: 60, maxWidth: 80, maxHeight: 60, contain: true} // Options
);
// Add the HTML to the UL element
data.context = tpl.appendTo(ul);
// Initialize the knob plugin
tpl.find('input').knob();
// Listen for clicks on the cancel icon
tpl.find('span').click(function() {
if (tpl.hasClass('working'))
{
data='';
}
tpl.fadeOut(function() {
tpl.remove();
});
});
// myfiles.push(data.files[0]);
} else {
noty({type: 'error', text: 'file exceeds limit of 350Kb'});
}//check for file type
} else
{
noty({type: 'error', text: 'Invalid file type.Please make sure image has valid extension jpeg|gif|jpg'});
}
$('#post_picture').on('click', function() {
if(data!='')
{
var jqXHR = data.submit().success(function(result, textStatus, jqXHR) {
});
}
tpl.fadeOut(function() {
tpl.remove();
});
$('#post_picture').off('click');
});
},
stop: function(e) {
console.log(myfiles);
},
progress: function(e, data) {
// Calculate the completion percentage of the upload
var progress = parseInt(data.loaded / data.total * 100, 10);
// Update the hidden input field and trigger a change
// so that the jQuery knob plugin knows to update the dial
data.context.find('input').val(progress).change();
if (progress == 100) {
data.context.removeClass('working');
}
},
fail: function(e, data) {
// Something has gone wrong!
data.context.addClass('error');
}
}).on('fileuploaddone', function(e, data) {
myfiles.push(data.result);
});

Related

Dropzone using div passing files(multiple images) to controller through ajax not working

Im trying to create a dropzone in div with class dropzone,im getting dropone and can load images on it but can't pass it to controller, but data is not passig through jquery to cotroller.... removing files, everything else are working fine..but i can't get the uploaded files , can someone please tell whats the problm is, i wanted to insert multiple images,
This is div:
<div class="col-md-12" style="margin-bottom: 48px; bottom: -50px; border-color:white ">
<div class="dropzone" id="mydropzone" action="<?php echo URL.'Events/addeventdetails'?>" >
<h1 align="center"><i> Drag or Drop Image Here</i></h1>
</div>
</div>
Jquery:
<script type="text/javascript">
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone('div#mydropzone', {
addRemoveLinks: true,
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 15,
paramName: 'file',
clickable: true,
url: '<?php echo URL . 'Events/addeventdetails' ?>',
init: function () {
var myDropzone = this;
// Update selector to match your button
$btn.click(function (e) {
e.preventDefault();
if ( $form.valid() ) {
myDropzone.processQueue();
}
return false;
});
this.on('sending', function (file, xhr, formData) {
// Append all form inputs to the formData Dropzone will POST
var data = $form.serializeArray();
$.each(data, function (key, el) {
formData.append(el.name, el.value);
});
console.log(formData);
});
},
error: function (file, response){
if ($.type(response) === "string")
var message = response; //dropzone sends it's own error messages in string
else
var message = response.message;
file.previewElement.classList.add("dz-error");
_ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
_results.push(node.textContent = message);
}
return _results;
},
successmultiple: function (file, response) {
console.log(file, response);
$modal.modal("show");
},
completemultiple: function (file, response) {
console.log(file, response, "completemultiple");
//$modal.modal("show");
},
reset: function () {
console.log("resetFiles");
this.removeAllFiles(true);
}
});
</script>
Controller:
$uploaddir = './uploads';
$images = $_FILES;
$data = [];
foreach ($images as $key => $image) {
$name = $image['name'];
$uploadfile = $uploaddir . basename($name);
if (move_uploaded_file($image['tmp_name'], $uploadfile)) {
$data[$key]['success'] = true;
$data[$key]['src'] = $name;
} else {
$data[$key]['success'] = false;
$data[$key]['src'] = $name;
}
}
$this->Common_model->form_insertpic('images');
I can see that you declared var myDropzone twice. That might be a problem.
Check if the ajax call is actualy trigered after you upload an image.
Var_dump($_FILES) in your controller to see what's in there.
I've done it this way. Try it like this:
let myDropzone= $("#mydropzone");
const myDropzoneImage = {
paramName: "file", // name used to transfer the file //
maxFiles: 50,
maxFilesize: 5,
resizeWidth: 350,
resizeHeight: 258,
thumbnailWidth: 350,
thumbnailHeight: 258,
addRemoveLinks: true,
dictResponseError: "Server not Configured",
acceptedFiles: ".png,.jpg,.jpeg",
//previewsContainer: "#your preview container",
init: function() {
let self = this;
let prevImage = "";
self.options.dictRemoveFile = "Delete";
//New file added
self.on("addedfile", function(file) {
//console.log("new file added ", file);
});
// On removing file
self.on("removedfile", function(file) {
// put your ajax call for remove
});
self.on("success", function(file, responseText) {
prevFile = responseText.img_id;
});
self.on("error", function(file){
// console.log("File Failed to Upload");
});
//Check image width and height
self.on("thumbnail", function(file) {
if (file.width > maxImageWidth || file.height > maxImageHeight) {
file.rejectDimensions()
}
else {
file.acceptDimensions();
}
});
},
accept: function(file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function() {
done("Image width or height too big."); };
}
}
}
myDropzone.dropzone(myDropzoneImage);
And make sure this url action="<?php echo URL.'Events/addeventdetails'?>" is correct!

Opening php file in mymodal box and passing a variable to it

I have a modal box that opens content from the footer of a page (a hidden div). I am trying to launch the modal and display the content of another .php file whilst passing a variable that can be used to SELECT from a DB Any ideas?
Here is the code:
The modal box link
Click Me For A Modal
The JS
(function($) {
$('a[data-reveal-id]').live('click', function(e) {
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$('#'+modalLocation).reveal($(this).data());
});
The .php file with the modalbox content
<div id="myModal" class="reveal-modal">
<div>content called from DB using passed variable</div>
<p>more content</p>
<a class="close-reveal-modal">×</a>
Does anyone have any ideas please?
-----------------------------------------------------------------------------------
UPDATED!
Here is the full js file:
(function($) {
$('a[data-reveal-id').live('click', function(e)
{
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$.ajax({
url: 'code.php',
data: '$varible',
type: 'GET',
error: function()
{
// If there's an issue, display an error...
},
success: function(output)
{
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
}
});
})
$.fn.reveal = function(options) {
var defaults = {
animation: 'fadeAndPop', //fade, fadeAndPop, none
animationspeed: 300, //how fast animtions are
closeonbackgroundclick: true, //if you click background will modal close?
dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
};
var options = $.extend({}, defaults, options);
return this.each(function() {
var modal = $(this),
topMeasure = parseInt(modal.css('top')),
topOffset = modal.height() + topMeasure,
locked = false,
modalBG = $('.reveal-modal-bg');
if(modalBG.length == 0) {
modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal);
}
//Entrance Animations
modal.bind('reveal:open', function () {
modalBG.unbind('click.modalEvent');
$('.' + options.dismissmodalclass).unbind('click.modalEvent');
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modal.css({'top': $(document).scrollTop()-topOffset, 'opacity' : 0, 'visibility' : 'visible'});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"top": $(document).scrollTop()+topMeasure + 'px',
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "fade") {
modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(document).scrollTop()+topMeasure});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "none") {
modal.css({'visibility' : 'visible', 'top':$(document).scrollTop()+topMeasure});
modalBG.css({"display":"block"});
unlockModal()
}
}
modal.unbind('reveal:open');
});
//Closing Animation
modal.bind('reveal:close', function () {
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"top": $(document).scrollTop()-topOffset + 'px',
"opacity" : 0
}, options.animationspeed/2, function() {
modal.css({'top':topMeasure, 'opacity' : 1, 'visibility' : 'hidden'});
unlockModal();
});
}
if(options.animation == "fade") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"opacity" : 0
}, options.animationspeed, function() {
modal.css({'opacity' : 1, 'visibility' : 'hidden', 'top' : topMeasure});
unlockModal();
});
}
if(options.animation == "none") {
modal.css({'visibility' : 'hidden', 'top' : topMeasure});
modalBG.css({'display' : 'none'});
}
}
modal.unbind('reveal:close');
});
//Open Modal Immediately
modal.trigger('reveal:open')
//Close Modal Listeners
var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
if(options.closeonbackgroundclick) {
modalBG.css({"cursor":"pointer"})
modalBG.bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
}
$('body').keyup(function(e) {
if(e.which===27){ modal.trigger('reveal:close'); } // 27 is the keycode for the Escape key
});
function unlockModal() {
locked = false;
}
function lockModal() {
locked = true;
}
});//each call
}//orbit plugin call
})(jQuery);
Here is the html trigger:
<a class="big-link" href="#" data-reveal-id="myModal">Click Me to open modal</a>
Here is the code.php, file containing the modal:
<div id="myModal" class="reveal-modal"><div>content called from DB using passed variable</div><p>more content</p><a class="close-reveal-modal">×</a>
The issue at the minute is not passing the variable, but actually lauching the modal with the content of code.php
Thanks again for your time with this problem!
Without knowing what variables you're looking to pass, and what you're trying to grab, you can modify this. I haven't tested it so you may have to do some tweaking.
$('a[data-reveal-id').live('click', function(e)
{
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$.ajax({
url: 'URL_TO_YOUR_PHP',
data: 'YOUR_VARIABLE', // Look at how to pass data using GET, or POST
type: 'GET' or 'POST', // Choose one, and pass the data above appropriately
error: function()
{
// If there's an issue, display an error...
},
success: function(output)
{
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
}
});
})
-- EDIT --
Now the problem is that you don't have #myModal available in your HTML, yet. So, what you want to do is change the following line accordingly:
$('#' + modalLocation).innerHTML(output).reveal( $(this).data() );
-- BECOMES --
$("body").append(output).reveal( $(this).data() );
In your CSS you'll want to initially hide your modal box that way it's revealed appropriately.

Jquery-fileupload plugin - uploads file but says 'file upload failed'

I click 'Add files' choose a file it then creates a thumbnail (depending on browser) and displays the 'Upload' button beneath it.
when I click 'Upload', sometimes it uploads the file and says 'File upload failed.' - the file is actually uploaded but I still get this message. Sometimes it doesn't upload and i get the same message.
I have two errors -
1st is in the PHP error log 'PHP Warning: exif_imagetype(): Filename cannot be empty in ***\***\UploadHandler.php' I don't get it all the time though.
2nd is jquery.validation on the page - 'Uncaught Error: Syntax error, unrecognized expression: [name=files[]]'
In the debugger it jumps straight to '.on('fileuploadfail', function (e, data)' without going anywhere else and once that completes it refreshes the whole page..guess I need a 'return false' somewhere?
Thanks for your help.
HTML:
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br>
<br>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
Javascript:
var filepower = function () {
'use strict';
var url = 'server/php/',
uploadButton = $('<button/>')
.addClass('btn btn-primary')
.prop('disabled', true)
.text('Processing...')
.on('click', function () {
var $this = $(this),
data = $this.data();
$this
.off('click')
.text('Abort')
.on('click', function () {
$this.remove();
data.abort();
});
data.submit().always(function () {
$this.remove();
});
});
$('#fileupload').fileupload({
url: url,
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 5000000, // 5 MB
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('#files');
$.each(data.files, function (index, file) {
var node = $('<p/>')
.append($('<span/>').text(file.name));
if (!index) {
node
.append('<br>')
.append(uploadButton.clone(true).data(data));
}
node.appendTo(data.context);
});
}).on('fileuploadprocessalways', function (e, data) {
var index = data.index,
file = data.files[index],
node = $(data.context.children()[index]);
if (file.preview) {
node
.prepend('<br>')
.prepend(file.preview);
}
if (file.error) {
node
.append('<br>')
.append($('<span class="text-danger"/>').text(file.error));
}
if (index + 1 === data.files.length) {
data.context.find('button')
.text('Upload')
.prop('disabled', !!data.files.error);
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}).on('fileuploaddone', function (e, data) {
$.each(data.result.files, function (index, file) {
if (file.url) {
var link = $('<a>')
.attr('target', '_blank')
.prop('href', file.url);
$(data.context.children()[index])
.wrap(link);
} else if (file.error) {
var error = $('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index])
.append('<br>')
.append(error);
}
});
}).on('fileuploadfail', function (e, data) {
$.each(data.files, function (index, file) {
var error = $('<span class="text-danger"/>').text('File upload failed.');
$(data.context.children()[index])
.append('<br>')
.append(error);
});
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
};
You didn't post your source code, but if you can add to the response on the server, then you can fix it by implementing the return structure here:
https://github.com/blueimp/jQuery-File-Upload/wiki/JSON-Response
I can't help you if you can't change the server, though the library author says there's a way to modify/over-ride the expected JSON fields so it doesn't error out.
Either return an appropriate expected response from the server or get data.jqXHR . this will contain the response from the server. you can use that to check whether upload was successful or not.

jQuery file uploader showing error when restrictions has been added

I wanted a jQuery multi file uploader with process bar. Thats why I went to this url. In this there is one option called basic. I just downloaded all the files and I used only the basic.html file. With basic.html files code I can easily upload files. But I want some restriction so that user will only upload some kind of files like png,jpg and gif only. So to use restriction in upload I checked for documentation and I got this link.
So I mixed all the codes like this
<div class="container">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Select files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br>
<br>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
<br>
</div>
<script>
/*jslint unparam: true */
/*global window, $ */
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === '' ?
'//jquery-file-upload.appspot.com/' : 'server/php/';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
options: {
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
processQueue: [
action: 'validate',
acceptFileTypes: '#',
disabled: '#disableValidation'
]
},
processActions: {
validate: function (data, options) {
if (options.disabled) {
return data;
}
var dfd = $.Deferred(),
file = data.files[data.index],
if (!options.acceptFileTypes.test(file.type)) {
file.error = 'Invalid file type.';
dfd.rejectWith(this, [data]);
} else {
dfd.resolveWith(this, [data]);
}
return dfd.promise();
}
}
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
But here I can't upload any files also I can't get restriction in upload. After all this codes in my firefox console tab I got an error like
SyntaxError: missing ] after element list
action: 'validate',
Can someone kindly tell me why this error is here? How to solve this? Any help and suggestions will be really appreciable. Thanks..
Missing a comma there between literal objects, after processActions
/*jslint unparam: true */
/*global window, $ */
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === '' ?
'//jquery-file-upload.appspot.com/' : 'server/php/';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
options: {
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
processQueue: [
action: 'validate',
acceptFileTypes: '#',
disabled: '#disableValidation'
],
processActions: {
validate: function (data, options) {
if (options.disabled) {
return data;
}
var dfd = $.Deferred(),
file = data.files[data.index],
if (!options.acceptFileTypes.test(file.type)) {
file.error = 'Invalid file type.';
dfd.rejectWith(this, [data]);
} else {
dfd.resolveWith(this, [data]);
}
return dfd.promise();
}
},
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
} // end of options
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});

Magento how to get original image file after resize?

I am building a webshop in magento.
On the product detailpage i am resizing the image in Magento itself so that it doesn't have to load the very big image.
When i click on the image it should open a lightbox with the image but this time it has to be larger.
But because i resized it the quality really is really low.
There is one other thing which i can't seem to figure out.
I also have some smaller images which should appear as main image when they are hovered over. If i hover over them my resize doesn't work anymore.
I hope someone can point out my mistakes :)
Here is my code:
HTML/PHP code for getting and resizing the image.
<p class="product-image">
<?php
$_img = '<img id="image1" src="'.$this->helper('catalog/image')->init($_product, 'image')->resize(235, 350).'" alt="'.$this->htmlEscape($this->getImageLabel()).'" title="'.$this->htmlEscape($this->getImageLabel()).'" width="235" height="350 " />';
echo $_helper->productAttribute($_product, $_img, 'image');
?>
Javascript code for switching the images on hover.
function imageswitcher(imagename){
jQuery('#image1').attr('src', imagename);
var options = {
zoomrange: [<?php echo Mage::getStoreConfig('featurezoom/zoomrange/start');?>, <?php echo Mage::getStoreConfig('featurezoom/zoomrange/end');?>],
magnifiersize: [<?php echo Mage::getStoreConfig('featurezoom/magnifiersize/height');?>,<?php echo Mage::getStoreConfig('featurezoom/magnifiersize/width');?>],
magnifierpos: '<?php echo Mage::getStoreConfig('featurezoom/general/magnifierpos');?>',
cursorshade: true,
largeimage: imagename //<-- No comma after last option!
}
jQuery('#image1').addimagezoom(options);
}
function doTimer(imageName){
myTimer=setTimeout(function(){
imageswitcher(imagename);
}, 2000);
}
Event.observe(window, 'load', function() {
jQuery('#image1').addimagezoom({
zoomrange: [<?php echo Mage::getStoreConfig('featurezoom/zoomrange/start');?>, <?php echo Mage::getStoreConfig('featurezoom/zoomrange/end');?>],
magnifiersize: [<?php echo Mage::getStoreConfig('featurezoom/magnifiersize/height');?>,<?php echo Mage::getStoreConfig('featurezoom/magnifiersize/width');?>],
magnifierpos: '<?php echo Mage::getStoreConfig('featurezoom/general/magnifierpos');?>',
cursorshade: true,
largeimage: '<?php echo $this->helper('catalog/image')->init($_product, 'image');?>' //<-- No comma after last option!
})
});
jQuery code for opening positioning and closing the lightbox.
(function(window, $, undefined) {
jQuery(function() {
/*$(window).on('click', function(e) {
console.log(e.target);
//e.preventDefault();
});*/
$('.zoomtracker').on('click', function(e) {
removeLightbox();
$('body').css('overflow-y', 'hidden'); // hide scrollbars!
$('<div id="overlay"></div>')
.css('top', $(document).scrollTop())
.css('opacity', '0')
.appendTo('body');
$('<div id="lightbox"></div>')
.hide()
.appendTo('body');
var img = new Image();
img.onload = function() {
var width = img.width,
height = img.height;
$('<img id="lightboxImage" />')
.attr('width', '235')
.attr('src', img.src)
.load(function() {
positionLightboxImage(e);
})
.click(function() {
removeLightbox();
})
.appendTo('#lightbox');
};
img.src = $('#image2').attr('src');
$('#overlay').click(function(e){
})
/*var height = $('<img />').attr('width', .width());
alert(height);
$('<img />')
.attr('src', $(this).attr('href'))
.load(function() {
positionLightboxImage(e);
})
.click(function() {
removeLightbox();
})
.appendTo('#lightbox');
return false;*/
e.preventDefault();
});
});
function positionLightboxImage(e) {
var top = 173;
var left = 271;
/* In plaats van de img width en height de hoogte en breedte van het scherm berekenen en aan de hand heirvan het centrum bepalen. */
$('#lightbox')
.css({
'top': top,
'left': left
})
.fadeIn(500)
.animate({'width': '640','left': '50%', 'margin-left': -($('#lightbox').width()/2), 'top': '19%', 'margin-top': -($('#lightbox').height()/2)}, {queue: false}, 8000);
$('#lightboxImage')
.animate({'width': '550','height': '930'}, {queue: false}, 8000)
}
function removeLightbox() {
$('#overlay, #lightbox')
.fadeOut(500, function() {
$(this).remove();
$('body').css('overflow-y', 'auto'); // show scrollbars!
})
.animate({'width': '235','left': '-72', 'margin-left': ($('#lightbox').width()/2), 'top': '-295', 'margin-top': ($('#lightbox').height()/2)}, {queue: false}, 8000);
$('#lightboxImage')
.animate({'width': '235', 'height': '350'}, {queue: false}, 8000)
}
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) +
$(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - this.outerWidth()) / 2) +
$(window).scrollLeft()) + "px");
return this;
}
})(window, jQuery);
Try to use naturalWidth and naturalHeight methods after image load and your scripts initialised.
jsFiddle example.
var img = $("img")[0];
alert( img.naturalWidth + "x" + img.naturalHeight );
Note: if you wan to do this with another way, you can inspect this answer too: https://stackoverflow.com/a/670433/1428241

Categories