javascriptイベント操作
1:HTML属性を使う方法(埋め込む)
<div class="btn" onclick="alert('サンプル')"></div>
2:イベントプロパティを使う方法:要素.イベントハンドラ:イベントの追加登録は不可
ex: document.getElementById('hoge').onclick();
3:EventTarget.addEventListener('イベント',実行関数,false);イベント追加登録が可能
//CODE
element.addEventListener('click', myClickHandler, {
once: true,//一度だけ
passive: true,//スマホ対応
capture: true
});
単にtrue、flaseの場合は、capture
true = キャプチャリング → 下の要素ににクリックイベントが伝播
バブリング → 上の要素ににクリックイベントが伝播
EventTarget.addEventListener('イベント',実行関数,false);
//イベントだけ渡す
function listener(e){
console.log(e.target);
}
//イベント以外にも値を渡す
function listener(color){
return function(e){
e.target.style.backgroundColor = color;
}
}
EventTarget.addEventListener('click',listener("red"),false);
EventTarget.addEventListener()
注意)イベントターゲットで使えるハンドラが違う
例えば、selectionchange イベントは、documentにはあるけど、Elementにはない!
またElementには、selectイベントはあるが、inputやtextareaのみ発生。contenteditableなエリアでは拾えない。
イベント一覧参考
//CODE
//イベント一覧
click マウスがクリックされた場合
keydown キーボードが押された場合
keyup キーボードが離された場合
mousedown マウスボタンが押された場合
mouseup マウスボタンが離された場合
mousemove マウスカーソルが移動した場合
mouseover マウスカーソルがオブジェクトに重なった場合
mouseout マウスカーソルがオブジェクトから離れた場合
onLoad ページが読み込まれた場合
onUnload 他のページに移動する場合
-------------
focus 選択された状態になった場合
blur フォーカスを失った場合
-------------
submit フォームがサブミットされた場合
reset フォームがリセットされた場合
change フォームの内容が変更された場合
-------------
resize ウインドウがリサイズされた場合
abort イメージの読み込みが中断された場合
error 読み込みが失敗した場合
load Webページの読み込みが完了した時に発動(画像などのリソースすべて含む)
-------------
以下、実験的な機能
paste
cut
copy
-------------
削除(removeEventListener)
- -> EventTarget.removeEventListener
- ->
- ->
- ->
//登録
element.addEventListener("mousedown", handleMouseDown, true);
//削除
element.removeEventListener("mousedown", handleMouseDown, false); // 失敗
element.removeEventListener("mousedown", handleMouseDown, true); // 成功
イベントの登録(addEventListener)と
参考:
window.addEventListener('click', function() { console.log(1); }, false);
window.addEventListener('click', function() { console.log(2); }, false);
var handler = (function(){
var events = {},
key = 0;
return {
addListener: function(target, type, listener, capture) {
target.addEventListener(type, listener, capture);
events[key] = {
target: target,
type: type,
listener: listener,
capture: capture
};
return key++;
},
removeListener: function(key) {
if(key in events) {
var e = events[key];
e.target.removeEventListener(e.type, e.listener, e.capture);
}
}
};
}());
var key = handler.addListener(window, 'click', (function(x) {
return function() { console.log(x); }
})(1), false);
操作検知
//json
$(function(){
function timer_func(){
location.href='10分後の移動先';
}
var time_limit=10*60*1000; //制限時間
var timer_id=setTimeout(timer_func, time_limit);
//拾うイベントは追加・調整もできます
$('body').on('keydown mousedown',function(){
clearTimeout(timer_id);
timer_id=setTimeout(timer_func, time_limit);
});
});
//自動リロード
const timer = 60000 // ミリ秒で間隔の時間を指定
window.addEventListener('load',function(){
setInterval('location.reload()',timer);
});
//特定入力作業中は、リロード中断
//自動リロード
//リロードカウンター中断関数
//リロード再スタート中断関数
function handleEvent (event) { console.log(event); }
var element = document.querySelector('body');
element.addEventListener('mousedown', handleEvent, false);
element.addEventListener('touchstart', handleEvent, false);
Window幅でのリサイズ検知
// ロード時のウインドウ幅を基準として記録。
// iosでスクロール時にもresizeイベントが発生するので、ウインドウ幅が変化していたら実行するようにする。
// ピンチ操作の時には、連続で動作してしまうので、タイマーで連続のイベントを間引く。
//【重要】タイマー直後に基準のウインドウ幅をリセット。
//vanilla.js
;(function() {
})();
//ほぼ、vanilla.js jqueryも対応
;(function($, undefined) {
let timer = 0;
let wW,wH;
let cW = window.innerWidth;
window.onresize = function () {
wW = window.innerWidth;
if (timer > 0) {
clearTimeout(timer);//clear timer
}
timer = setTimeout(function () {
if(cW !== wW) {
cW = window.innerWidth;
wH = window.innerHeight;
//ここに処理記述
};
}, 300);
};
})(jQuery);
スクロールイベント
//vanilla.js
//scroll
var timer = null;
function func() {
clearTimeout(timer);
timer = setTimeout(function () {
// 処理
// do something
}, 16);
}
document.addEventListener("scroll", func, { passive: true });
リサイズの最初と最後
//苦無忍者で安定して動作しているけど、メモリー負荷とか
//開始用タイマー
let starttimer;
//終了タイマー
let endtimer = 0;
$window.on(op.resize, function(){
clearTimeout(starttimer); // for start timer clear
if (endtimer > 0) clearTimeout(endtimer);//for end timer clear
// for start action
starttimer = setTimeout( function () {
$t.each(function() {
nuku($(this),op);
});
},20);
// for end action
endtimer = setTimeout(function () {
if(kunaiisShow($t)) {
resizeHandler($t,op);
};
}, 300);
});