Skip to content

Commit

Permalink
- Reverting fitToSection from CSS Snaps to custom JS
Browse files Browse the repository at this point in the history
  • Loading branch information
alvarotrigo committed Aug 30, 2022
1 parent 30beb1b commit 614dcf4
Show file tree
Hide file tree
Showing 17 changed files with 41 additions and 95 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ var myFullpage = new fullpage('#fullpage', {
scrollingSpeed: 700,
autoScrolling: true,
fitToSection: true,
fitToSectionDelay: 600,
scrollBar: false,
easing: 'easeInOutCubic',
easingcss3: 'ease',
Expand Down Expand Up @@ -430,6 +431,9 @@ It requires the file `vendors/easings.min.js` or [jQuery UI](http://jqueryui.com

- `fitToSection`: (default `true`) Determines whether or not to fit sections to the viewport or not. When set to `true` the current active section will always fill the whole viewport. Otherwise the user will be free to stop in the middle of a section.

- `fitToSectionDelay`: (default 1000). If `fitToSection` is set to true, this delays
the fitting by the configured milliseconds.

- `scrollBar`: (default `false`) Determines whether to use scroll bar for the **vertical sections** on site or not. In case of using scroll bar, the `autoScrolling` functionality will still work as expected. The user will also be free to scroll the site with the scroll bar and fullPage.js will fit the section in the screen when scrolling finishes.

- `paddingTop`: (default `0`) Defines the top padding for each section with a numerical value and its measure (paddingTop: '10px', paddingTop: '10em'...) Useful in case of using a fixed header.
Expand Down
4 changes: 4 additions & 0 deletions lang/brazilian-portuguese/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ var myFullpage = new fullpage('#fullpage', {
scrollingSpeed: 700,
autoScrolling: true,
fitToSection: true,
fitToSectionDelay: 600,
scrollBar: false,
easing: 'easeInOutCubic',
easingcss3: 'ease',
Expand Down Expand Up @@ -431,6 +432,9 @@ Requer o arquivo `vendors/easings.min.js` ou [jQuery UI](http://jqueryui.com/) p

- `fitToSection`: (padrão `true`) Determina se as seções devem ou não ser ajustadas à viewport. Quando definido como `true`, a seção ativa atual sempre preencherá toda a janela de visualização. Caso contrário, o usuário estará livre para parar no meio de uma seção.

- `fitToSectionDelay`: (default 1000). If `fitToSection` is set to true, this delays
the fitting by the configured milliseconds.

- `scrollBar`: (padrão `false`) Determina se a barra de rolagem deve ser usada para as **seções verticais** no site ou não. No caso de usar a barra de rolagem, a funcionalidade `autoScrolling` ainda funcionará conforme o esperado. O usuário também estará livre para rolar o site com a barra de rolagem e fullPage.js caberá na seção na tela quando a rolagem terminar.

- `paddingTop`: (padrão `0`) Define o preenchimento superior para cada seção com um valor numérico e sua medida (paddingTop: '10px', paddingTop: '10em'...) Útil no caso de usar um cabeçalho fixo.
Expand Down
3 changes: 3 additions & 0 deletions lang/chinese/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ var myFullpage = new fullpage('#fullpage', {
scrollingSpeed: 700,
autoScrolling: true,
fitToSection: true,
fitToSectionDelay: 600,
scrollBar: false,
easing: 'easeInOutCubic',
easingcss3: 'ease',
Expand Down Expand Up @@ -428,6 +429,8 @@ new fullpage('#fullpage', {

- `fitToSection`: (默认为 `true` )确定是否将 section 适应视图。 当设置为 `true` 时,当前激活 section 将始终填充整个视图。 否者,section 可以停留在网页的任何位置。

- `fitToSection`: (默认为 `true` )确定是否将 section 适应视图。 当设置为 `true` 时,当前激活 section 将始终填充整个视图。 否者,section 可以停留在网页的任何位置。

- `scrollBar`: (默认 `false` )确定是否使用站点的滚动条。 在使用滚动条的情况下,`autoScrolling` 功能仍将按预期工作。 用户也可以使用滚动条自由滚动网站,当滚动完成时,fullPage.js 将适配屏幕上的部分。

- `paddingTop`: (默认 `0` )用数值和相对长度(paddingTop:'10px',paddingTop:'10em'...)定义每个 section 的内边距( top )。
Expand Down
3 changes: 3 additions & 0 deletions lang/french/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ var myFullpage = new fullpage('#fullpage', {
scrollingSpeed: 700,
autoScrolling: true,
fitToSection: true,
fitToSectionDelay: 600,
scrollBar: false,
easing: 'easeInOutCubic',
easingcss3: 'ease',
Expand Down Expand Up @@ -437,6 +438,8 @@ new fullpage('#fullpage', {

- `fitToSection`: (par défaut `true`) Détermine si des sections doivent ou non être ajustées à la fenêtre d'affichage. Lorsqu'elle est réglée sur `true`, la section active courante remplira toujours toute la fenêtre d'affichage. Sinon, l'utilisateur sera libre de s'arrêter au milieu d'une section.

- `fitToSectionDelay` : (par défaut 1000). Si `fitToSection` est mis à true, cela retarde l'adaptation par millisecondes configurées.

- `scrollBar` : (par défaut `false`) Détermine s'il faut utiliser la barre de défilement pour le site ou non. En cas d'utilisation de la barre de défilement, la fonctionnalité `autoScrolling` fonctionnera toujours comme prévu. L'utilisateur sera également libre de faire défiler le site avec la barre de défilement et fullPage.js s'adaptera à la section à l'écran lorsque le défilement sera terminé.

- `paddingTop` : (par défaut `0`) Définit le remplissage supérieur de chaque section avec une valeur numérique et sa mesure (paddingTop:'10px', paddingTop:'10em'...) Utile en cas d'utilisation d'un en-tête fixe.
Expand Down
3 changes: 3 additions & 0 deletions lang/korean/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ new fullpage('#fullpage', {
scrollingSpeed: 700,
autoScrolling: true,
fitToSection: true,
fitToSectionDelay: 600,
scrollBar: false,
easing: 'easeInOutCubic',
easingcss3: 'ease',
Expand Down Expand Up @@ -417,6 +418,8 @@ new fullpage('#fullpage', {

- `fitToSection`: (기본값 `true`) 구역을 모바일 지원(viewport)에 맞출지 말지를 결정합니다. `true`로 설정하면 현재 활성화된 구역이 항상 모바일 지원(viewport) 전체를 가득 채웁니다. 그렇지 않은 경우에는 사용자는 구역 중간에서 자유롭게 멈출 수 있습니다.

- `fitToSectionDelay`: (기본값 1000). `fitToSection`이 true로 설정되면 설정된 1000분의 1초 단위로 맞춤을 지연합니다.

- `scrollBar`: (기본값 `false`) 웹사이트에 스크롤 막대기를 쓸지 말지를 결정합니다. 스크롤 막대기를 쓰는 경우 `autoScrolling` 기능이 여전히 예상대로 작동할 것입니다. 또한 사용자는 스크롤 막대기로 웹사이트에서 이동할 수도 있으며 스크롤이 끝나면 fullPage.js가 화면 구역에 맞춰집니다.

- `paddingTop`: (기본값 `0`) 구역별 상위에 채우는 부분을 수치와 측정값(`paddingTop: '10px'`, `paddingTop: '10em'`...)으로 정의합니다. 고정된 머리말을 쓰실 때 유용합니다.
Expand Down
3 changes: 3 additions & 0 deletions lang/russian/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ var myFullpage = new fullpage('#fullpage', {
scrollingSpeed: 700,
autoScrolling: true,
fitToSection: true,
fitToSectionDelay: 600,
scrollBar: false,
easing: 'easeInOutCubic',
easingcss3: 'ease',
Expand Down Expand Up @@ -427,6 +428,8 @@ new fullpage('#fullpage', {

- `fitToSection`: (по умолчанию `true`) Определяет, нужна ли подстройка разделов под окно просмотра. При установке значения `true` для данной опции текущий активный раздел всегда будет заполнять окно просмотра. В противном случае пользователь будет иметь возможность остановиться на середине раздела (когда )

- `fitToSectionDelay`: (по умолчанию 1000). Если для опции `fitToSection` установлено значение `true`, данная функция замедлит подстройку на настроенные миллисекунды.

- `scrollBar`: (по умолчанию `false`) Определяет, будет ли использоваться полоса прокрутки на сайте. При использовании полосы прокрутки функция `autoScrolling` будет работать как обычно. Пользователь по-прежнему сможет пролистывать сайт с помощью полосы прокрутки, и fullPage.js подстроит раздел под экран по окончании скроллинга.

- `paddingTop`: (по умолчанию `0`) Определяет верхний отступ для каждого раздела в числовом формате (paddingTop: '10px', paddingTop: '10em'...) Данная функция удобна при использовании фиксированных верхних колонтитулов.
Expand Down
4 changes: 3 additions & 1 deletion lang/spanish/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ new fullpage('#fullpage', {
scrollingSpeed: 700,
autoScrolling: true,
fitToSection: true,
fitToSectionDelay: 1000,
fitToSectionDelay: 600,
scrollBar: false,
easing: 'easeInOutCubic',
easingcss3: 'ease',
Expand Down Expand Up @@ -432,6 +432,8 @@ Otras librerías puede ser usadas si se desea.

- `fitToSection`: (por defecto `true`) Determina si "encajar" las secciones en el navegador o no. Esto tiene sentido cuando se usa `autoScrolling:false` o `scrollBar:false` o el modo responsive. Cuando se usa `true` la sección actual se desplazará en la pantalla hasta llegar el contenido de la ventana usando. De lo contrario el usuario podrá desplazarse libremente y parar en mitad de 2 secciones.

- `fitToSectionDelay`: (por defecto `1000`). Si `fitToSection` está activo, esta opción define el tiempo en milisegundos que esperará fullpage.js desde que el usuario dejó de desplazarse hasta que la sección se encaja en la ventana.

- `scrollBar`: (por defecto `false`) Determina si se utiliza la barra de desplazamiento del navegador o no para las **secciones verticales**. En caso afirmativo, la funcionalidad de `autoScrolling` (de desplazamiento automático o "a saltos") funcionará como se espera. El usuario será también libre de desplazarse por la página usando la barra de navegación y fullpage.js encajará la sección cuando el desplazamiento cese siempre y cuando se use `fitToSection`.

- `paddingTop`: (por defecto `0`) Determina el "padding" superior para cada sección con un valor numérico y su unidad de medida (paddingTop: '10px', paddingTop: '10em'...). Útil cuando se usan cabeceras fijas (`fixed`).
Expand Down
18 changes: 0 additions & 18 deletions src/css/fullpage.css
Original file line number Diff line number Diff line change
Expand Up @@ -266,24 +266,6 @@ html.fp-enabled,
border: 0;
}

.fp-snaps{
overflow-y: auto !important;
height: 100% !important;
-ms-scroll-snap-type: y mandatory;
scroll-snap-type: y mandatory;
scroll-behavior: smooth;
}

.fp-snaps .fp-section{
scroll-snap-align: start;
}

/* Used for DragAndMove*/
.fp-disable-snap body{
scroll-behavior: unset !important;
scroll-snap-type: none !important;
}

/* Customize website's scrollbar like Mac OS
Not supports in Firefox and IE */
.fp-scroll-mac .fp-overflow::-webkit-scrollbar {
Expand Down
4 changes: 0 additions & 4 deletions src/js/autoScrolling.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,6 @@ export function setAutoScrolling(value, type){

//scrolling the page to the section with no animation
if (element != null) {
utils.css($htmlBody, {
'scroll-behavior': 'unset'
});

var scrollSettings = getScrollSettings(element.offsetTop);
scrollSettings.element.scrollTo(0, scrollSettings.options);
}
Expand Down
3 changes: 0 additions & 3 deletions src/js/beyondFullpage/scrollBeyondFullPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@ export function scrollBeyondFullPage(){
var scrollSettings = getScrollSettings(dtop);
FP.test.top = -dtop + 'px';

utils.css($html, {'scroll-snap-type': 'none'});
utils.css($htmlBody, {'scroll-behavior': 'unset'});

setState({canScroll: false});
scrollTo(scrollSettings.element, scrollSettings.options, getOptions().scrollingSpeed, function(){
setTimeout(function(){
Expand Down
7 changes: 0 additions & 7 deletions src/js/common/scrollTo.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,6 @@ export function scrollTo(element, to, duration, callback) {

setState({activeAnimation: true});

// Making sure we can trigger a scroll animation
// when css scroll snap is active. Temporally disabling it.
var usingSnaps = getOptions().fitToSection && (!getOptions().autoScrolling || getOptions().scrollBar);
if(usingSnaps){
utils.css($html, {'scroll-snap-type': 'none'});
}

// Cancelling any possible previous animations (io: clicking on nav dots very fast)
if(g_animateScroll){
window.cancelAnimationFrame(g_animateScroll);
Expand Down
1 change: 0 additions & 1 deletion src/js/common/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export const ACTIVE = 'active';
export const ACTIVE_SEL = '.' + ACTIVE;
export const COMPLETELY = 'fp-completely';
export const COMPLETELY_SEL = '.' + COMPLETELY;
export const SNAPS = 'fp-snaps';

// section
export const SECTION_DEFAULT_SEL = '.section';
Expand Down
56 changes: 12 additions & 44 deletions src/js/fitToSection.js
Original file line number Diff line number Diff line change
@@ -1,61 +1,29 @@
import * as utils from './common/utils.js';
import { setVariableState } from './common/options.js';
import { getOptions } from './common/options.js';
import { $html } from './common/cache.js';
import { doc, FP } from './common/constants.js';
import {
SNAPS
} from './common/selectors.js';
import { FP } from './common/constants.js';
import { setState, state } from './common/state.js';
import { scrollPage } from './scroll/scrollPage.js';

FP.setFitToSection = setFitToSection;
FP.fitToSection = fitToSection;

export const g_isCssSnapsSupported = (function(){
return isCssSnapsSupported();
})();

/**
* Sets fitToSection
*/
export function setFitToSection(value, type){
toggleCssSnapsWhenPossible(value);
setVariableState('fitToSection', value, type);
}


/**
* Adds or removes CSS snaps scrolling behaviour depending on the given value.
*/
export function toggleCssSnapsWhenPossible(value){
if(g_isCssSnapsSupported){
var canAddSnaps = getOptions().fitToSection && (!getOptions().autoScrolling || getOptions().scrollBar) && value;
var toggleFunction = canAddSnaps ? utils.addClass : utils.removeClass;
toggleFunction($html, SNAPS);
}
}

/**
* Checks for CSS scroll snaps support.
*/
function isCssSnapsSupported(){
var style = doc.documentElement.style;

return 'scrollSnapAlign' in style ||
'webkitScrollSnapAlign' in style ||
'msScrollSnapAlign' in style;
}

/**
* Fits the site to the nearest active section
*/
export function fitToSection(){
// //checking fitToSection again in case it was set to false before the timeout delay
// if(canScroll){
// //allows to scroll to an active section and
// //if the section is already active, we prevent firing callbacks
// isResizing = true;

// scrollPage(state.activeSection);
// isResizing = false;
// }
//checking fitToSection again in case it was set to false before the timeout delay
if(state.canScroll){
//allows to scroll to an active section and
//if the section is already active, we prevent firing callbacks
setState({isResizing: true});

scrollPage(state.activeSection);
setState({isResizing: false});
}
}
2 changes: 0 additions & 2 deletions src/js/instance.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { setMouseHijack } from './mouse/wheel.js';
import { responsive } from './responsive.js';
import { setBodyClass } from './stateClasses.js';
import { setKeyboardScrolling } from './keyboard/setKeyboardScrolling.js';
import { toggleCssSnapsWhenPossible } from './fitToSection.js';
import { DESTROYED } from './common/selectors.js';
import { doc, FP } from './common/constants.js';
import { EventEmitter } from './common/eventEmitter.js';
Expand All @@ -26,7 +25,6 @@ export function init(){

setOptionsFromDOM();
prepareDom();
toggleCssSnapsWhenPossible(true);
setAllowScrolling(true);
setMouseHijack(true);
setAutoScrolling(getOptions().autoScrolling, 'internal');
Expand Down
1 change: 1 addition & 0 deletions src/js/optionsDefault.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const defaultOptions = {
scrollingSpeed: 700,
autoScrolling: true,
fitToSection: true,
fitToSectionDelay: 600,
easing: 'easeInOutCubic',
easingcss3: 'ease',
loopBottom: false,
Expand Down
9 changes: 4 additions & 5 deletions src/js/scroll/scrollHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getState, setState, state } from '../common/state.js';
import { lazyLoad } from '../lazyLoad/lazyLoad.js';
import { setPageStatus } from '../anchors/setPageStatus.js';
import { activateMenuAndNav } from '../menu/activateMenuAndNav.js';
import { $body, $html } from '../common/cache.js';
import { $body } from '../common/cache.js';
import { getYmovement } from '../common/utilsFP.js';
import {
COMPLETELY,
Expand All @@ -15,7 +15,7 @@ import {
import { fireCallbackOncePerScroll } from '../callbacks/fireCallbacksOncePerScroll.js';
import { fireCallback } from '../callbacks/fireCallback.js';
import { EventEmitter } from '../common/eventEmitter.js';
import { doc } from '../common/constants.js';
import { fitToSection } from '../fitToSection.js';

var lastScroll = 0;
let g_scrollId;
Expand Down Expand Up @@ -149,7 +149,6 @@ export function scrollHandler(e){
}



if(getOptions().fitToSection && state.canScroll){

clearTimeout(g_scrollId2);
Expand All @@ -163,9 +162,9 @@ export function scrollHandler(e){

// No section is fitting the viewport? Let's fix that!
if(!fixedSections.length){
utils.css($html, {'scroll-snap-type': 'y mandatory'});
fitToSection();
}
}, 300);
}, getOptions().fitToSectionDelay);
}
}
}
Expand Down
11 changes: 1 addition & 10 deletions src/js/scroll/scrollPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,6 @@ function performMovement(v){
var scrollSettings = getScrollSettings(v.dtop);
FP.test.top = -v.dtop + 'px';

utils.css($htmlBody, {'scroll-behavior': 'unset'});
clearTimeout(g_afterSectionLoadsId);

scrollTo(scrollSettings.element, scrollSettings.options, getOptions().scrollingSpeed, function(){
Expand Down Expand Up @@ -260,15 +259,7 @@ function performMovement(v){
/**
* Actions to do once the section is loaded.
*/
function afterSectionLoads(v){
if(getOptions().fitToSection){

// Removing CSS snaps for auto-scrolling sections
if(utils.hasClass(utils.$(SECTION_ACTIVE_SEL)[0], AUTO_HEIGHT)){
utils.css($html, {'scroll-snap-type': 'none'});
}
}

function afterSectionLoads(v){
setState({isBeyondFullpage: false});
continuousVerticalFixSectionOrder(v);

Expand Down

0 comments on commit 614dcf4

Please sign in to comment.