I want to disable button if any image greater then one mb using javascript - javascript

I am beginner with javascript and I am using this plugin for uploading multiple image https://www.cssscript.com/demo/multiple-image-uploader/ and just i want to disable button if any image is greater then one mb the button should be disabled Does anyone khow where i need to put this code $('#btnSubmit').prop('disabled', true); please help me ? thank u.
html view
<div class="multiple-uploader" id="multiple-uploader">
<div class="mup-msg">
<span class="mup-main-msg">click to upload images.</span>
<span class="mup-msg" id="max-upload-number">Upload up to 10 images</span>
<span class="mup-msg">Only images, pdf and psd files are allowed for upload</span>
</div>
</div>
<button type="submit" id="btnSubmit" class="btn btn-primary w-100">Save</button>
javascript
class MultipleUploader {
#multipleUploader;
#$imagesUploadInput;
constructor( multiUploaderSelector )
{
this.#multipleUploader = document.querySelector(multiUploaderSelector);
this.#$imagesUploadInput = document.createElement('input')
}
init( { maxUpload = 3 , maxSize = 1 , formSelector = 'form' , filesInpName = 'images' } = {} )
{
const form = document.querySelector(formSelector);
if (! this.#multipleUploader ) // check if the end user didnt write the multiple uploader div
throw new Error('The multiple uploader element doesnt exist');
if (! form ) // check if there is no form with this selector
throw new Error('We couldn\'t find a form with this selector: ' + formSelector);
// ensure that the form has enctype attribute with the value multipart/form-data
form.enctype = 'multipart/form-data'
if ( document.getElementById('max-upload-number') )
document.getElementById('max-upload-number').innerHTML = `Upload up to ${ maxUpload } files`;
// create multiple file input and make it hidden
this.#$imagesUploadInput.type = 'file';
this.#$imagesUploadInput.name = `${filesInpName}[]`;
this.#$imagesUploadInput.multiple = true;
this.#$imagesUploadInput.accept = "image";
this.#$imagesUploadInput.class = "image";
this.#$imagesUploadInput.style.setProperty('display','none','important');
// create multiple file input and make it hidden
// append the newly created input to the form with the help of the formSelector provided by the user
document.querySelector(formSelector).append( this.#$imagesUploadInput );
this.#multipleUploader.addEventListener("click", (e) => {
if ( e.target.className === 'multiple-uploader' || e.target.className === 'mup-msg' || e.target.className === 'mup-main-msg' )
this.#$imagesUploadInput.click() // trigger the input file to upload images
});
const self = this;
// preview the uploaded images
this.#$imagesUploadInput.addEventListener("change",function () {
if (this.files.length > 0)
{
self.#multipleUploader.querySelectorAll('.image-container').forEach( image => image.remove() ); // clear the previous rendered images
self.#multipleUploader.querySelector('.mup-msg').style.setProperty('display', 'none'); // hide the hint texts inside drop zone
// if the length of uploaded images greater than the images uploaded by the user, the maximum uploaded will be considered
const uploadedImagesCount = this.files.length > maxUpload ? maxUpload : this.files.length;
const unAcceptableImagesIndices = [];
for (let index = 0; index < uploadedImagesCount; index++) {
const imageSize = self.#bytesToSize( this.files[ index ].size );
const isImageSizeAcceptable = self.#checkImageSize( index , imageSize , maxSize , 'MB' );
// appended the newly created image to the multiple uploader
self.#multipleUploader.innerHTML += `
<div class="image-container" data-image-index="${ index }" id="mup-image-${ index }" data-acceptable-image="${ +isImageSizeAcceptable }" >
<div class="image-size"> ${ imageSize['size'] + ' ' + imageSize['unit'] } </div>
${ !isImageSizeAcceptable ? `<div class="exceeded-size"> greater than ${ maxSize } MB </div>` : '' }
<img src="${ URL.createObjectURL( this.files[ index ]) }" class="image-preview" alt="" />
</div>`;
if ( ! isImageSizeAcceptable )
unAcceptableImagesIndices.push( index )
}
unAcceptableImagesIndices.forEach( (index ) => self.#removeFileFromInput(index, false ))
}
});
// event for deleting uploaded images
document.addEventListener('click',function(e){
if( e.target.className === 'image-container' ) // clicked on remove pseudo element
{
const imageIndex = e.target.getAttribute(`data-image-index`)
const imageIsAcceptable = e.target.getAttribute(`data-acceptable-image`)
e.target.remove() // remove the html element from the dom
if ( +imageIsAcceptable )
self.#removeFileFromInput(imageIndex)
if ( document.querySelectorAll('.image-container').length === 0 ) // if there are no images
self.clear();
self.#reorderFilesIndices(); // reorder images indices
}
});
return this;
}
clear()
{
this.#multipleUploader.querySelectorAll('.image-container').forEach( image => image.remove() );
this.#multipleUploader.querySelectorAll('.mup-msg').forEach( msg => msg.style.setProperty('display', 'flex') );
this.#$imagesUploadInput.value = [];
}
#removeFileFromInput( deletedIndex )
{
// remove the delete file from input
const dt = new DataTransfer()
for (const [ index, file] of Object.entries( this.#$imagesUploadInput.files ))
{
if ( index != deletedIndex )
dt.items.add( file )
}
this.#$imagesUploadInput.files = dt.files
// remove the delete file from input
}
#reorderFilesIndices()
{
document.querySelectorAll('.image-container').forEach( ( element, index) => {
element.setAttribute('data-image-index', index.toString() );
element.setAttribute('id',`mup-image-${ index }`)
});
}
#checkImageSize( imageIndex, imageSize , maxSize )
{
return imageSize['unit'] !== 'MB' || ( imageSize['unit'] === 'MB' && ( imageSize['size'] <= maxSize ) ) ; // return true if acceptable
}
#bytesToSize(bytes)
{
const sizes = ['Bytes', 'KB', 'MB']
const i = parseInt( Math.floor(Math.log(bytes) / Math.log(1024) ), 10)
if (i === 0)
return {size: bytes , unit: sizes[i] }
else
return {size: (bytes / (1024 ** i)).toFixed(1) , unit: sizes[i] }
}
}

Your code already has all the information needed. You have unAcceptableImagesIndices that contains a list of unaccepted images.
So, all you need is just check if unAcceptableImagesIndices length is not zero and disable the button if so.
For example with something like this:
if (this.files.length > 0)
{
// your current code
document.getElementById("btnSubmit").disabled = unAcceptableImagesIndices.length > 0;
}

Related

Javascript - Play audio only when a div is visible in the DOM

I have a problem with my script, and that is that I want to play an audio when I click on a .bbp button, but this button is inside a hidden div that is then cloned.
Only when the cloned div becomes visible in the DOM, I want to play an audio when I click on .bbp, but it does not work for me.
SEE DEMO LIVE (Codepen) - The Snippet does not run on Stackoverflow
Note that if you comment #products, the audio assigned to .bbp yes will play, otherwise it will NOT play, since the audio
script can not identify if #products is visible in the DOM or not.
So, first I need to know that .bbp is visible, and I can not find how I can do it.
Any idea...?
Thanks in advance!
//-----------------
HTML & CSS
#products {display:none}
#derecha {display:none}
<div class="comprar">Clone 1</div> <!--Clone the div from "products" to "derecha"-->
<div class="bbp">X</div> <!--Delete the cloned div placed into "derecha"-->
SCRIP (Play Audio)
let audioHolderComprar = {};
$('.comprar').click(()=>{
let tempIdentifier = Date.now();
audioHolderComprar[tempIdentifier] = new Audio('comprar.mp3');
audioHolderComprar[tempIdentifier].play();
setTimeout(() => {
delete audioHolderComprar[tempIdentifier];
}, audioHolderComprar[tempIdentifier].duration + 1200);
});
//------------------
let audioHolderBorrar = {};
$('.bbp').click(()=>{
let tempIdentifier = Date.now();
audioHolderBorrar[tempIdentifier] = new Audio('borrar.mp3');
audioHolderBorrar[tempIdentifier].play();
setTimeout(() => {
delete audioHolderBorrar[tempIdentifier];
}, audioHolderBorrar[tempIdentifier].duration + 1200);
});
As I've mentioned in my comment, you have two places where you handle the click event for .bpp - these interfere with each other.
Also you're mixing the places where you should add html and javascript code. Though it works, it's a little bit messy.
Replace all of the content in your HTML pane on the left by this:
<div id="container">
<div id="productos">
<!-- =============== -->
<div id="cont-p1" class="cont-p">
<div id="producto-1">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>cont-p1 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp">X</div></div>
</div> <!-- // productos -->
<div class="derecha" id="derecha"></div> <!-- // div derecha -->
<div id="comp-p1" data-clone="cont-p1" class="comp-clone comprar">Clone 1</div>
<div class="cont-num" id="clicks">0</div>
<div class="cont-num" id="clicksdos">0</div>
<div id="cont-resultado">
<input name="total" id="total">
</div>
<div id="cont-note">How to play the audio on the button to close the cloned div <span>.bbp</span><br>( <span class="red">X</span> ),<br>if the audio script can not know that it has been cloned...?
<br><br>
Note the CSS (line 3) that the div container of the all div´s that must be cloned is in <span>display=none</span>, but if you comment this line it can reproduce the audio onclick in the X button</div>
</div> <!-- // container -->
and all of the following goes into the JS pane to the right:
/*
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js
*/
let audioHolderComprar = {};
$('.comprar').click(()=>{
let tempIdentifier = Date.now();
audioHolderComprar[tempIdentifier] = new Audio('https://notificationsounds.com/soundfiles/8b16ebc056e613024c057be590b542eb/file-sounds-1113-unconvinced.mp3');
audioHolderComprar[tempIdentifier].play();
// removing after play process gets over so if won't consume memory
setTimeout(() => {
delete audioHolderComprar[tempIdentifier];
}, audioHolderComprar[tempIdentifier].duration + 1200 /* you can remove threshold value if you wants to */);
});
//------------------
let audioHolderBorrar = {};
let clicks = 0;
let clicksdos = 0;
const safeInt = (key) => {
let value = parseInt(getValue(key));
return (isNaN(value) || value < 0) ? 0 : value;
}
// This loads our clicks from the LocalStorage
const loadClicks = () => {
clicks = safeInt('clicks');
clicksdos = safeInt('clicksdos');
}
const loadHTML = () => {
return getValue('html', '');
}
const loadFromStorage = () => {
let html = loadHTML();
if (html !== '') {
loadClicks();
}
displayClicks();
document.querySelector(".derecha").innerHTML = html;
}
// Display the clicks on the screen
const displayClicks = () => {
clicks = (clicks === NaN) ? 0 : clicks;
clicksdos = (clicksdos === NaN) ? 0 : clicksdos;
document.querySelector('#clicks').innerHTML = clicks;
document.querySelector('#clicksdos').innerHTML = clicksdos;
// Hide / Show Result
let display = (clicks > 0) ? 'block' : 'none';
document.querySelector('#cont-resultado').style.display = display;
document.querySelector('.derecha').style.display = display;
//document.querySelector('#aviso-producto-agregado').style.display = "block";
}
const adjustClicks = (value) => {
clicks += value;
clicksdos += value;
storeValue('clicks', clicks);
storeValue('clicksdos', clicksdos);
displayClicks();
}
const addClick = () => adjustClicks(1);
const removeClick = () => adjustClicks(-1);
// Manage localStorage
const storeValue = (key, value) => (localStorage) ? localStorage.setItem(key, value) : '';
const getValue = (key, defaultValue) => (localStorage) ? localStorage.getItem(key) : defaultValue;
const storeHTML = () => storeValue("html", document.getElementsByClassName("derecha")[0].innerHTML);
// Add a node to the Derecha
const addToDerecha = (nodeId) => {
let node = document.querySelector(`#${nodeId}`);
document.querySelector('.derecha').appendChild(node.cloneNode(true));
storeHTML();
displaySuma();
};
// Monitor ALL click events
document.addEventListener('click', (event) => {
let target = event.target;
// Add
if (target.matches('.comp-clone')) {
addClick();
addToDerecha(event.target.dataset.clone);
}
// Remove
if (target.matches('.bbp')) {
let tempIdentifier = Date.now();
audioHolderBorrar[tempIdentifier] = new Audio('https://notificationsounds.com/soundfiles/99c5e07b4d5de9d18c350cdf64c5aa3d/file-sounds-1110-stairs.mp3');
audioHolderBorrar[tempIdentifier].play();
// removing after play process gets over so if won't consume memory
setTimeout(() => {
delete audioHolderBorrar[tempIdentifier];
}, audioHolderBorrar[tempIdentifier].duration + 1200 /* you can remove threshold value if you wants to */);
getParent('.derecha', target).removeChild(target.parentNode);
removeClick();
storeHTML();
displaySuma();
}
});
// This is just a helper function.
const getParent = (match, node) => (node.matches(match)) ? node : getParent(match, node.parentNode);
// New Script for sum inputs
//const displaySuma = () => document.getElementById("total").value = suma();
const displaySuma=()=>document.getElementById("total").value=suma().toLocaleString("es-ES");
const suma = function() {
return Array.from(document.querySelectorAll(".derecha div .add-prod"))
.reduce((a, v) => a + parseFloat(v.value), 0);
}
// Code to run when the document loads.
document.addEventListener('DOMContentLoaded', () => {
if (localStorage) {
loadFromStorage();
}
displaySuma();
});
</script>
<script>
// Displays the new product alert added when the scroll is detected in the div #derecha
var displaced = document.getElementById('derecha')
if (displaced.scrollHeight > displaced.offsetHeight) {
document.getElementById("notice-product-added").style.display = "block";
};
// LocalStorage for the div #notice-product-added
const showMsgCart=localStorage.getItem('showMsgCarrito');if(showMsgCart==='false'){$('#notice-product-added').hide();}$('#notice-product-added').on('click',function(){$('#notice-product-added').fadeOut('slow');localStorage.setItem('showMsgCarrito','false');});
After that you should hear the closing sound.

Snap.svg Load svg in order not available

I'm trying to get the (load in order) example to work. Here is my code.
I load snap.js and then my code in loadsvg.js it has my plugin. Then main.js with my code calling the function. I get a error in console that says "base.loadFilesDisplayOrdered is not a function". So it can't find it any help will be appreciated. Thanks
Snap.plugin( function( Snap, Element, Paper, global ) {
function addLoadedFrags( whichSVG, fragList, runWhenFinishedFunc ) { // This is called once all the loaded frags are complete
for( var count = 0; count < fragList.length; count++ ) {
myEl = whichSVG.append( fragList[ count ] );
}
runWhenFinishedFunc();
}
Paper.prototype.loadFilesDisplayOrdered = function( list, afterAllLoadedFunc, onEachElementLoadFunc ) {
var image, fragLoadedCount = 0, listLength = list.length, fragList = new Array(), whichSVG = this;
for( var count = 0; count < listLength; count++ ) {
(function() {
var whichEl = count,
fileName = list[ whichEl ],
image = Snap.load( fileName, function ( loadedFragment ) {
fragLoadedCount++;
onEachElementLoadFunc( loadedFragment, fileName );
fragList[ whichEl ] = loadedFragment;
if( fragLoadedCount >= listLength ) {
addLoadedFrags( whichSVG, fragList, afterAllLoadedFunc );
}
} );
})();
}
};
});
Then i call it in main.js
var base = Snap("#svgout");
console.log(base);
var myLoadList = [ "svgs/layer.svg", "svgs/cutout.svg" ];
var myDisplayList = { "Bird.svg": "zoom", "Dreaming_tux.svg": "fade" };
base.loadFilesDisplayOrdered( myLoadList, onAllLoaded, onEachLoaded );
The problem is, you are trying to create Snap into a div element. Snap only works on SVG elements.
Change,
<div id="svgout"></div>
to
<svg id="svgout"></svg>
And the error should go away.
jsfiddle

How to display only one image in ezpublish JS slider

I'm a beginner php developer, and have a shockingly poor fluency in Javascript. An ezpublish website I'm working on has this slider in as a default piece of code, but it displays three items. How can I edit it to show only 1 item? The code is:
(function() {
YUI( YUI3_config ).use( 'node', 'event', 'io-ez', function(Y, result) {
Y.on('domready', function(e) {
var offset = 0;
var limit = 1;
var total = {$block.valid_nodes|count()};
var handleRequest = function(e) {
var className = e.target.get('className');
if ( className == 'carousel-next-button' ) {
offset += 1;
if ( offset > total )
offset = 0;
}
if ( className == 'carousel-prev-button' ) {
var diff = total - offset;
if( offset == 0 )
offset = 0;
else
offset -= 1;
}
var colContent = Y.Node.all('#block-3 .col-content');
colContent.each(function(n, e) {
n.addClass('loading');
var height = n.get('region').bottom - n.get('region').top;
n.setStyle('height', height + 'px');
n.set('innerHTML', '');
});
var data = 'http_accept=json&offset=' + offset;
data += '&limit=' + limit;
data += '&block_id={$block.id}';
Y.io.ez( 'ezflow::getvaliditems', { on: { success: _callBack
}, method: 'POST', data: data } );
};
var _callBack = function(id, o) {
if ( o.responseJSON !== undefined ) {
var response = o.responseJSON;
var colContent = Y.Node.all('#block-{$block.id} .col-content');
for(var i = 0; i < colContent.size(); i++) {
var colNode = colContent.item(i);
if ( response.content[i] !== undefined )
colNode.set('innerHTML', response.content[i] );
}
}
};
var prevButton = Y.one('#block-{$block.id} input.carousel-prev-button');
prevButton.on('click', handleRequest);
var nextButton = Y.one('#block-{$block.id} input.carousel-next-button');
nextButton.on('click', handleRequest);
});
});
})();
</script>
A hand with this would be great x
Looks to me like this code loads each item after the user clicks prevButton or nextButton. So the simplest way to force only a single item to display is probably to hide those buttons.
Without the markup it's hard to say what the optimal solution is, but I would try to find out what makes the particular markup you're working with into a carousel (I'd guess a class containing "carousel") and remove that so that it's just a single item without the carousel functionality.
For what it's worth, this question is not specific to eZ Publish or PHP so I'd consider removing those tags.

upload fails with image greater than 800kb

I have a form where i can drag and drop an image into a canvas and then click an upload button to upload the file to the server. Below is my javascript file and php file. I cannot find where or why this will not allow me to upload something greater than 800kb? I believe its all failing in the php at if(file_put_contents($uploaddir.$randomName, $decodedData)) { but again i dont know why? The sql statment fails to by the way thats why i think its failing at that point in the php file. 32M is php max file size upload.
UPDATE... i removed anything to do with uploading with php in the php and only left echo $randomName.":uploaded successfully"; which now leads me to believe there is something wrong in the JS file at $.post('/mods/photogallery/manager/upload.php?gpID=' + bla, dataArray[index], function(data) { for anything greater than 800kb (ish)
JS
$(document).ready(function() {
// Makes sure the dataTransfer information is sent when we
// Drop the item in the drop box.
jQuery.event.props.push('dataTransfer');
var z = -40;
// The number of images to display
var maxFiles = 1;
var errMessage = 0;
// Get all of the data URIs and put them in an array
var dataArray = [];
// Bind the drop event to the dropzone.
$('#drop-files').bind('drop', function(e) {
// Stop the default action, which is to redirect the page
// To the dropped file
var files = e.dataTransfer.files;
// Show the upload holder
$('#uploaded-holder').show();
$('#drop-files').hide();
// For each file
$.each(files, function(index, file) {
// Some error messaging
if (!files[index].type.match('image.*')) {
if(errMessage == 0) {
$('#drop-files').html('Hey! Images only');
++errMessage
}
else if(errMessage == 1) {
$('#drop-files').html('Stop it! Images only!');
++errMessage
}
else if(errMessage == 2) {
$('#drop-files').html("Can't you read?! Images only!");
++errMessage
}
else if(errMessage == 3) {
$('#drop-files').html("Fine! Keep dropping non-images.");
errMessage = 0;
}
return false;
}
// Check length of the total image elements
if($('#dropped-files > .image').length < maxFiles) {
// Change position of the upload button so it is centered
var imageWidths = ((220 + (40 * $('#dropped-files > .image').length)) / 2) - 20;
$('#upload-button').css({'left' : imageWidths+'px', 'display' : 'block'});
}
// Start a new instance of FileReader
var fileReader = new FileReader();
// When the filereader loads initiate a function
fileReader.onload = (function(file) {
return function(e) {
// Push the data URI into an array
dataArray.push({name : file.name, value : this.result});
// Move each image 40 more pixels across
z = z+40;
var image = this.result;
// Just some grammatical adjustments
if(dataArray.length == 1) {
$('#upload-button span').html("1 file to be uploaded");
} else {
$('#upload-button span').html(dataArray.length+" files to be uploaded");
}
// Place extra files in a list
if($('#dropped-files > .image').length < maxFiles) {
// Place the image inside the dropzone
$('#dropped-files').append('<div class="image" style="background: #fff url('+image+') no-repeat;background-size: cover;background-position: center center;"> </div>');
}
else {
$('#extra-files .number').html('+'+($('#file-list li').length + 1));
// Show the extra files dialogue
$('#extra-files').show();
// Start adding the file name to the file list
$('#extra-files #file-list ul').append('<li>'+file.name+'</li>');
}
};
})(files[index]);
// For data URI purposes
fileReader.readAsDataURL(file);
});
});
function restartFiles() {
// This is to set the loading bar back to its default state
$('#loading-bar .loading-color').css({'width' : '0%'});
$('#loading').css({'display' : 'none'});
$('#loading-content').html(' ');
// --------------------------------------------------------
// We need to remove all the images and li elements as
// appropriate. We'll also make the upload button disappear
$('#upload-button').hide();
$('#dropped-files > .image').remove();
$('#extra-files #file-list li').remove();
$('#extra-files').hide();
$('#uploaded-holder').hide();
$('#drop-files').show();
// And finally, empty the array/set z to -40
dataArray.length = 0;
z = -40;
return false;
}
$('#upload-button .upload').click(function() {
$("#loading").show();
var totalPercent = 100 / dataArray.length;
var x = 0;
var y = 0;
$('#loading-content').html('Uploading '+dataArray[0].name);
$.each(dataArray, function(index, file) {
bla = $('#gpID').val();
$.post('/mods/photogallery/manager/upload.php?gpID=' + bla, dataArray[index], function(data) {
var fileName = dataArray[index].name;
++x;
// Change the bar to represent how much has loaded
$('#loading-bar .loading-color').css({'width' : totalPercent*(x)+'%'});
if(totalPercent*(x) == 100) {
// Show the upload is complete
$('#loading-content').html('Uploading Complete!');
// Reset everything when the loading is completed
setTimeout(restartFiles, 500);
} else if(totalPercent*(x) < 100) {
// Show that the files are uploading
$('#loading-content').html('Uploading '+fileName);
}
// Show a message showing the file URL.
var dataSplit = data.split(':');
if(dataSplit[1] == 'uploaded successfully') {
alert('Upload Was Successfull');
var realData = '<li>'+fileName+' '+dataSplit[1]+'</li>';
$('#drop-files').css({
'background' :'url(/mods/photogallery/photos/' + dataSplit[0] + ') no-repeat',
'background-size': 'cover',
'background-position' : 'center center'
});
$('#uploaded-files').append('<li>'+fileName+' '+dataSplit[1]+'</li>');
// Add things to local storage
if(window.localStorage.length == 0) {
y = 0;
} else {
y = window.localStorage.length;
}
window.localStorage.setItem(y, realData);
} else {
$('#uploaded-files').append('<li><a href="/mods/photogallery/photos/'+data+'. File Name: '+dataArray[index].name+'</li>');
}
});
});
return false;
});
// Just some styling for the drop file container.
$('#drop-files').bind('dragenter', function() {
$(this).css({'box-shadow' : 'inset 0px 0px 20px rgba(0, 0, 0, 0.1)', 'border' : '4px dashed #bb2b2b'});
return false;
});
$('#drop-files').bind('drop', function() {
$(this).css({'box-shadow' : 'none', 'border' : '4px dashed rgba(0,0,0,0.2)'});
return false;
});
// For the file list
$('#extra-files .number').toggle(function() {
$('#file-list').show();
}, function() {
$('#file-list').hide();
});
$('#dropped-files #upload-button .delete').click(restartFiles);
// Append the localstorage the the uploaded files section
if(window.localStorage.length > 0) {
$('#uploaded-files').show();
for (var t = 0; t < window.localStorage.length; t++) {
var key = window.localStorage.key(t);
var value = window.localStorage[key];
// Append the list items
if(value != undefined || value != '') {
$('#uploaded-files').append(value);
}
}
} else {
$('#uploaded-files').hide();
}
});
PHP
// We're putting all our files in a directory.
$uploaddir = '../photos/';
// The posted data, for reference
$file = $_POST['value'];
$name = $_POST['name'];
$gpID = $_GET['gpID'];
// Get the mime
$getMime = explode('.', $name);
$mime = end($getMime);
// Separate out the data
$data = explode(',', $file);
// Encode it correctly
$encodedData = str_replace(' ','+',$data[1]);
$decodedData = base64_decode($encodedData);
// You can use the name given, or create a random name.
// We will create a random name!
$randomName = $gpID.'.'.$mime;
if(file_put_contents($uploaddir.$randomName, $decodedData)) {
$sql = "UPDATE zmods_galleriesphotos SET gpFile = '$randomName' WHERE gpID = '$gpID'";
$rows = $db->query($sql);
echo $randomName.":uploaded successfully";
}
else {
echo "Something went wrong. Check that the file isn't corrupted";
}
Check the upload_max_filesize in your php.ini file (although it should be large enough by default)
Check the post_max_size as well
If you're uploading multiple files, then also check max_file_uploads
The fact that your sql is failing makes me wonder if this is a mysql problem and not a php problem. What is the SQL error that occurs?

Stuck while Implementing complex jQuery Image Slider

I have stuck some where while modifying THIS slider.
Here Thumbnail & main display Image have one to one relationship i.e by clicking on 1 thumbnail, It shows a single Image & then it slides to the next thumbnail & displays its associated image & so on.
Now, I want to modify this slider in such a way that one thumbnail should be assiciated / linked with multiple Images i.e one thumbnail to many main display images relationship (one –to-many)
i.e by clicking on “Bedroom thumbnail” (As shown in attached image .. SCREENSHOT ) , It should only display & slide 5 (or n) number of Images related to this particular thumbnail, then in the same way if I am clicking on “Bathroom thumbnail” , It should display & slide 5 (or n) number of images related to this particular section & so on. So this is how I wanna modify the code from ONE-to-ONE [one thumbnail-to-one main display image] to ONE-to-MANY [one thumbnail-to- 5 or n number of images related to that particular thumbnail]
My Modified Thumbnail Section’s HTML code is same.
I have modified the Main Image section as shown ..
<div id="lofslidecontent45" class="lof-slidecontent" style="width:670px;height:236px;">
<div class="preload"><div></div></div>
<div class="lof-main-outer" style="width:670px; height:236px;">
<ul class="lof-main-wapper">
<li>
<ul class=”lof-main-subwapper”>
<li>
<img src="images/slider1.jpg" title="Newsflash 2" >
<div class="lof-main-item-desc">
<h3>Innovation</h3>
<h2>lorem ipsum is simply dummy text</h2>
</div>
</li>
<li>
..
</li>
</ul>
</li>
<li>
<ul class=”lof-main-subwapper”>
<li>
…
</li>
<li>
…
</li>
</ul>
</li>
</ul>
</div>
</div>
I am modifying the slider’s Script code, so far I have adder another wrappersub class & I am stuck while linking the group of images to one thumbnail i.e linking main image section’s ul with thumbnail’s li...
(function($) {
$.fn.lofJSidernews = function( settings ) {
return this.each(function() {
// get instance of the lofSiderNew.
new $.lofSidernews( this, settings );
});
}
$.lofSidernews = function( obj, settings ){
this.settings = {
direction : '',
mainItemSelector : 'li',
mainInnerItemSelector : 'li',
navInnerSelector : 'ul',
navSelector : 'li' ,
navigatorEvent : 'click',
subWrapperSelector :'.lof-main-subwrapper',
wapperSelector: '.lof-main-wapper',
interval : 4000,
innerinterval :20000,
auto : true, // whether to automatic play the slideshow
maxItemDisplay : 5,
startItem : 0,
navPosition : 'vertical',
navigatorHeight : 100,
navigatorWidth : 310,
duration : 600,
navItemsSelector : '.lof-navigator li',
navOuterSelector : '.lof-navigator-outer' ,
isPreloaded : true,
easing : 'easeInOutQuad'
}
$.extend( this.settings, settings ||{} );
this.nextNo = null;
this.previousNo = null;
this.maxWidth = this.settings.mainWidth || 600;
this.wrapper = $( obj ).find( this.settings.wapperSelector );
this.subSlides = this.wrapper.find( this.settings.mainItemSelector );
this.subwrapper = this.subslides.find(this.settings.subWrapperSelector)
this.slides = this.subwrapper.find(this.settings.mainInnerItemSelector)
if( !this.wrapper.length || !this.subslides.length ) return ;
if( !this.subwrapper.length || !this.slides.length ) return ;
if( this.settings.maxItemDisplay > this.slides.length ){
this.settings.maxItemDisplay = this.slides.length;
}
this.currentNo = isNaN(this.settings.startItem)
)||this.settings.startItem > this.slides.length?0:this.settings.startItem;
this.navigatorOuter = $( obj ).find( this.settings.navOuterSelector );
this.navigatorItems = $( obj ).find( this.settings.navItemsSelector );
this.navigatorInner = this.navigatorOuter.find( this.settings.navInnerSelector );
if( this.settings.navPosition == 'horizontal' ){
this.navigatorInner.width( this.slides.length * this.settings.navigatorWidth );
this.navigatorOuter.width( this.settings.maxItemDisplay * this.settings.navigatorWidth );
this.navigatorOuter.height( this.settings.navigatorHeight );
} else {
this.navigatorInner.height( this.slides.length * this.settings.navigatorHeight );
this.navigatorOuter.height( this.settings.maxItemDisplay * this.settings.navigatorHeight );
this.navigatorOuter.width( this.settings.navigatorWidth );
}
this.navigratorStep = this.__getPositionMode( this.settings.navPosition );
this.directionMode = this.__getDirectionMode();
if( this.settings.direction == 'opacity') {
this.subwrapper.addClass( 'lof-opacity' );
$(this.slides).css('opacity',0).eq(this.currentNo).css('opacity',1);
} else {
this.subwrapper.css
({'left':'-'+this.currentNo*this.maxSize+'px', 'width':( this.maxWidth ) * this.slides.length } );
}
if( this.settings.isPreloaded ) {
this.preLoadImage( this.onComplete );
} else {
this.onComplete();
}
}
$.lofSidernews.fn = $.lofSidernews.prototype;
$.lofSidernews.fn.extend = $.lofSidernews.extend = $.extend;
$.lofSidernews.fn.extend({
startUp:function( obj, subwrapper ) {
seft = this;
this.navigatorItems.each( function(index, item ){
$(item).click( function(){
seft.jumping( index, true );
seft.setNavActive( index, item );
} );
$(item).css( {'height': seft.settings.navigatorHeight, 'width': seft.settings.navigatorWidth} );
})
this.registerWheelHandler( this.navigatorOuter, this );
this.setNavActive(this.currentNo );
if( this.settings.buttons && typeof (this.settings.buttons) == "object" ){
this.registerButtonsControl( 'click', this.settings.buttons, this );
}
if( this.settings.auto )
this.play( this.settings.innerinterval,'next', true );
return this;
},
onComplete:function(){
setTimeout( function(){ $('.preload').fadeOut( 900 ); }, 400 ); this.startUp( );
},
preLoadImage:function( callback ){
var self = this;
var images = this.subwrapper.find( 'img' );
var count = 0;
images.each( function(index,image){
if( !image.complete ){
image.onload =function(){
count++;
if( count >= images.length ){
self.onComplete();
}
}
image.onerror =function(){
count++;
if( count >= images.length ){
self.onComplete();
}
}
}else {
count++;
if( count >= images.length ){
self.onComplete();
}
}
} );
},
navivationAnimate:function( currentIndex ) {
if (currentIndex <= this.settings.startItem
|| currentIndex - this.settings.startItem >= this.settings.maxItemDisplay-1) {
this.settings.startItem = currentIndex - this.settings.maxItemDisplay+2;
if (this.settings.startItem < 0) this.settings.startItem = 0;
if (this.settings.startItem >this.slides.length-this.settings.maxItemDisplay) {
this.settings.startItem = this.slides.length-this.settings.maxItemDisplay;
}
}
Any HELP would be appreciated.
Thank you
Maybe you could try adding a slide show inside of another slider that will support more content like the Anything Slider. I've used it on projects and had some luck with adding my own custom stuff in the slides.
try adding "var" to line 238, it becomes: var seft = this;

Categories

Resources