5
13

More than 1 year has passed since last update.

Vanilla.js チートシート

Last updated at Posted at 2023-05-08

ネイティブのJavaScriptを記述する際に個人的によく確認するもののチートシート

要素の指定

id

document.getElementById('idName')

class

document.getElementsByClassName('className')

要素

document.querySelector('selectorName')
document.querySelectorAll('selectorName')

絞り込み

document.getElementById('idName').getElementsByClassName('className')

親要素

function onClickItem(e) {
  const target = e.target;
  const parent = target.parentNode;
}
function onClickItem(e) {
  const target = e.target;
  const parent = target.closest('selectorName');
}

スクロール位置

const scroll = {};
scroll.x = window.scrollX || window.pageXOffset || document.documentElement.scrollLeft;
scroll.y = window.scrollY || window.pageYOffset || document.documentElement.scrollTop;
console.log({ scroll });

要素の大きさ・位置

const target = {};
function getTargetPosition(element) {
  const clientRect = element.getBoundingClientRect();
  target.height = element.offsetHeight;
  target.width = element.offsetWidth;
  target.x = clientRect.left;
  target.y = clientRect.top;
}
getTargetPosition(document.getElementById('idName'));
console.log({ target });

footer要素が見えている時はhtml要素に .view-footer を付与

const footerElement = document.getElementById('js-footer');
const ioFooter = new IntersectionObserver((entries) => {
  if (entries[0].isIntersecting) {
    // console.log('footer view');
    document.documentElement.classList.add('view-footer');
  } else {
    // console.log('footer leave');
    if (document.documentElement.classList.contains('view-footer')) {
      document.documentElement.classList.remove('view-footer');
    }
  }
});
ioFooter.observe(footerElement);

.c-observeItem 要素が見えたら .is-view を付与

const observeElements = document.getElementsByClassName('c-observeItem');
const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      if (!entry.target.classList.contains('is-view')) {
        entry.target.classList.add('is-view');
      }
    }
  });
}, {
  root: null,
  rootMargin: `-${window.innerHeight / 5}px 0px`, // ウィンドウの下から20%で発火
  threshold: [0]
});
if (observeElements) {
  for (let i = 0; i < observeElements.length; i += 1) {
    observer.observe(observeElements[i]);
  }
}
5
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
13