バニラjavascriptを書くのにざっと使ったもの
class名で要素を取得
document.getElementsByClassName('クラス名');
HTMLCollection 要素として返ってくるので配列として使えない。
カスタムデータ
// class name の場合
document.querySelector(".className");
document.querySelectorAll(".className"); //複数の場合
タグで取得
document.getElementsByTagName('タグ名');
id名で要素を取得
document.getElementById("className");
イベントリスナー
document.addEventListener( 'DOMContentLoaded', function()
{
}, false );
openBtn.addEventListener('click', () => {
});
//複数の時、それぞれに指定
for (var i = 0; i < closeBtn.length; i++) {
closeBtn[i].addEventListener('click', () => {
})
}
//上記書き方変更
for(const value of closeBtn.entries()) {
}
//resize
window.addEventListener('resize', () => {
this.checkDevice();
});
window.addEventListener('resize', this.checkDevice);
// 要素読み込み
document.addEventListener("DOMContentLoaded", function() {
});
document.addEventListener("DOMContentLoaded", this.setting);
class remove add hasClass
BODY.classList.remove(OPEN_CLASS);
BODY.classList.add(OPEN_CLASS);
BODY.classList.contains(OPEN_CLASS); // hasClass // true or false
attr 系
//set
var imgscr = elm.getAttribute("data-src");
elm.setAttribute("src", imgscr);
// get
elm.getAttribute('data')
or
elm.attributes['data'].value
find系
普通にdocumentから始めず、制限したい要素から付ける
getElementById('wrapper').querySelector(".pageImage")
特定の要素
html
document.documentElement;
document.body;
offset
var myTop = $("#main").offset().top
//書き換え JavaScript
var myMain = document.getElementById("main");
var rect = myMain.getBoundingClientRect();
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
var myTop = rect.top + scrollTop;
// matome
document.getElementById(value.getAttribute("href")).getBoundingClientRect().top + (window.pageYOffset || document.documentElement.scrollTop);
wight
バニラってわけじゃないけど
// window
var windowWidth = (window.innerWidth || document.documentElement.clientWidth || 0);
var windowHeight = (window.innerHeight || document.documentElement.clientHeight || 0);
// element
var elmHeight = element.clientHeight;
next()
const nextElem = (node, selector) => {
if (selector && document.querySelector(selector) !== node.nextElementSibling) {
return null;
}
return node.nextElementSibling;
};
nextElem(elem);
scroll eventの計算のやつ
let last_known_scroll_position = 0;
let ticking = false;
function doSomething(scroll_pos) {
// Do something with the scroll position
last_known_scroll_position = window.window.scrollY ? window.scrollY : window.pageYOffset;;
}
window.addEventListener('scroll', () => {
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(last_known_scroll_position);
ticking = false;
});
ticking = true;
}
});