Firefox drag and drop redirect stop JQUERY - javascript

I am using fabric.js library to create a drag and drop moodboard creator. Everything works perfect, except in Firefox when I drag and drop the image to the canvas. It adds the image, but redirects to the img url. After the redirect, When I click on the back btn it goes back to the previous page and the image is on the canvas.
I have been searching and reading for a few hours now, trying all kinds of things. It seems that something in my code is preventing either "e.stopPropagation();" or "e.preventDefault()" from functioning correctly. I just cant seem to find the gremlin.
Any help would be great. Thanks!
UPDATE: Added JSFiddle.
here is a jsfiddle with my code:
http://jsfiddle.net/bQxMu/
UPDATE 2:
Fixed the issue, here is the part that fixed it:
function handleDrop(e) {
// this / e.target is current target element.
/*
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
*/
e.stopPropagation(); // Stops some browsers from redirecting.
e.preventDefault(); // Stops some browsers from redirecting.
var img = document.querySelector('#images img.img_dragging');
console.log('event: ', e);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative
// to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
return false;
}
Thanks for all the help :)
window.onload=function(){
var canvas = new fabric.Canvas('canvas');
canvas.backgroundColor = '#ffffff';
function handleDragStart(e) {
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
this.classList.add('img_dragging');
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'copy';
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
this.classList.add('over');
}
function handleDragLeave(e) {
e.stopPropagation();
this.classList.remove('over'); // this / e.target is previous target element.
}
function handleDrop(e) {
// this / e.target is current target element.
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
var img = document.querySelector('#images img.img_dragging');
console.log('event: ', e);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative
// to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
return false;
}
function handleDragEnd(e) {
// this/e.target is the source node.
[].forEach.call(images, function (img) {
img.classList.remove('img_dragging');
});
}
var removeSelectedEl = document.getElementById('remove-selected');
removeSelectedEl.onclick = function() {
var activeObject = canvas.getActiveObject(),
activeGroup = canvas.getActiveGroup();
if (activeGroup) {
var objectsInGroup = activeGroup.getObjects();
canvas.discardActiveGroup();
objectsInGroup.forEach(function(object) {
canvas.remove(object);
});
}
else if (activeObject) {
canvas.remove(activeObject);
$("#imageControl").fadeOut('slow');
}
};
var sendBackwardsEl = document.getElementById('send-backwards');
sendBackwardsEl.onclick = function() {
var activeObject = canvas.getActiveObject();
if (activeObject) {
canvas.sendBackwards(activeObject);
}
};
var sendToBackEl = document.getElementById('send-to-back');
sendToBackEl.onclick = function() {
var activeObject = canvas.getActiveObject();
if (activeObject) {
canvas.sendToBack(activeObject);
}
};
var bringForwardEl = document.getElementById('bring-forward');
bringForwardEl.onclick = function() {
var activeObject = canvas.getActiveObject();
if (activeObject) {
canvas.bringForward(activeObject);
}
};
var bringToFrontEl = document.getElementById('bring-to-front');
bringToFrontEl.onclick = function() {
var activeObject = canvas.getActiveObject();
if (activeObject) {
canvas.bringToFront(activeObject);
}
};
document.getElementById('saveImg').onclick = function() {
if (!fabric.Canvas.supports('toDataURL')) {
alert('This browser doesn\'t provide means to serialize canvas to an image');
}
else {
canvas.deactivateAll().renderAll();
window.open(canvas.toDataURL('png'));
}
};
canvas.on('selection:cleared', function(options) {
var activeObject = canvas.getActiveObject();
if (activeObject === null) {
$("#imageControl").fadeOut('slow');
}
});
canvas.on('object:selected', function(options) {
var activeObject = canvas.getActiveObject();
if (options.target && activeObject !== null) {
$("#imageControl").show('slow');
}
});
canvas.on('selection:created', function(options) {
if (options.target) {
$("#imageControl").show('slow');
}
});
if (Modernizr.draganddrop) {
// Browser supports HTML5 DnD.
// Bind the event listeners for the image elements
var images = document.querySelectorAll('#images img');
[].forEach.call(images, function (img) {
img.addEventListener('dragstart', handleDragStart, false);
img.addEventListener('dragend', handleDragEnd, false);
});
// Bind the event listeners for the canvas
var canvasContainer = document.getElementById('canvas-container');
canvasContainer.addEventListener('dragenter', handleDragEnter, false);
canvasContainer.addEventListener('dragover', handleDragOver, false);
canvasContainer.addEventListener('dragleave', handleDragLeave, false);
canvasContainer.addEventListener('drop', handleDrop, false);
} else {
// Replace with a fallback to a library solution.
alert("This browser doesn't support the HTML5 Drag and Drop API.");
}
}
HTML:
<div id="images">
<img draggable="true" src="http://i.imgur.com/q9aLMza.png" width="70" height="90"></img>
</div>
<div id="canvas-container-controls">
<div id="imageControlWrapper">
<div id="imageControl">
<button class= "imgBtn" id="saveImg">Save Canvas</button>
<button class="imgBtn" id="remove-selected">Remove selected object/group</button>
<button id="send-backwards" class="imgBtn">Send backwards</button>
<button id="send-to-back" class="imgBtn">Send to back</button>
<button id="bring-forward" class="imgBtn">Bring forwards</button>
<button id="bring-to-front" class="imgBtn">Bring to front</button>
</div>
</div>
<div id="canvas-container">
<canvas id="canvas" width="400" height="400"></canvas>
</div>
</div>

