본문 바로가기

자바스크립트 이벤트 처리 본문

개발/JavaScript

자바스크립트 이벤트 처리

Louisus 2021. 8. 6. 11:20
728x90
  • Inline Events

html 태그 내에서 이벤트 기능 추가

const btn = document.querySelector("#v2')

// 클릭 이벤트 한번 적용
btn.onclick = function() {
}
  • addEventListener('event', () ⇒ {})

다중 이벤트 적용 가능

const btn = document.querySelector('#v3')
btn.addEventListener('click', function() {
})
const input = document.querySelector('input')
input.addEventListener('keydown', function(evt) {
    console.log(evt.key)
    console.log(evt.code)
})

window.addEventListener('keydown', function(e) {
    switch (e.code) {
        case 'ArrowUp':
            console.log("UP");
            break
        default:
            console.log("DE");
    }
})
    <h1>Form Test</h1>
  <form action="#" id="tweetForm">
      <input type="text" name="username" placeholder="username">
      <input type="text" name="tweet" placeholder="tweet">
      <button>Post</button>
  </form>

  <h2>Tweet:</h2>
  <ul id="tweets">

  </ul>

// form tag
const tweetForm = document.querySelector('#tweetForm')
const tweetsContainer = document.querySelector('#tweets')
console.log(tweetForm)
tweetForm.addEventListener('submit', function(e) {
    e.preventDefault()

    // const usernameInput = document.querySelectorAll('input')[0]
    // const tweetInput = document.querySelectorAll('input')[1]
    // console.log(usernameInput.value, tweetInput.value)

    const usernameInput = tweetForm.elements.username.value
    const tweetInput = tweetForm.elements.tweet.value

    addTweet(usernameInput.value, tweetInput.value)
    usernameInput.value = ''
    tweetInput.value = ''
})

const addTweet = (username, tweet) => {
    const newTweet = document.createElement('li')
    const bTag = document.createElement('b')

    bTag.append(username)
    newTweet.append(bTag)
    newTweet.append(`- ${tweet}`)
    tweets.container.append(newTweet)
}
// input
const input = document.querySelector('input')
const h1 = document.querySelector('h1')

input.addEventListener('input', function(e) {
    h1.innerText = input.value
})
  • event bubbling
// tag 안에 여러 액션이 중첩됨
// 'A', 'B', 'C' 모두 alert

<section onclick="alert('A')">
   <p onclick="alert('B')">
      <button onclick="alert('C')"></button>
   </p>
</section>

<div id="container">
        Click Me!
        <button id="changeColor">Change Color!</button>
</div>

const btn = document.querySelector('#changeColor')
const container = document.querySelector('#container')

btn.addEventListener('click', function(e) {
    container.getElementsByClassName.backgroundColor = makeRandColor()
    e.stopPropagation() // 버블링 안생기게 함
})

container.addEventListener('click', function() {
    container.classList.toggle('hide')
})

const makeRandColor = () => {
    const r = Math.floor(Math.random()*255)
    const g = Math.floor(Math.random()*255)
    const b = Math.floor(Math.random()*255)

    return `rgb(${r}, ${g}, ${b})`
}
  • event delegation

새로 추가된 요소에 대해 이벤트 리스너가 자동 적용 안되기 때문에 부모 노드에서 자식노드로 target을 걸어서 모든 새로운 요소에 적용 가능

// 새로 갱신될 경우 적용 안됨
let lis = document.querySelectorAll('li')
for (let li of lis) {
    li.remove()
}

tweetsContainer.addEventListener('click', function (e) {
    e.target.remove() // target => li, parent => ul
    e.target.nodeName === 'LI' && e.target.remove()
})

'개발 > JavaScript' 카테고리의 다른 글

자바스크립트 개념 정리  (0) 2021.08.06
자바스크립트 웹 개발 관련 정리  (0) 2021.08.06
DOM 정리  (0) 2021.08.06
자바스크립트로 AJAX 사용하기  (0) 2021.08.06
Comments