JS 實作 #2 | keypress event ;addEventListener

延續 JS 實作 #1 | 模組化 完成 module 架構後,第一件事是先加入 event listener。

若是鍵盤的沒有綁定DOM,則會指定到整個頁面的按鍵行為:

document.addEventListener('keypress', function(event) {
		
		console.log(event);

});
https://s3-us-west-2.amazonaws.com/secure.notion-static.com/c8ed9a8d-ede0-4294-9d75-46c811a265e8/_2020-03-23_16.50.22.jpg

KeyCode & which

KeyCode 是新型的瀏覽器;而 which 對應到舊型瀏覽器,可以查看以下網址來獲得每個鍵的對應:

document.addEventListener('keypress', function(event) {
		
		if (event.keyCode === 13 || event.which === 13) {
				// 13 是 Enter 鍵的對應
		    ctrlAddItem();
		}

});

完成滑鼠按鈕與鍵盤 enter 綁定

// GLOBAL APP CONTROLLER
var controller = (function(budgetCtrl, UICtrl){

    var ctrlAddItem = function() {
        // 1. Get the field input data
        // 2. add the item to the budget controller
        // 3. add the item to the UI
        // 4. Calculate the budget
        // 5. Display the budget on the UI
    }

    document.querySelector('.add__btn').addEventListener('click', ctrlAddItem);

    document.addEventListener('keypress', function(event) {

        if (event.keyCode === 13 || event.which === 13) {
            ctrlAddItem();
        }

    });
    // Some code

})(budgetController, UIController);

Zeen is a next generation WordPress theme. It’s powerful, beautifully designed and comes with everything you need to engage your visitors and increase conversions.