Add an e.preventDefault() in handleDrop: http://jsfiddle.net/wN29y/
function handleDrop(e) {
// this / e.target is current target element.
e.preventDefault();
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
var img = document.querySelector('#images img.img_dragging');
console.log('event: ', e);
var newImage = new fabric.Image(img, {
width: img.width,
height: img.height,
// Set the center of the new object based on the event coordinates relative
// to the canvas container.
left: e.layerX,
top: e.layerY
});
canvas.add(newImage);
return false;
}

My understanding is that you should have e.stopPropagation in handleDragOver, otherwise the browser still accepts the event, and opens the image.
(Similar to my answer here: Why can't I get file dropping to work with jquery?)

Related

How to remove added template from canvas in fabricjs?

I need to remove added template from canvas when I insert a layout. I use following code to clear canvas but it does not work.
function clearCanvas() {
canvas.clear();
canvas.renderAll.bind(canvas);
$('#layer-list li').each(function(i,obj) {
if(!$(this).hasClass('disabled'))
$(this).remove();
});
}
Layout adding function as follows.
$(document).on('click','#layout-content .item', function(event) {
if($(this).attr('data-image')) {
var url = $(this).attr('data-image');
if(url != '') {
layoutMode = true;
clearCanvas();
loadLayout(url);
}
}
});
Loadlayout function
function loadTemplate(url) {
fabric.loadSVGFromURL(url, function(objects, options) {
var svg = fabric.util.groupSVGElements(objects,options);
svg.scaleToHeight(canvas.getHeight());
canvas.add(svg);
svg.center();
canvas.renderAll();
var bounds = svg.getObjects();
fabric.loadSVGFromURL(url, function(objects, options) {
var group = new fabric.Group(objects,options);
canvas.add(group);
group.scaleToHeight(canvas.getHeight());
canvas.renderAll();
var items = group._objects;
group._restoreObjectsState();
canvas.remove(group);
for(var i = 0; i < items.length; i++) {
var left = svg.getLeft() + bounds[i].getLeft()*svg.getScaleX();
var top = svg.getTop() + bounds[i].getTop()*svg.getScaleY();
items[i].set({
left:left,
top:top,
droppable:true,
selectable:false,
hasControls:false,
hasBorders:false,
layering:false
});
canvas.add(items[i]);
canvas.renderAll();
}
canvas.remove(svg);
makeOverlay(templateBase);//////////wrong
makeOverlay(templateText);
canvas.renderAll();
});
});
}
How to fix that issue?
There are no any problems with your function clearCanvas() and $(document).on('click','#layout-content .item', function(event). The problem is in your function loadTemplate(url).
makeOverlay(templateBase);
makeOverlay(templateText);
Above line in function loadTemplate(url) load previous base template as well. So remove those lines and try.

2 self-invoking javascript functions running

I have a container which contains a primary image and 2-3 thumbnails each. I wanted the user to be able to change the image by clicking on the thumbnail of its parent. Aside from that, I want the containers to be draggable/sortable so that users can be able to compare them easily.
This is why I made these 2 self invoking functions in my javascript file.
This one is to change the primary image into the image of the thumbnail.
$(document).ready(function(){
$('.thumb-img').on('click', function(){
var url = $(this).attr('src');
$(this).closest('.item-container').find('.primary-img').attr('src', url);
});
});
While this one is used to drag and drop the containers to interchange positions.
(function() {
"use strict";
var dragAndDropModule = function(draggableElements){
var elemYoureDragging = null
, dataString = 'text/html'
, elementDragged = null
, draggableElementArray = Array.prototype.slice.call(draggableElements) //Turn NodeList into array
, dragonDrop = {}; //Put all our methods in a lovely object
// Change the dataString type since IE doesn't support setData and getData correctly.
dragonDrop.changeDataStringForIe = (function () {
var userAgent = window.navigator.userAgent,
msie = userAgent.indexOf('MSIE '), //Detect IE
trident = userAgent.indexOf('Trident/'); //Detect IE 11
if (msie > 0 || trident > 0) {
dataString = 'Text';
return true;
} else {
return false;
}
})();
dragonDrop.bindDragAndDropAbilities = function(elem) {
elem.setAttribute('draggable', 'true');
elem.addEventListener('dragstart', dragonDrop.handleDragStartMove, false);
elem.addEventListener('dragenter', dragonDrop.handleDragEnter, false);
elem.addEventListener('dragover', dragonDrop.handleDragOver, false);
elem.addEventListener('dragleave', dragonDrop.handleDragLeave, false);
elem.addEventListener('drop', dragonDrop.handleDrop, false);
elem.addEventListener('dragend', dragonDrop.handleDragEnd, false);
};
dragonDrop.handleDragStartMove = function(e) {
var dragImg = document.createElement("img");
dragImg.src = "http://alexhays.com/i/long%20umbrella%20goerge%20bush.jpeg";
elementDragged = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData(dataString, this.innerHTML);
//e.dataTransfer.setDragImage(dragImg, 20, 50); //idk about a drag image
};
dragonDrop.handleDragEnter = function(e) {
if(elementDragged !== this) {
this.style.border = "2px dashed #3a3a3a";
}
};
dragonDrop.handleDragOver = function(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
};
dragonDrop.handleDragLeave = function(e) {
this.style.border = "2px solid transparent";
};
dragonDrop.handleDrop = function(e) {
if(elementDragged !== this) {
var data = e.dataTransfer.getData(dataString);
elementDragged.innerHTML = this.innerHTML;
this.innerHTML = e.dataTransfer.getData(dataString);
}
this.style.border = "2px solid transparent";
e.stopPropagation();
return false;
};
dragonDrop.handleDragEnd = function(e) {
this.style.border = "2px solid transparent";
};
// Actiavte Drag and Dropping on whatever element
draggableElementArray.forEach(dragonDrop.bindDragAndDropAbilities);
};
var allDraggableElements = document.querySelectorAll('.draggable-droppable');
dragAndDropModule(allDraggableElements);
})();
The two functions work but when I drag the container and change its position, the first function doesn't work anymore.
It's probably because you drag it and recreate the element node.
you can use Event to solve the problem.
$(document).ready(function(){
// It delegate thumb-img event to body, so whatever you recreate thumb-img,is all right
$('body').on('click', '.thumb-img', function(){
var url = $(this).attr('src');
$(this).closest('.item-container').find('.primary-img').attr('src', url);
});
});

Javascript jQuery plugin - multiple instances, external control

I am trying to wrap a canvas function in a jquery plugin, so that it can be invoked via multiple instances.
I want to be able to loop through found items and call the plugin like this
http://jsfiddle.net/M99EY/69/
HTML...
<div id="select1" class="foo" data-init="multi">A</div>
<div id="select2" class="foo" data-init="multi">B</div>
<div id="select3" class="foo" data-init="multi">C</div>
<div id="select4" class="foo" data-init="multi">D</div>
JS
...
var complicatedObj = {
init: function(element){
this.el = element;
console.log("init method", this.el);
//start a complicated process
//like rendering a canvas applicaation
this.bindEvent();
this.addRandom(this.el);
},
addRandom: function(el){
$(el).text(Math.random());
},
reInit: function(){
console.log("re-initialize method");
},
bindEvent: function(){
$(this.el).click(function() {
console.log("Letter.", $(this).text());
});
}
}
//An application with complicated functions -- initialize, re-initialize
$.multiInstance = {
id: 'multiInstance',
version: '1.0',
defaults: { // default settings
foo: 'bar'
}
};
(function ($) {
//Attach this new method to jQuery
$.fn.extend({
multiInstance: function (params) {
//Merge default and user parameters
var otherGeneralVars = 'example';
return this.each(function () {
var $this = $(this), opts = $.extend({},$.multiInstance.defaults, params);
switch (params) {
case "init":
complicatedObj.init($this);
break;
case "reInit":
complicatedObj.addRandom($this);
break;
}
//console.log("$this", $this);
console.log("params", params);
//$this.text(opts.foo);
});
}
})
})(jQuery);
/*
$("#select1").multiInstance();
$("#select2").multiInstance({foo:"foobar"})
$("#select3").multiInstance("init");*/
$('[data-init="multi"]').each(function( index ) {
//console.log( index + ": " + $( this ).text());
$(this).multiInstance("init");
});
setTimeout(function(){ $('#select3').multiInstance("reInit"); }, 2000);
but I need to be able to invoke different methods, pass arguments to these methods -- and then when a change has occurred - provide a callback to catch changes to the instance
Is this the correct way of building the plugin... I want to be able to create multiple instances of the app -- but also control it externally - and also pull values out of it for external results.
This is the application I am trying to wrap into its own jquery plugin.
https://jsfiddle.net/7a4738jo/10/
css..
body {
background-color: #CCCCCC;
margin: 0;
padding: 0;
overflow: hidden;
}
canvas{
background: grey;
}
html..
<script type="text/javascript" src="https://code.createjs.com/easeljs-0.6.0.min.js"></script>
<canvas id='canvas1' data-init="canvas360" width="465" height="465"></canvas>
<canvas id='canvas2' data-init="canvas360" width="465" height="465"></canvas>
js...
var stage;
function init(element) {
var canvas = $(element)[0];
if (!canvas || !canvas.getContext) return;
stage = new createjs.Stage(canvas);
stage.enableMouseOver(true);
stage.mouseMoveOutside = true;
createjs.Touch.enable(stage);
var imgList = ["http://jsrun.it/assets/N/b/D/X/NbDXj.jpg",
"http://jsrun.it/assets/f/K/7/y/fK7yE.jpg",
"http://jsrun.it/assets/j/U/q/d/jUqdG.jpg",
"http://jsrun.it/assets/q/o/4/j/qo4jP.jpg",
"http://jsrun.it/assets/i/Q/e/1/iQe1f.jpg",
"http://jsrun.it/assets/5/k/y/R/5kyRi.jpg",
"http://jsrun.it/assets/x/T/I/h/xTIhA.jpg",
"http://jsrun.it/assets/4/X/G/F/4XGFt.jpg",
"http://jsrun.it/assets/6/7/n/r/67nrO.jpg",
"http://jsrun.it/assets/k/i/r/8/kir8T.jpg",
"http://jsrun.it/assets/2/3/F/q/23Fqt.jpg",
"http://jsrun.it/assets/c/l/d/5/cld59.jpg",
"http://jsrun.it/assets/e/J/O/f/eJOf1.jpg",
"http://jsrun.it/assets/o/j/Z/x/ojZx4.jpg",
"http://jsrun.it/assets/w/K/2/m/wK2m3.jpg",
"http://jsrun.it/assets/w/K/2/m/wK2m3.jpg",
"http://jsrun.it/assets/4/b/g/V/4bgVf.jpg",
"http://jsrun.it/assets/4/m/1/8/4m18z.jpg",
"http://jsrun.it/assets/4/w/b/F/4wbFX.jpg",
"http://jsrun.it/assets/4/k/T/G/4kTGQ.jpg",
"http://jsrun.it/assets/s/n/C/r/snCrr.jpg",
"http://jsrun.it/assets/7/f/H/u/7fHuI.jpg",
"http://jsrun.it/assets/v/S/d/F/vSdFm.jpg",
"http://jsrun.it/assets/m/g/c/S/mgcSp.jpg",
"http://jsrun.it/assets/t/L/t/P/tLtPF.jpg",
"http://jsrun.it/assets/j/7/e/H/j7eHx.jpg",
"http://jsrun.it/assets/m/o/8/I/mo8Ij.jpg",
"http://jsrun.it/assets/n/P/7/h/nP7ht.jpg",
"http://jsrun.it/assets/z/f/K/S/zfKSP.jpg",
"http://jsrun.it/assets/2/3/4/U/234U6.jpg",
"http://jsrun.it/assets/d/Z/y/m/dZymk.jpg"];
var images = [], loaded = 0, currentFrame = 0, totalFrames = imgList.length;
var rotate360Interval, start_x;
var bg = new createjs.Shape();
stage.addChild(bg);
var bmp = new createjs.Bitmap();
stage.addChild(bmp);
var myTxt = new createjs.Text("HTC One", '24px Ubuntu', "#ffffff");
myTxt.x = myTxt.y =20;
myTxt.alpha = 0.08;
stage.addChild(myTxt);
function load360Image() {
var img = new Image();
img.src = imgList[loaded];
img.onload = img360Loaded;
images[loaded] = img;
}
function img360Loaded(event) {
loaded++;
bg.graphics.clear()
bg.graphics.beginFill("#222").drawRect(0,0,stage.canvas.width * loaded/totalFrames, stage.canvas.height);
bg.graphics.endFill();
if(loaded==totalFrames) start360();
else load360Image();
}
function start360() {
document.body.style.cursor='none';
// 360 icon
var iconImage = new Image();
iconImage.src = "http://jsrun.it/assets/y/n/D/c/ynDcT.png";
iconImage.onload = iconLoaded;
// update-draw
update360(0);
// first rotation
rotate360Interval = setInterval(function(){ if(currentFrame===totalFrames-1) { clearInterval(rotate360Interval); addNavigation(); } update360(1); }, 25);
}
function iconLoaded(event) {
var iconBmp = new createjs.Bitmap();
iconBmp.image = event.target;
iconBmp.x = 20;
iconBmp.y = canvas.height - iconBmp.image.height - 20;
stage.addChild(iconBmp);
}
function update360(dir) {
currentFrame+=dir;
if(currentFrame<0) currentFrame = totalFrames-1;
else if(currentFrame>totalFrames-1) currentFrame = 0;
bmp.image = images[currentFrame];
}
//-------------------------------
function addNavigation() {
stage.onMouseOver = mouseOver;
stage.onMouseDown = mousePressed;
document.body.style.cursor='auto';
}
function mouseOver(event) {
document.body.style.cursor='pointer';
}
function mousePressed(event) {
start_x = event.rawX;
stage.onMouseMove = mouseMoved;
stage.onMouseUp = mouseUp;
document.body.style.cursor='w-resize';
}
function mouseMoved(event) {
var dx = event.rawX - start_x;
var abs_dx = Math.abs(dx);
if(abs_dx>5) {
update360(dx/abs_dx);
start_x = event.rawX;
}
}
function mouseUp(event) {
stage.onMouseMove = null;
stage.onMouseUp = null;
document.body.style.cursor='pointer';
}
function handleTick() {
stage.update();
}
document.body.style.cursor='progress';
load360Image();
// TICKER
createjs.Ticker.addEventListener("tick", handleTick);
createjs.Ticker.setFPS(60);
createjs.Ticker.useRAF = true;
}
// Init
$(document).ready(function() {
//create multiple instances of canvas
$('[data-init="canvas360"]').each(function(index) {
init(this);
});
});

What part of jquery code is responsible for jump to next image?

I'm working to adapt malihu Sideways gallery and little messed up with jquery code.
I'm trying to change functionality of (clicking on background image for next image load) to (clicking on button for next image load)
I know that it sound simple but it isn't.
I can't solve what part of the code is responsible for this function
so I can just change the selector.
Here is the code:
$( function() {
// init Isotope
var $container = $('.isotope').isotope({
itemSelector: '.element-item',
layoutMode: 'fitRows'
});
// filter functions
var filterFns = {
// show if number is greater than 50
numberGreaterThan50: function() {
var number = $(this).find('.number').text();
return parseInt( number, 10 ) > 50;
},
// show if name ends with -ium
ium: function() {
var name = $(this).find('.name').text();
return name.match( /ium$/ );
}
};
// bind filter button click
$('#filters').on( 'click', 'button', function() {
var filterValue = $( this ).attr('data-filter');
// use filterFn if matches value
filterValue = filterFns[ filterValue ] || filterValue;
$container.isotope({ filter: filterValue });
});
// change is-checked class on buttons
$('.button-group').each( function( i, buttonGroup ) {
var $buttonGroup = $( buttonGroup );
$buttonGroup.on( 'click', 'button', function() {
$buttonGroup.find('.is-checked').removeClass('is-checked');
$( this ).addClass('is-checked');
});
});
});
//set default view mode
$defaultViewMode="full"; //full (fullscreen background), fit (fit to window), original (no scale)
//cache vars
$bg=$("#bg");
$bgimg=$("#bg #bgimg");
$preloader=$("#preloader");
$outer_container=$("#outer_container");
$outer_container_a=$("#outer_container a.thumb_link");
$toolbar=$("#toolbar");
$nextimage_tip=$("#nextimage_tip");
$(window).load(function() {
$toolbar.data("imageViewMode",$defaultViewMode); //default view mode
ImageViewMode($toolbar.data("imageViewMode"));
//cache vars
$customScrollBox=$("#customScrollBox");
$customScrollBox_container=$("#customScrollBox .container");
$customScrollBox.height($customScrollBox_container.height());
//resize browser window functions
$(window).resize(function() {
FullScreenBackground("#bgimg"); //scale bg image
});
LargeImageLoad($bgimg);
});
//loading bg image
$bgimg.load(function() {
LargeImageLoad($(this));
});
function LargeImageLoad($this){
$preloader.fadeOut("fast"); //hide preloader
$this.removeAttr("width").removeAttr("height").css({ width: "", height: "" }); //lose all previous dimensions in order to rescale new image data
$bg.data("originalImageWidth",$this.width()).data("originalImageHeight",$this.height());
if($bg.data("newTitle")){
$this.attr("title",$bg.data("newTitle")); //set new image title attribute
}
FullScreenBackground($this); //scale new image
$bg.data("nextImage",$($outer_container.data("selectedThumb")).next().attr("href")); //get and store next image
if(typeof itemIndex!="undefined"){
if(itemIndex==lastItemIndex){ //check if it is the last image
$bg.data("lastImageReached","Y");
$bg.data("nextImage",$outer_container_a.first().attr("href")); //get and store next image
} else {
$bg.data("lastImageReached","N");
}
} else {
$bg.data("lastImageReached","N");
}
$this.fadeIn("slow"); //fadein background image
if($bg.data("nextImage") || $bg.data("lastImageReached")=="Y"){ //don't close thumbs pane on 1st load
SlidePanels("open"); //close the left pane
}
NextImageTip();
}
$bgimg.click(
function(){
SlidePanels("close").toggle();
});
$bgimg.click(
function(){
SlidePanels("open").toggle();
});
$("#arrow_indicator").click(
function(){ //click
SlidePanels("open");
}
);
$("#arrow_next").click(
function(){
//Code for next image will go here
}
);
//Clicking on thumbnail changes the background image
$outer_container_a.click(function(event){
event.preventDefault();
var $this=this;
$bgimg.css("display","none");
$preloader.fadeIn("fast"); //show preloader
//style clicked thumbnail
$outer_container_a.each(function() {
$(this).children(".selected").css("display","none");
});
$(this).children(".selected").css("display","block");
//get and store next image and selected thumb
$outer_container.data("selectedThumb",$this);
$bg.data("nextImage",$(this).next().attr("href"));
$bg.data("newTitle",$(this).children("img").attr("title")); //get and store new image title attribute
itemIndex=getIndex($this); //get clicked item index
lastItemIndex=($outer_container_a.length)-1; //get last item index
$bgimg.attr("src", "").attr("src", $this); //switch image
});
//clicking on large image loads the next one
$("#arrow_next").click(function(event){
var $this=$(this);
if($bg.data("nextImage")){ //if next image data is stored
$this.css("display","none");
$preloader.fadeIn("fast"); //show preloader
$($outer_container.data("selectedThumb")).children(".selected").css("display","none"); //deselect thumb
if($bg.data("lastImageReached")!="Y"){
$($outer_container.data("selectedThumb")).next().children(".selected").css("display","none"); //select new thumb
} else {
$outer_container_a.first().children(".selected").css("display","none"); //select new thumb - first
}
//store new selected thumb
var selThumb=$outer_container.data("selectedThumb");
if($bg.data("lastImageReached")!="Y"){
$outer_container.data("selectedThumb",$(selThumb).next());
} else {
$outer_container.data("selectedThumb",$outer_container_a.first());
}
$bg.data("newTitle",$($outer_container.data("selectedThumb")).children("img").attr("title")); //get and store new image title attribute
if($bg.data("lastImageReached")!="Y"){
itemIndex++;
} else {
itemIndex=0;
}
$this.attr("src", "").attr("src", $bg.data("nextImage")); //switch image
}
});
//function to get element index (IE!)
function getIndex(theItem){
for ( var i = 0, length = $outer_container_a.length; i < length; i++ ) {
if ( $outer_container_a[i] === theItem ) {
return i;
}
}
}
//toolbar (image view mode button) hover
$toolbar.hover(
function(){ //mouse over
$(this).stop().fadeTo("fast",1);
},
function(){ //mouse out
$(this).stop().fadeTo("fast",0.8);
}
);
$toolbar.stop().fadeTo("fast",0.8); //set its original state
//Clicking on toolbar changes the image view mode
$toolbar.click(function(event){
if($toolbar.data("imageViewMode")=="full"){
ImageViewMode("fit");
} else if($toolbar.data("imageViewMode")=="fit") {
ImageViewMode("original");
} else if($toolbar.data("imageViewMode")=="original"){
ImageViewMode("full");
}
});
//next image balloon tip
function NextImageTip(){
if($bg.data("nextImage")){ //check if this is the first image
$nextimage_tip.stop().css("right",20).fadeIn("fast").fadeOut(2000,"easeInExpo",function(){$nextimage_tip.css("right",$(window).width());});
}
}
//slide in/out left pane function
function SlidePanels(action){
var speed=400;
var easing="easeInBack";
if(action=="open"){
$("#arrow_indicator").fadeTo("fast",0);
$outer_container.stop().animate({left: 0}, speed,easing);
$bg.stop().animate({left: 585}, speed,easing);
} else {
$outer_container.stop().animate({left: -710}, speed,easing);
$bg.stop().animate({left: 0}, speed,easing,function(){$("#arrow_indicator").fadeTo("fast",1);});
}
}
//Image scale function
function FullScreenBackground(theItem){
var winWidth=$(window).width();
var winHeight=$(window).height();
var imageWidth=$(theItem).width();
var imageHeight=$(theItem).height();
if($toolbar.data("imageViewMode")!="original"){ //scale
$(theItem).removeClass("with_border").removeClass("with_shadow"); //remove extra styles of orininal view mode
var picHeight = imageHeight / imageWidth;
var picWidth = imageWidth / imageHeight;
if($toolbar.data("imageViewMode")!="fit"){ //image view mode: full
if ((winHeight / winWidth) < picHeight) {
$(theItem).css("width",winWidth).css("height",picHeight*winWidth);
} else {
$(theItem).css("height",winHeight).css("width",picWidth*winHeight);
};
} else { //image view mode: fit
if ((winHeight / winWidth) > picHeight) {
$(theItem).css("width",winWidth).css("height",picHeight*winWidth);
} else {
$(theItem).css("height",winHeight).css("width",picWidth*winHeight);
};
}
//center it
$(theItem).css("margin-left",((winWidth - $(theItem).width())/2)).css("margin-top",((winHeight - $(theItem).height())/2));
} else { //no scale
//add extra styles for orininal view mode
$(theItem).addClass("with_border").addClass("with_shadow");
//set original dimensions
$(theItem).css("width",$bg.data("originalImageWidth")).css("height",$bg.data("originalImageHeight"));
//center it
$(theItem).css("margin-left",((winWidth-$(theItem).outerWidth())/2)).css("margin-top",((winHeight-$(theItem).outerHeight())/2));
}
}
//image view mode function - full or fit
function ImageViewMode(theMode){
$toolbar.data("imageViewMode", theMode); //store new mode
FullScreenBackground($bgimg); //scale bg image
//re-style button
if(theMode=="full"){
$toolbar.html("<span class='lightgrey'>CATEGORY ›</span> LOGO");
} else if(theMode=="fit") {
$toolbar.html("<span class='lightgrey'>CATEGORY ›</span> APP DESIGN");
} else if(theMode=="fit") { {
$toolbar.html("<span class='lightgrey'>CATEGORY ›</span> WEB DESIGN");
}
} else {
$toolbar.html("<span class='lightgrey'>CATEGORY ›</span> 3D");
}
}
//preload script images
var images=["ajax-loader_dark.gif","round_custom_scrollbar_bg_over.png"];
$.each(images, function(i) {
images[i] = new Image();
images[i].src = this;
});
Its going to be at:
$outer_container_a.click(function(event){
You can change this to:
$(".CLASSNAME").click(function(event){
Seeing the source and how it actually works would help too.

HTML5 Drag and Drop only images

What i'm trying to do is : if all the dragged files was images drop them, but if there was other file exstensions don't drop them, but drop the images only.
Here's my try :
HTML :
<div id="dropzone"></div>
Javascript :
var dropzone = document.getElementById("dropzone");
dropzone.ondrop = function (e) {
e.preventDefault();
e.stopPropagation();
var files = e.dataTransfer.files;
for(x = 0; x < files.length; x = x + 1){
if(files[x].type.split("/")[0] == 'image') {
console.log(files[x].name + "is image");
}else {
console.log(files[x].name + "is not image");
}
}
}
i need to loop through the files that i dragged and if the file was image do something otherwise do something else, for example
file.jpeg is image
file.txt is not image
But using my code if i dragged other file extension with the image it's not dropping the image, it's skipping both files.
The point is : Dropping only images.
You could use the FileReader and test the file type for an image like this:
// don't try to process non-images
var imageType = /image.*/;
if (file.type.match(imageType)) {
// it's an image, process it
}
Here's example code and a Demo:
// dropzone event handlers
var dropzone;
dropzone = document.getElementById("dropzone");
dropzone.addEventListener("dragenter", dragenter, false);
dropzone.addEventListener("dragover", dragover, false);
dropzone.addEventListener("drop", drop, false);
//
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
}
//
function dragover(e) {
e.stopPropagation();
e.preventDefault();
}
//
function drop(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.dataTransfer;
var files = dt.files;
handleFiles(files);
}
//
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
// get the next file that the user selected
var file = files[i];
var imageType = /image.*/;
// don't try to process non-images
if (!file.type.match(imageType)) {
continue;
}
// a seed img element for the FileReader
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
// get an image file from the user
// this uses drag/drop, but you could substitute file-browsing
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.onload = function() {
// draw the aImg onto the canvas
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = aImg.width;
canvas.height = aImg.height;
ctx.drawImage(aImg, 0, 0);
// make the jpeg image
var newImg = new Image();
newImg.onload = function() {
newImg.id = "newest";
document.body.appendChild(newImg);
}
newImg.src = canvas.toDataURL('image/jpeg');
}
// e.target.result is a dataURL for the image
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
} // end for
} // end handleFiles
body {
background-color: ivory;
}
canvas {
border: 1px solid red;
}
#dropzone {
border: 1px solid blue;
width: 300px;
height: 300px;
}
<h4>Drag file(s) from desktop to blue dropzone.<br>Only image files will be processed.</h4>
<div id="dropzone"></div>
<div id="preview"></div>

Categories

Resources