switchClass() swaps class after 3rd click - image

I got the following:
http://jsfiddle.net/GsL8Z/
I want to toggle the size of an image. After each toggle, I want to replace the scaled image with its instance in right size.
This actually works pretty well, but only the first time. After the third click, the wrong class gets allocated.
Any help would be greatly appreciated!
HTML
<div id="projekt_1" class="projekt">
<ul class="bilder">
<li><img class="imgKlein" src="images/mainworks_th.jpg" alt="Mainworks"/></li>
</ul>
</div>​
CSS
.imgGross{
height: 450px;
}
.imgKlein{
height: 215px;
}​
JS
var status = true,
obj = $('.projekt'),
projekte = $.makeArray(obj),
obj = $('.bilder'),
projekte_li = $.makeArray(obj),
obj = $('.projekt li img'),
projekte_li_img = $.makeArray(obj);
var images = new Array (2);
images[0] = $('<img class="imgKlein"/>').attr({src: 'images/mainworks_th.jpg'});
images[1] = $('<img class="imgGross"/>').attr({src:'images/mainworks_pre.jpg'});
$('#projekt_1').click(function() {
if (status == true) {
$("img", this).switchClass( "imgKlein", "imgGross", 1000, "easeInOutQuad" );
setTimeout(function(){
$(projekte_li[0]).html(images[1]);
}, 2000);
status = false;
}
else {
$("img", this).switchClass( "imgGross", "imgKlein", 1000, "easeInOutQuad" );
setTimeout(function(){
$(projekte_li[0]).html(images[0]);
}, 2000);
status = true;
}
return false;
});

Somehow the switchClass is having problems with you replacing the whole html for the img. As a matter of fact you can just change the src.
Also, you are better off using .toggle() in jQuery to handle things changing back and forward on each click.
By the way, also the setTimeout can give problems. .switchClass() has a complete handler that runs after the animation is complete and you should use that.
So, the solution could be:
$('#projekt_1').toggle(
function(e) {
$("img", this).switchClass("imgKlein", "imgGross", 1000, "easeInOutQuad",
function() {
$(this).attr({ src: 'images/mainworks_pre.jpg', alt: "Mainworks_pre" });
});
return false;
},
function (e) {
$("img", this).switchClass("imgGross", "imgKlein", 1000, "easeInOutQuad",
function(){
$(this).attr({ src: 'images/mainworks_th.jpg', alt: "Mainworks_TH" });
});
return false;
}
);
Fiddle: http://jsfiddle.net/GsL8Z/2/

i testet something with the example from jquery-ui and it works
the code is little bit shorter than yours:
$(function() {
$( "#projekt_1" ).click(function(){
$(".imgKlein").switchClass( "imgKlein", "imgGross", 1000, "easeInOutQuad", function()
{
$("img").attr("src", "http://www.spielwiki.de/images/e/e9/Kleines_M%C3%A4dchen%2C_zu_gro%C3%9Fer_Luftballon.png");
});
$(".imgGross").switchClass( "imgGross", "imgKlein", 1000, "easeInOutQuad", function()
{
$("img").attr("src", "http://images.all-free-download.com/images/graphiclarge/small_house_329.jpg");
});
return false;
});
});​
the link to the example: http://jsfiddle.net/DWrC6/24/

Related

Dropzone createThumbnailFromUrl() issue

