What does rootmodifers do in famo.us? - javascript

I am new to Famo.us, can anybody explain me what does rootmodifers do in famo.us, here is its example
function SlideshowView () {
Views.apply(this, arguments);
this.rootModifier = new StateModifier({
size:this.options.size
});
this.mainNode = this.add(this.rootModifier);
_createLightBox.call(this);
_createSlides.call(this);
}

this.rootMidifier just allows you to have a way to control the entire slideShow's position, opacity, origin, or alignment later in the applications. More importantly this.rootModifier is added to the render node like this this.mainNode = this.add(this.rootModifier); This code places the modifier at the top of the render tree for the slideshow branch and exposes access to the modifier for later use in the all. For example later in the app you could have a function that changes the opacity.
SlideShow.prototype.hide = function() {
this.rootModifier.setOpacity(0, {duration: 3000});
}

Related

IntersectionObserver Lazy Loading not Working

This is my first time attempting Lazy Loading, and I wanted to use IntersectionObserver. Got started by following along with this website. I honestly just want the content of the page to wait to load until it is less than 50% of the viewport's width below the viewport. I'm not sure how to observe all content, so I just selected the classes for the widgets that are being displayed, as they are the main content. Unfortunately my code doesn't seem to be doing much. I added a console.log at the beginning to make sure the file was linked correctly, and I tried to add more console.logs to log when the widget moves in and out of the capture area. The first console.log works, but nothing else happens.
Here is what I have:
console.log('file loaded');
const widgets = document.querySelectorAll('.widget');
const config = {
root: null,
rootMargin: '-50px 0px -55% 0px',
threshold: .5
};
let isLeaving = false;
let observer = new IntersectionObserver(function(entries, self) {
entries.forEach(entry => {
if (entry.isIntersecting) {
// we are ENTERING the "capturing frame". Set the flag.
isLeaving = true;
// Do something with entering entry
console.log("Widget loaded.");
self.unobserve(entry.target);
} else if (isLeaving) {
// we are EXITING the "capturing frame"
isLeaving = false;
// Do something with exiting entry
console.log("Widget is exiting.")
}
});
}, config);
widgets.forEach(widget => {
observer.observe(widget);
});
This code is in it's own js file. Where should I be linking it in the HTML file?
I'd appreciate any help I can get! Let me know if I need to provide more information.

Issue with image load recursive chain on slow network/mobile

So basically I have a page with a few sections. Each sections contains 5-30 image icons that are fairly small in size but large enough that I want to manipulate the load order of them.
I'm using a library called collagePlus which allows me to give it a list of elements which it will collage into a nice image grid. The idea here is to start at the first section of images, load the images, display the grid, then move on to the next section of images all the way to the end. Once we reach the end I pass a callback which initializes a gallery library I am using called fancybox which simply makes all the images interactive when clicked(but does not modify the icons state/styles).
var fancyCollage = new function() { /* A mixed usage of fancybox.js and collagePlus.js */
var collageOpts = {
'targetHeight': 200,
'fadeSpeed': 2000,
'allowPartialLastRow': true
};
// This is just for the case that the browser window is resized
var resizeTimer = null;
$(window).bind('resize', function() {
resetCollage(); // resize all collages
});
// Here we apply the actual CollagePlus plugin
var collage = function(elems) {
if (!elems)
elems = $('.Collage');
elems.removeWhitespace().collagePlus(collageOpts);
};
var resetCollage = function(elems) {
// hide all the images until we resize them
$('.Collage .Image_Wrapper').css("opacity", 0);
// set a timer to re-apply the plugin
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
collage(elems);
}, 200);
};
var setFancyBox = function() {
$(".covers").fancybox({/*options*/});
};
this.init = function(opts) {
if (opts != null) {
if (opts.height) {
collageOpts.targetHeight = opts.height;
}
}
$(document).ready(function() {
// some recursive functional funk
// basically goes through each section then each image in each section and loads the image and recurses onto the next image or section
function loadImage(images, imgIndex, sections, sectIndex, callback) {
if (sectIndex == sections.length) {
return callback();
}
if (imgIndex == images.length) {
var c = sections.eq(sectIndex);
collage(c);
images = sections.eq(sectIndex + 1).find("img.preload");
return loadImage(images, 0, sections, sectIndex + 1, callback);
}
var src = images.eq(imgIndex).data("src");
var img = new Image();
img.onload = img.onerror = function() {
images[imgIndex].src = src; // once the image is loaded set the UI element's source
loadImage(images, imgIndex + 1, sections, sectIndex, callback)
};
img.src = src; // load the image in the background
}
var firstImgList = $(".Collage").eq(0).find("img.preload");
loadImage(firstImgList, 0, $(".Collage"), 0, setFancyBox);
});
}
}
From my galleries I then call the init function.
It seems like my recursive chain being triggered by img.onload or img.onerror is not working properly if the images take a while to load(on slow networks or mobile). I'm not sure what I'm missing here so if anyone can chip in that would be great!
If it isn't clear what is going wrong from the code I posted you can see a live example here: https://www.yuvalboss.com/albums/olympic-traverse-august-2017
It works quite well on my desktop, but on my Nexus 5x it does not work and seems like the finally few collage calls are not happening. I've spent too long on this now so opening this up to see if I can get some help. Thanks everyone!
Whooooo I figured it out!
Was getting this issue which I'm still unsure about what it means
[Violation] Forced reflow while executing JavaScript took 43ms
Moved this into the callback that happens only once all images are loaded
$(window).bind('resize', function() {
resetCollage(); // resize all collages
});
For some reason it was getting called early even if the browser never resized causing collage to get called when no elements existed yet.
If anyone has any informative input as to why I was getting this js violation would be great to know so I can make a better fix but for now this works :):):)

