lazy load doesnt work with hidden elements - image

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;
});
});
});

Related

JQuery Terminal typing animation not displaying special HTML characters or class styles until after animation completes

I'm using code from the JQuery Terminal examples to emulate typed animation in a console window. I can get the animation to work as intended, but during the course of the animation special HTML characters do not display until after the animation completes. For example, while the animation is running, the console renders '\' instead of ''
This problem also applies to styles assigned to the class of any div that's being animated. The styles do not show up until after the animation is complete.
Below is the code used to animate (adapted from the JQuery Terminal examples page):
var anim = false;
function typed(finish_typing) {
return function(term, message, delay, finished, classname) {
anim = true;
var prompt = term.get_prompt();
var c = 0;
if (message.length > 0) {
term.set_prompt('');
var interval = setInterval(function() {
term.insert(message[c++]);
if (c == message.length) {
clearInterval(interval);
// execute in next interval
setTimeout(function() {
// swap command with prompt
finish_typing(term, message, prompt, classname);
anim = false
finish && finish();
}, delay);
}
}, delay);
}
};
}
var typed_message = typed(function(term, message, prompt, classname) {
if (typeof classname === "undefined") { classname = "default"; }
term.set_command('');
term.echo(message, {
finalize: function(div) { div.addClass(classname); }});
term.set_prompt(prompt);
});
And an example of how it's being called:
E.match(/^\s*ping\s*$/i)?
typed_message(N, "PONG", 10, function(){finished = true;}, "pong"):
In this case, styles applied to the "pong" class that's assigned to the div output by typed_message do not display until after the text is finished typing.
Is there a way to go about having the styles or special characters display while the animation is running?
Slightly modified typed animation using set_prompt instead of insert, also $.terminal.substring and length (that last one need to go to $.terminal.length).
var anim = false;
function typed(finish_typing) {
return function(term, message, delay, finish) {
anim = true;
var prompt = term.get_prompt();
var c = 0;
if (message.length > 0) {
term.set_prompt('');
var new_prompt = '';
var interval = setInterval(function() {
// handle html entities like &
var chr = $.terminal.substring(message, c, c+1);
new_prompt += chr;
term.set_prompt(new_prompt);
c++;
if (c == length(message)) {
clearInterval(interval);
// execute in next interval
setTimeout(function() {
// swap command with prompt
finish_typing(term, message, prompt);
anim = false
finish && finish();
}, delay);
}
}, delay);
}
};
}
function length(string) {
return $('<span>' + $.terminal.strip(string) + '</span>').text().length;
}
var typed_message = typed(function(term, message, prompt) {
term.set_command('');
term.echo(message);
term.set_prompt(prompt);
});
$('body').terminal(function(command, term) {
typed_message(term, '[[;#fff;;class_name]hello]', 400);
});
body {
min-height: 100vh;
margin: 0;
}
.class_name {
text-decoration: underline;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.terminal/1.8.0/js/jquery.terminal.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.terminal/1.8.0/css/jquery.terminal.min.css" rel="stylesheet"/>
The example on the site was updated accordingly.

Slideshow using Prototype and Scriptaculous

I wrote my first scriptaculous script to create a slideshow between some div element :
var SlideShow = Class.create({
initialize:function(element, delayStart){
this.element = element;
this.delayStart = delayStart;
this.slides = this.element.childElements();
this.numberOfSlides = this.slides.size();
this.numberActiveSlide = 1;
this.start_slideshow();
},
start_slideshow: function()
{
this.switch_slides.delay(this.delayStart);
},
switch_slides: function()
{
this.slides[this.numberActiveSlide].fade();
if (this.numberActiveSlide == this.numberOfSlides) { this.numberActiveSlide = 1; } else { this.numberActiveSlide = this.numberActiveSlide + 1; }
Effect.Appear.delay(this.slides[this.numberActiveSlide], 850);
this.switch_slides.delay(this.delay + 850);
}
});
document.observe("dom:loaded", function(){
var slideshows = $$('div.slideshow');
slideshows.each(
function(slideshow) {
s = new SlideShow(slideshow, 2);
});
});
But I always get this error and It's been hours I can't figure it out where my problem is!
Undefined is not an object (evaluating this.slides[this.numberActiveSlide]);
Thanks you !
Nick
99% sure it's a context issue. Make sure you bind your function calls so that this is retained throughout your code.
Debug what this is in switch_slides: it should be the same thing as this in start_slideshow. If it's not, bind your call to switch_slides to your instance:
start_slideshow: function()
{
this.switch_slides.bind(this).delay(this.delayStart);
},
You'll probably have to do the same in switch_slides where it calls itself.

Add checkbox to the ckeditor toolbar to addClass/removeClass in img elements

I want to write a ckeditor plugin that adds a checkbox to the toolbar.
When an img element is selected, the checkbox should reflect whether the image has a certain class or not.
When something else than an image is selected, the checkbox should be
disabled, or maybe invisible.
When I check or uncheck the checkbox, the class should be added/removed to/from the img.
In other words, I want to add something else than a button to the toolbar (those that are added with editor.ui.addButton), and that something should be a checkbox.
How do I do that?
I managed to do it anyway, using editor.ui.add and editor.ui.addHandler. Here is a screenshot:
plugin.js:
CKEDITOR.plugins.add('add_zoomable_to_image',
{
init: function( editor )
{
var disabled_span_color = "#cccccc";
var enabled_span_color = "#000000";
var cb;
var span;
var html =
"<div style='height: 25px; display: inline-block'>" +
"<div style='margin: 5px'><input class='add_zoomable_cb' type='checkbox' disabled='disabled'>" +
"<span class='add_zoomable_span' style='color: " + disabled_span_color + "'> Add zoomable to image</span>" +
"</div>" +
"</div>";
editor.ui.add('add_zoomable_to_image', "zoomable_button", {});
editor.ui.addHandler("zoomable_button",
{
create: function ()
{
return {
render: function (editor, output)
{
output.push(html);
return {};
}
};
}
});
editor.on("selectionChange", function()
{
var sel = editor.getSelection();
var ranges = sel.getRanges();
if (ranges.length == 1)
{
var el = sel.getStartElement();
if (el.is('img'))
{
enable_input();
if (el.hasClass('zoomable'))
check_cb();
else
uncheck_cb();
}
else
disable_input();
}
else
disable_input();
});
editor.on("instanceReady", function ()
{
cb = $('.add_zoomable_cb');
span = $('.add_zoomable_span');
cb.change(function()
{
var element = editor.getSelection().getStartElement();
if (cb.is(':checked'))
element.addClass('zoomable');
else
element.removeClass('zoomable');
});
});
function enable_input()
{
cb.removeAttr('disabled');
span.css('color', enabled_span_color);
}
function disable_input()
{
uncheck_cb();
cb.attr('disabled', 'disabled');
span.css('color', disabled_span_color);
}
function check_cb()
{
cb.attr('checked', 'checked');
}
function uncheck_cb()
{
cb.removeAttr('checked');
}
}
});
CKEditor doesn't include the option to add a checkbox to the toolbar, so your first step is to look at their code and extend it to add the checkbox.
Then look at how other buttons work to modify the content and detect when the selection in the editor changes to reflect its new state, and apply those ideas to your checkbox.

switchClass() swaps class after 3rd click

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/

hidding elements in a layout page mvc3

ok so im having a hard time hiding some layout sections (divs in my layout page and im using mvc3).
I have this js fragment which is basically the main logic:
$('.contentExpand').bind('click', function () {
$.cookie('right_container_visible', "false");
});
//Cookies Functions========================================================
//Cookie for showing the right container
if ($.cookie('right_container_visible') === 'false') {
if ($('#RightContainer:visible')) {
$('#RightContainer').hide();
}
$.cookie('right_container_visible', null);
} else {
if ($('#RightContainer:hidden')) {
$('#RightContainer').show();
}
}
as you can see, im hidding the container whenever i click into some links that have a specific css. This seems to work fine for simple tests. But when i start testing it like
.contentExpand click --> detail button click --> .contentExpand click --> [here unexpected issue: the line $.cookie('right_container_visible', null); is read but it doesnt set the vaule to null as if its ignoring it]
Im trying to understand whats the right logic to implement this. Anyone knows how i can solve this?
The simpliest solution is to create variable outside delegate of bind.
For example:
var rightContVisibility = $.cookie('right_container_visible');
$('.contentExpand').bind('click', function () {
$.cookie('right_container_visible', "false");
rightContVisibility = "false";
});
if (rightContVisibility === 'false') {
...
}
The best thing that worked for me was to create an event that can catch the resize of an element. I got this from another post but I dont remember which one. Anyway here is the code for the event:
//Event to catch rezising============================================================================
(function () {
var interval;
jQuery.event.special.contentchange = {
setup: function () {
var self = this,
$this = $(this),
$originalContent = $this.text();
interval = setInterval(function () {
if ($originalContent != $this.text()) {
$originalContent = $this.text();
jQuery.event.handle.call(self, { type: 'contentchange' });
}
}, 100);
},
teardown: function () {
clearInterval(interval);
}
};
})();
//=========================================================================================
//Function to resize the right container============================================================
(function ($) {
$.fn.fixRightContainer = function () {
this.each(function () {
var width = $(this).width();
var parentWidth = $(this).offsetParent().width();
var percent = Math.round(100 * width / parentWidth);
if (percent > 62) {
$('#RightContainer').remove();
}
});
};
})(jQuery);
//===================================================================================================

Resources