I need to add pre-existing image files to dropzone by using Laravel 5.4. This is why I use createThumbnailFromUrl() function. But it does not generate images properly. Instead it shows them in blank way. I used that link (jsfiddle) for that purpose. I googled a lot, tried several ways, but it did not help:
Below is my code:
<script type="text/javascript" src='{{asset("js/dropzone/min/dropzone.min.js")}}'></script>
<script type="text/javascript">
Dropzone.options.addImages = {
paramName: "file", // The name that will be used to transfer the file
addRemoveLinks: true,
// The setting up of the dropzone
init:function() {
// Add server images
var myDropzone = this;
var existingFiles = [
{ name: "Filename 1.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 2.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 3.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 4.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' },
{ name: "Filename 5.pdf", size: 12345678,imageUrl:'http://img.tfd.com/wn/93/17E8B3-awful.png' }
];
for (i = 0; i < existingFiles.length; i++) {
// alert(existingFiles[i].imageUrl);
myDropzone.emit("addedfile",existingFiles[i]);
myDropzone.files.push(existingFiles[i]);
myDropzone.createThumbnailFromUrl(existingFiles[i], existingFiles[i].imageUrl, function() {
myDropzone.emit("complete", existingFiles[i]);
}, "anonymous");
}
},
};
</script>
Here is the result :( :
P.S: Any kind of help would be appreciated.
had the same issue with dropzone 5.3
this fixed it for me
let mockFile = { name: "Loaded File", dataURL: relURL };
dropzoneInst.files.push(mockFile);
dropzoneInst.emit("addedfile", mockFile);
dropzoneInst.createThumbnailFromUrl(mockFile,
dropzoneInst.options.thumbnailWidth,
dropzoneInst.options.thumbnailHeight,
dropzoneInst.options.thumbnailMethod, true, function (thumbnail)
{
dropzoneInst.emit('thumbnail', mockFile, thumbnail);
});
dropzoneInst.emit('complete', mockFile);
I am attaching for reference my solution, based on many previous answers, but mostly on Raphael Eckmayer. This is how it is done to make it work well with Django 3.0.5 and dropzone.js 5.7.0. Maybe it is not the best solution, but it works.
I am sending my current images from Django view using new template tag json_script that packs my list of files prepared in Django into JSON. Basically in my template I have this:
{{ images|json_script:"images" }}
Then I process this in my script. Here is entire script from my site, hope that will help someone.
EDIT:
I had an issue with this code that if I add new pictures to the dropzone together with the old one from database I got this form submitted twice. In first pass I get pictures from dropzone.js, but also all fields since I am copying them from the form. And then, on second pass, I am submitting form again but now without pictures. My view actually was handling this well and storing data, but when I started to write down how to handle removed pictures on form edit I had issue with this, so I decided to handle this differently. Please note that code is now changed and instead of submitting form twice I am sending entire form and pictures with dropzone, but after successmultiple I am just redirecting to other page. Everything is updated and stored then. So the change is in the successmultiple part.
<script type="text/javascript">
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Dropzone.autoDiscover = false;
var first_time = true;
var old_images = JSON.parse(document.getElementById('images').textContent)
var myDropzoneX = new Dropzone("div#mydropzone", {
autoProcessQueue: false,
url: "{% url 'site_report_edit' report_id=1 %}",
addRemoveLinks: true,
thumbnailWidth: 400,
thumbnailHeight: 400,
uploadMultiple: true,
parallelUploads: 12,
init: function() {
var myDropzone = this;
var addButton = document.getElementById("submit-btn");
if (old_images) {
console.log(old_images);
for (x in old_images) {
var mockFile = {
name: old_images[x].name,
size: old_images[x].size,
kind: 'image',
dataURL: old_images[x].urlich,
accepted: true
}
myDropzone.files.push(mockFile);
myDropzone.emit('addedfile', mockFile);
createThumbnail(mockFile);
console.log(old_images[x].name, old_images[x].urlich);
}
function createThumbnail(temp) {
myDropzone.createThumbnailFromUrl(temp,
myDropzone.options.thumbnailWidth,
myDropzone.options.thumbnailHeight,
myDropzone.options.thumbnailMethod, true, function (thumbnail) {
myDropzone.emit('thumbnail', temp, thumbnail);
myDropzone.emit("complete", temp);
});
}
myDropzone._updateMaxFilesReachedClass();
}
addButton.addEventListener("click", function (e) {
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
document.getElementById("dropzone-form").submit();
}
});
this.on("successmultiple", function (files, response) {
setTimeout(function (){
{#document.getElementById("dropzone-form").submit();#}
window.location.href = "/admin/report/{{ report_id }}";
}, 1000);
});
},
sending: function (file, xhr, formData) {
var formEl = document.getElementById("dropzone-form");
if (first_time) {
for (var i=0; i<formEl.elements.length; i++){
formData.append(formEl.elements[i].name, formEl.elements[i].value)
first_time = false;
}
}
formData.append('csrfmiddlewaretoken', getCookie('csrftoken'));
formData.append("image", file.name);
}
});
</script>
Please note that there are some comments and some writing to console.log, but you can obviously get rid of this.
I had the same problem. Use these files:
https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/dropzone.js
https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/dropzone.css
It worked for me.
I know it's a bit late, however I was facing the same issue. The problem I was having was a race condition where only the last thumbnail was loaded and the others were stuck before completing, because i changed before createThumbnailFromUrl was getting it's data. Putting the call inside function did the trick for me:
for (var i = 0; i < images.length; i++) {
var temp = { name: images[i], dataURL: images[i] };
myDropzone.files.push(temp);
myDropzone.emit("addedfile", temp);
createThumbnail(temp);
}
function createThumbnail(temp) {
myDropzone.createThumbnailFromUrl(temp,
myDropzone.options.thumbnailWidth,
myDropzone.options.thumbnailHeight,
myDropzone.options.thumbnailMethod, true, function (thumbnail) {
myDropzone.emit('thumbnail', temp, thumbnail);
myDropzone.emit("complete", temp);
});
}
My answer is inspired by BLitande's, which helped me getting it to kind of work in the first place.

lazy load doesnt work with hidden elements

this is my simple test code for lazy load
http://codepen.io/kevkev/pen/bVVGdE
it works so far .. but the thing is that hidden images in an onclick function for buttons etc. doesnt work!
(watch through my code and scroll to end and push the button)
you can see in the network feedback that it already had load the images.
i could figure out that the problem is "display:none"
.pop {
display:none;
z-index:99;
position:absolute;
width:100%;
height:auto;
background:inherit;
}
Because display: none; elements are unknown in position. And the lazyloader doesn't know, when and if you change this. Therefore it decides to eager load it. If you want a lazyloader that automatically detects this use https://github.com/aFarkas/lazysizes/.
As alternative I would recommend justlazy, because it's more lightweight and don't uses jQuery.
1. Define placeholder (similar to that what you have done):
<span data-src="path/to/image" data-alt="alt" data-title="title"
class="placeholder">
</span>
2. Initialize lazy loading after your button click:
$(document).ready(function () {
$("#art").click(function () {
$("#art_pop").fadeIn(300);
Justlazy.registerLazyLoadByClass("placeholder", {
// image will be loaded if it is 300 pixels
// below the lower display border
threshold: 300
});
});
// other code ..
});
thanks guys! but I also got a working solution on this:
http://codepen.io/kevkev/full/meebpQ/
$(document).ready(function () {
$("#art").click(function () {
$("#art_pop").fadeIn(300);
});
$(".pop > span, .pop").click(function () {
$(".pop").fadeOut(600);
});
});
;(function($) {
$.fn.unveil = function(threshold, callback) {
var $w = $(window),
th = threshold || 0,
retina = window.devicePixelRatio > 1,
attrib = retina? "data-src-retina" : "data-src",
images = this,
loaded;
this.one("unveil", function() {
var source = this.getAttribute(attrib);
source = source || this.getAttribute("data-src");
if (source) {
this.setAttribute("src", source);
if (typeof callback === "function") callback.call(this);
}
});
function unveil() {
var inview = images.filter(function() {
var $e = $(this);
if ($e.is(":hidden")) return;
var wt = $w.scrollTop(),
wb = wt + $w.height(),
et = $e.offset().top,
eb = et + $e.height();
return eb >= wt - th && et <= wb + th;
});
loaded = inview.trigger("unveil");
images = images.not(loaded);
}
$w.on("scroll.unveil resize.unveil lookup.unveil", unveil);
unveil();
return this;
};
})(window.jQuery || window.Zepto);
/* OWN JAVASCRIPT */
$(document).ready(function() {
$("img").unveil(200, function() {
$(this).load(function() {
this.style.opacity = 1;
});
});
});

Ckeditor Get Content From Iframe

I have a iframe and i'm trying to use Dialog to get data in Iframe and output to current html, but i don't know how to get Ckeditor Content from the Iframe.
I tried to using CKEDITOR.instances['editor'].getData(); but look like cannot get it.
This is my code:
<textarea class='editor' name='description' id='description'></textarea>
$( "#dialog_custom" ).dialog({
autoOpen: false,
modal: true,
height: 768,
width: 1024,
buttons: {
Add: function() {
var model = $('.dialog_custom').contents().find('#model').val();
var product_id = $('.dialog_custom').contents().find('#product_id').val();
var product_name = $('.dialog_custom').contents().find('#product_name').val();
var qty = $('.dialog_custom').contents().find('#qty').val();
var total = $('.dialog_custom').contents().find('#total').val();
var category = $('.dialog_custom').contents().find('#category').val();
if(qty=='') { qty = '0'; }
if(total=='') { total = '0.00'; }
if(model=='') {
alert('Please input the correct Model Number.');
} else {
$(".product").append(InsertTableGetFromIframe);
$('.delete_custom_row').click(function() {
if(confirm("Are you sure want to delete this data?")) {
$(this).parents('.custom_row').next('.parts_row').remove();
$(this).parents('.custom_row').remove();
}
});
$('.dialog_custom').contents().find('#model').val('');
$('.dialog_custom').contents().find('#product_id').val('');
$('.dialog_custom').contents().find('#product_name').val('');
$('.dialog_custom').contents().find('#qty').val('');
$('.dialog_custom').contents().find('#total').val('');
$('.dialog_custom').contents().find('#category').val('');
$(this).dialog("close");
i++;
}
},
Close: function() {
$(this).dialog("close");
}
}
});
$( "#open_custom" ).click(function() {
$( "#dialog_custom" ).dialog( "open" );
});
</script>
Finally, I found out the solution to get the content in the iframe, i used jquery to submit the form then POST the value on the field and get it by Jquery again.
It's the most simple way that i found, actually I think we have another way better to do it...

Passing "href" as data in jQuery UI tabs() through Ajax

I have some tabs (jQuery UI tabs) in the "index.php" of a page. This page not only shows content, but also retrieves the $_GET variable to show some other content below the tabs.
The problem is how to tell jQuery UI that the href (attr of the clicked ) is a value for the key "href" that has to send (GET) to the current index.php page, called in JS has window.location.pathname (I can't use PHP generated JavaScript).
The code is this, and i'm out of options for how to make things work.
jQuery('#front-tab').tabs({
spinner: "Loading...",
select: '#tab-one',
cache: true,
fx: { height: 'toggle', opacity: 'toggle' },
url: window.location.pathname,
ajaxOptions: {
type: 'get',
success: function(){alert('Sucess');},
error: function(){alert('I HAZ FAIL');};
},
dataType: 'html'
}
});
The HTML:
<div id="front-tab">
<ul>
<li><span>Home</span></li>
<li><span>Tab Content 1</span></li>
<li><span>Tab Content 2</span></li>
<li><span>Tab Content 3</span></li>
<li><span>Tab Content 4</span></li>
</ul>
<div id="tab-home">
content...
</div>
</div>
Yep, this gets me full of "I HAZ FAIL" every time I try to load other tabs. The first tab is inline HTML, but the rest is Ajax. url: window.location.pathname doesn't seems to work or point to the right direction. Well, I don't know if that does what I am looking for.
function initTabs(elementHref) {
jQuery('#front-tab').tabs({
spinner: "Loading...",
select: '#tab-one',
cache: true,
fx: { height: 'toggle', opacity: 'toggle' },
url: elementHref,
ajaxOptions: {
type: 'get',
success: function(){alert('Sucess');},
error: function(){alert('I HAZ FAIL');};
},
dataType: 'html'
}
});
}
jQuery('yourLink').on('click', function() {
initTabs(jQuery(this).attr('href'));
});
Well, after noting the inflexibility of jQuery UI Tabs I had to replicate the action on my own. Better yet, few lines of code compared to two plugins.
front_tab.click(function(e) {
// Content parent
tab_content = $('#tab-content');
// other variables
var tab_visible = tab_content.children('div.visible'),
span = $(this).children('span'),
span_value = span.html(),
value = $(this).attr('href'),
// This gets our target div (if exists)
target = tab_content.children(value);
// There is no anchor
e.preventDefault();
// Don't do nothing if we are animating or "ajaxing"
if (tab_content.children().is(':animated') || is_ajaxing) { return; };
// Put the "selected" style to the clicked tab
if (!$(this).hasClass('selected')) {
front_tab.removeClass('selected');
$(this).addClass('selected');
}
// If is target div, call it
if (target.length > 0) {
is_ajaxing = true;
span.html('Loading...');
tab_content.children().removeAttr('class');
tab_visible.slideUp('slow', 'swing', function(){
// Some timeout to slow down the animation
setTimeout(function() {
target.attr('class', 'visible').slideDown('slow');
if (value = '#tpopular') { update_postbox(); }
is_ajaxing = false;
span.html(span_value)
}, 400);
});
// So, the target div doesn't exists. We have to call it.
} else {
is_ajaxing = true;
span.html('Cargando...');
$.get(
window.location.pathname,
{ href : value },
function(data) {
tab_visible.slideUp('slow', 'swing', function(){
setTimeout(function() {
tab_content.children().removeAttr('class');
tab_content
.append(unescape(data))
.children(value)
.css('display', 'none')
.attr('class', 'visible')
.slideDown('slow');
if (value = '#tpopular') { update_postbox(); }
is_ajaxing = false;
span.html(span_value)
}, 800);
});
},
'html');
}
});
The next problem is to make a nice error warning, but that is the solution.

mouse enter mouse leave slidedown animation error

I have a piece of code for showing a picture that slides up from a div when the mouse enters the div, the code works exactly how i want except it bugs when the mouse hovers in and out too quickly and the animation doesn't have time to complete, I've already changed from mouseover and mouseout, to mouseenter and mouseleave and this hasn't seemed to help, any suggestions would be great
<script type="text/javascript">
document.observe("dom:loaded", function() {
var effectInExecution=null;
$('mid_about_us').observe('mouseenter', function() {
if(effectInExecution) effectInExecution.cancel();
effectInExecution=new Effect.SlideDown('about_us_mo',{style:'height:140px;', duration: 1.0 });
});
$('mid_about_us').observe('mouseleave', function() {
if(effectInExecution) effectInExecution.cancel();
effectInExecution=new Effect.SlideUp('about_us_mo',{style:'height:0px;', duration: 1.0 });
});
});
I wrote a Prototype class a while back to solve this problem, the issue can be fixed by supplying a scope parameter to the effect options. anyway here is the class i wrote:
var DivSlider = Class.create();
Object.extend(DivSlider, {
toggle: function(selector, element, options) {
element = $(element);
this.options = Object.extend({
duration: 0.5,
fps: 35,
scope: 'DivSlider',
forceOpen: false
}, options || {});
var toggle = element.visible();
if (toggle && this.options.forceOpen) {
//already open, leave.. still call callback
(this.options.after || Prototype.emptyFunction)
.bind(this, element)();
return;
}
var effects = new Array();
if (toggle) {
effects.push(new Effect.SlideUp(element, {
sync: true
}));
} else {
$$(selector).each(function(el) {
if ((element !== el) && el.visible()) {
effects.push(new Effect.SlideUp(el, {
sync: true
}));
}
});
effects.push(new Effect.SlideDown(element, {
sync: true
}));
}
new Effect.Parallel(effects, {
duration: this.options.duration,
fps: this.options.fps,
queue: {
position: 'end',
scope: this.options.scope
},
beforeStart: function() {
(this.options.before || Prototype.emptyFunction)
.bind(this, element)();
}.bind(this),
afterFinish: function() {
(this.options.after || Prototype.emptyFunction)
.bind(this, element)();
}.bind(this)
});
}
});
and to use it in your case you would simply use:
DivSlider.toggle('div.your_class', your_id);
in your enter/leave code, it can handle multiple div's of the same class also, allowing only one div per class to be open at any single time. If this does not fit your needs you can easily deconstruct the class to get the code you actually need.

Resources