Is there a way to animate the size of the header in the HeaderFooterLayout?

Is it possible to animate the size of the header in a HeaderFooterLayout? I am trying to change it's size with an animation but I am not seeing any API for this. So I was wondering about a technique for doing it.
You can achieve this by using a Transitionable. This is done by the following:
Create a transition for the animation:
var transition = {
duration: 400,
curve: Easing.inOutQuad
};
Set the start & end pixel counts:
var start = open ? 200 : 100;
var end = open ? 100 : 200;
Instantiate your new Transitionable with the starting pixel count:
var transitionable = new Transitionable(start);
Create the function that will be executed to apply the pixel count:
var prerender = function () {
layout.setOptions({
headerSize: transitionable.get()
})
};
Attache the function to the Engine event:
Engine.on('prerender', prerender);
Add transition to end state to the queue of pending transitions:
transitionable.set(end, transition, complete);
Here is a working fiddle for you to reference: http://jsfiddle.net/Mabuti/4or8nxh4/
In full disclosure I did use the following post as a point of reference: famo.us: can I animate the header/footer heights of a header footer layout? but I tried to add some context to the process.
You could also review the Transitionable documentation to see better understand what it is doing: https://famo.us/docs/transitions/Transitionable
An alternative could be to use the famous-flex LayoutController and HeaderFooterLayout.
The code is pretty straightforward:
var LayoutController = require('famous-flex/LayoutController');
var HeaderFooterLayout = require('famous-flex/layouts/HeaderFooterLayout');
// Create header/content surface/views
var header = new Surface(..);
var content = new Surface(..);
// Create header-footer layout
var layout = new LayoutController({
layout: HeaderFooterLayout,
layoutOptions: {
headerSize: 40
},
flow: true, // this causes a smooth transition when changing the header-size
reflowOnResize: false, // do not reflow on resize
dataSource: {
header: header,
content: content
}
});
...
// Change the height of the header (because flow is enabled,
// this will automatically cause it to smoothly animate from
// the old height to the new height)
layout.setLayoutOptions({
headerSize: 100
});
Library: https://github.com/IjzerenHein/famous-flex

About image rotation once element with specific id is clicked

Logo and elements from ul once clicked rotates image. By default image is already rotated by certain degrees, then on each click image rotates to necessary value.
So far I was using the following:
$("#objRotates").css('opacity','.2');
var value = 0;
var prev_value = 0;
$( "li" ).click(function() {
var text=$(this).text();
if(text==="text1"){value=0;}
if(text==="text2"){value=33;}
if(text==="text3"){value=66;}
if(prev_value != value){
$("#objRotates").animate({opacity:'1'});
$("#objRotates").rotate({
animateTo:value,
easing: $.easing.easeInOutExpo,
center: ["25px", "150px"],
callback: function(){$("#objRotates").animate({opacity:'0.2'});}
});
}
prev_value = value;
});
Above code is the one that was used before, where images start position was 0 and its animation was triggered from link text.
Using jqueryRotate.js examples(here)
How do I change the code, so that images start position is certain degrees and animation starts if element with specific ID is clicked?
Give at least clue..Cause for now, looking at my old code, I am lost. Thanks in advance.
SIMPLIFIED FIDDLE
Ok, so I've created a couple of samples for you to check out. The first one is very basic and I've simplified the code a little to make it easier to understand. This one just uses completely static values and a static elementId for the event, which I'm pretty sure answers your question based on your response to my comment yesterday. http://jsfiddle.net/x9ja7/594/
$("#elementId").click(function () {
var startingAngle = 45;
var endingAngle = 90;
var elementToRotate = "img";
$(elementToRotate).rotate({
angle: startingAngle,
animateTo: endingAngle
});
});
But I wanted to give another example as well that would be dynamic and repeatable for multiple elements. With the code above, you would have to copy/paste the same code over and over again if you want to perform this animation by clicking different elements. Here's an alternative. In this example, you set all of your parameters in the data attributes in the clickable element, then the function is completely repeatable, you only have to write it once. Less code = everyone happy! Here's the example: http://jsfiddle.net/x9ja7/595/
//#region Default starting angles
$("#image1").rotate({ angle: 90 });
$("#image2").rotate({ angle: 20 });
//#endregion
$(".rotateAction").click(function () {
//#region Optional parameter - used in the optional callback function
var $self = $(this);
//#endregion
var startingAngle = Number($(this).attr("data-startingangle"));
var endingAngle = Number($(this).attr("data-endingangle"));
var elementToRotate = $(this).attr("data-elementtorotate");
//#region If the current angle is the ending angle, reverse the animation - this can be removed if you want, I thought it may be cool to show some of the things you can do with this.
var currentAngle = $(elementToRotate).getRotateAngle();
if ( currentAngle[0] === endingAngle) {
startingAngle = Number($(this).attr("data-endingangle"));
endingAngle = Number($(this).attr("data-startingangle"));
}
//#endregion
$(elementToRotate).rotate({
angle: startingAngle,
animateTo: endingAngle
//#region This is optional - uncommenting this code would make the animation single-use only
//, callback: function () { $self.off().removeClass("clickable"); }
//#endregion
});
});
Hope this helps. If you need any other assistance, please let me know.

