infinite auto scrolling gallery tutorial - JS

woolee의 기록보관소·2022년 10월 28일
0

FE 기능구현 연습

목록 보기
5/33

JS

갤러리 별 이미지 삽입

const scrollable = document.querySelector('.scrollable');
const content = document.querySelector('.content');
const imgSections = [...document.querySelectorAll('.img-section')];
const images = [...document.querySelectorAll('.img')];

images.forEach((image, idx) => {
  image.style.backgroundImage = `url(./images/${idx+1}.jpeg)`
})

인터랙션 구현(위아래로 사라지고 등장하기)

getBoundingClientRect()를 사용하면 요소의 위치를 얻을 수 있다.
elem.getBoundingClientRect()에는 아래 값들이 전부 담겨 있으므로 .height로 뽑으면 높이값이 나오는 식.

  • top or y : 화면 상단부터 요소 첫지점
  • bottom : 화면 상단부터 요소 끝지점
  • left or x : 화면 좌측부터 요소 첫지점
  • right : 화면 좌측부터 요소 끝지점
  • width : 요소 너비
  • height : 요소 높이

resize 시 -> init()
document.body.style.height를 content 높이로 잡아주기.
resize 이벤트는 document view 변경될 때 발생함(브라우저 창이나 프레임 변경될 때 이벤트 호출).
여기에 init 함수를 넣으면 == 변경될 때마다 content 높이로 바꿔주기??
(아래에서 DOMContentLoaded로 DOM이 로드되면, scrollTo(0,1)로 계속 target을 증가시킬 거고, 그렇게 되면 바로 뷰가 변경되니까 여기서 다시 resize하고. 계속 resize하면서 1씩 내려가는 걸로 웹페이지가 계속 움직이는 걸 표현한 것 같다.)

.menuTog(우측 상단 메뉴 버튼) 클릭 시 -> toggleMenu()
if : 좌측 하단 .menu가 열려있으면(active),
-- 우측상단 .menu-tog active 지워주고
-- toggleMenuWraps()로 .menu-wrap들을 전부 지워주고
-- 0.3초 뒤에 .menu도 active 지워주기 (시간차를 둬서 인터랙션 구현)
-- 마찬가지로 0.3초 뒤에 toggleWraps로 갤러리 이미지 열어주기.
else : 반대로 구현

갤러리 이미지랑, 좌측 하단 애들을 전부 .wrap으로 관리하면서 끄고 닫고를 전부 관리.

const wraps = [...document.querySelectorAll('.wrap')];
const menuTog = document.querySelector('.menu-tog');
const menu = document.querySelector('.menu');
const menuWraps = [...document.querySelectorAll('.menu-wrap')];

function init() {
  document.body.style.height = `${content.getBoundingClientRect().height}px`;
}

window.addEventListener('resize', init);
menuTog.addEventListener('click', toggleMenu);

function displayWraps() {
  wraps.forEach((wrap,idx) => {
    setTimeout(() => {
      wrap.classList.add('active');
    }, (idx+1) * 50)
  })
}

function toggleMenu() {
  if (menu.classList.contains('active')) {
    menuTog.classList.remove('active');
    toggleMenuWraps(false);
    setTimeout(() => {
      menu.classList.remove('active');
    }, 300)
    setTimeout(() => {
      toggleWraps(true);
    }, 300)
  } else {
    menuTog.classList.add('active');
    toggleWraps(false);
    setTimeout(() => {
      menu.classList.add('active');
    }, 300)
    setTimeout(() => {
      toggleMenuWraps(true);
    }, 300)
  }
}

function toggleWraps(active) {
  wraps.forEach(wrap => {
    toggleWrap(wrap, active);
  })
}

function toggleMenuWraps(active) {
  menuWraps.forEach(wrap => {
    toggleWrap(wrap, active);
  })
}

function toggleWrap(wrap, active) {
  setTimeout(() => {
    if (active) {
      wrap.classList.add('active');
    } else {
      wrap.classList.remove('active');
    }
  })
}

How to detect a mobile device using jQuery는 아래 링크에서,
https://stackoverflow.com/questions/3514784/how-to-detect-a-mobile-device-using-jquery/3540295#3540295

모바일이 아니면 imgSection에 clonNode를 붙여서 무한 스크롤 구현

기본적으로 아래로 흐르게, 클릭시 방향 변경 구현 -> scroll()

target 값을 지정해놓고 거기로 계속 스크롤이 향하게 함으로써 웹페이지의 자연스러운 이동을 표현

window.scrollY : 수직으로 스크롤 얼마나 됐는지
content.offsetHeight : margin 제외 padding,border 값 포함한 콘텐츠의 높이
window.scrollTo(x좌표, y좌표) : 지정 위치로 스크롤바 이동
requestAnimationFram() : 애니메이션 구현

/* How to detect a mobile device using jQuery */
let isMobile = false;
if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) 
    || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) { 
    isMobile = true;
}

if (!isMobile) {
  imgSections.forEach(section => {
    let clonedSection = section.cloneNode(true);
    clonedSection.classList.add('clone');
    content.appendChild(clonedSection);
  })
}

let target = 1;
let reverse = false;

document.addEventListener('click', () => reverse = !reverse);

function scroll() {
  target = window.scrollY;

  if (!isMobile) {
    if (target <= 0) {
      target = (content.offsetHeight / 2) - 1;
      window.scrollTo(0, target);
    } else if (target >= content.offsetHeight / 2) {
      target = 1;
      window.scrollTo(0, target);
    }
  }

  if (reverse) {
    target--
  } else {
    target++
  }

  window.scrollTo(0, target);
  scrollable.style.transform = `translateY(-${target}px)`;
  requestAnimationFrame(scroll);
}


displayWraps();
init();

document.addEventListener('DOMContentLoaded', () => {
  setTimeout(() => {
    window.scrollTo(0, 1);
  }, 200)
  scroll();
})

참고

Vanilla JavaScript Project: Infinite Auto Scrolling Gallery With Clean Menu

profile
https://medium.com/@wooleejaan

0개의 댓글