Fading script will not work in IE?

I'm pretty new to Javascript and have been trying to achieve some fading effects on a website.
I've managed to hammer together the effects I want and everything's working fine on Firefox & Safari. However IE doesn't like it. The first script to change the background colour works but the second script to fade in the content does nothing.
I'm calling the scripts from the head as follows:
window.onload=siteIntro;
And the Javacript which is not working is here. Any help or suggestions would be appreciated, the live site can be viewed if needed.
Many Thanks
// ################# Fade Divs ###############################
function Fade(objID,CurrentAlpha,TargetAlpha,steps){
var obj = document.getElementById(objID);
CurrentAlpha = parseInt(CurrentAlpha);
if (isNaN(CurrentAlpha)){
CurrentAlpha = parseInt(obj.style.opacity*100);
if (isNaN(CurrentAlpha))CurrentAlpha=100;
}
var DeltaAlpha=parseInt((CurrentAlpha-TargetAlpha)/steps);
var NewAlpha = CurrentAlpha - DeltaAlpha;
if (NewAlpha == 100 && (navigator.userAgent.indexOf('Gecko') != -1 && navigator.userAgent.indexOf('Safari') == -1)) NewAlpha = 99.99;
obj.style.opacity = (NewAlpha / 100);
obj.style.MozOpacity = obj.style.opacity;
obj.style.KhtmlOpacity = obj.style.opacity;
obj.style.filter = 'alpha(opacity='+NewAlpha+')';
if (steps>1){
setTimeout('Fade("'+objID+'",'+NewAlpha+','+TargetAlpha+','+(steps-1)+')', 50);
}
}
// ################# Toggle content div visibility ###############################
function mainVis(showMain) {
document.getElementById(showMain).style.visibility ="visible";
}
function pageSwitch(show0, hide0, hide1, hide2, hide3) {
document.getElementById(show0).style.visibility ="visible";
document.getElementById(hide0).style.visibility ="hidden";
document.getElementById(hide1).style.visibility ="hidden";
document.getElementById(hide2).style.visibility ="hidden";
document.getElementById(hide3).style.visibility ="hidden";
}
function pg1() {
pageSwitch('prices', 'icon', 'about', 'map', 'news');
Fade('prices','0',100,30)
}
function pg2() {
pageSwitch('about', 'icon', 'prices', 'map', 'news');
Fade('about','0',100,30)
}
function pg3() {
pageSwitch('map', 'icon', 'about', 'prices', 'news');
Fade('map','0',100,30)
}
function pg4() {
pageSwitch('news', 'icon', 'map', 'about', 'prices');
Fade('news','0',100,30)
}
// ################# Site Intro Functions ###############################
function siteIntro() {
setTimeout("NLBfadeBg('b1','#FFFFFF','#000000','3000')",2000);
mainVis('main');
setTimeout("Fade('main','',100,30)",5000);
}
MS filters only apply to elements that "have layout".
To force layout, you can give the element a width or a height, or use the old zoom: 1; trick.
Not sure if this is the cause of your problems, but you could try it.
You can read more about hasLayout here.
Another thing, instead of:
setTimeout('Fade("'+objID+'",'+NewAlpha+','+TargetAlpha+','+(steps-1)+')', 50)`
you can simply write:
setTimeout(function() { Fade(objID, NewAlpha, TargetAlpha, steps-1); }, 50)`
Unless you are doing it just for fun and/or learning, just use an existing JS library instead of re-inventing the wheel.
Maybe you can take advantage of an out-of-the-box cross browser script like this
http://brainerror.net/scripts/javascript/blendtrans/
Or use jQuery (which is great with animating and effects) or any other JS library
This might not be an answer you are looking for, but you shouldn't be doing this: you can use jQuery to do this for you. One or two lines of code, and it is cross browser compatible.

Categories

Resources