■ EventListener
EventListener란?
document.getElementById('어쩌구').addEventListener('click', function(){
//실행할 코드
});
이벤트리스너는 웹페이지나 앱에서 발생하는 이벤트를 감지하고 처리하는 매커니즘으로
특정 이벤트가 발생했을 때 원하는 동작이 실행되도록 할 수 있습니다.
셀렉터로 요소를 선택한 뒤에 addEventListener() 메서드로 등록할 수 있습니다.
이벤트리스너는 2개의 파라미터를 가지고 있는데, 하나는 이벤트, 하나는 함수입니다.
Event 와 콜백함수
이벤트리스너는 2개의 파라미터를 가지고 있습니다.
이벤트에는 click(클릭), mouseover(마우스를 위로 올림), scroll(스크롤), keydown(키 입력) 등이 있습니다.
그리고 이벤트 외에 함수가 파라미터 자리에 들어가는데, 이렇게 파라미터 자리에 들어가는 함수를 콜백함수라고 부르며
보통 함수와는 다르겍 작명을 하지 않습니다.
■ classList
classList 를 활용한 class 추가
document.querySelectorAll('.navbar-toggler')[0].addEventListener('click', function ()
{
document.querySelectorAll('.list-group')[0].classList.toggle('show');
});
원하는 클래스를 추가하고 싶을 때나 제거하고 싶을 때는 classList 속성을 활용할 수 있습니다.
classList.add('클래스명') 을 붙이면 클래스를 추가하고,
classList.remove('클래스명') 을 붙이면 클래스를 삭제합니다.
classList.toggle('클래스명') 은 클래스명이 있을 경우 제거하고, 클래스명이 없으면 추가해줍니다.
querySelector
위의 예제 코드에서 선택자로 querySelector을 활용한 것을 볼 수 있습니다.
querySelector('요소') 는 id 나 class 관계 없이 선택할 수 있는 셀렉터로 .클래스명, #아이디명으로 찾는 것이 가능합니다.
querySelectorAll('요소')[x] 도 있는데 그냥 querySelector는 맨 위의 한 개 요소만 선택하는데,
querySelectorAll 은 중복된 클래스나 아이디 중에서 x 번째 요소를 찾을 수가 있습니다.
■ jQuery
html 변경
<p class="hello">안녕</p>
<p class="hello">안녕</p>
<script>
$('.hello').html('잘가');
$('.hello').eq(1).html('또만나');
</script>
jQuery는 셀렉터를 $('요소') 로 짧게 줄일 수 있다는 특징이 있습니다.
jQuery는 전용 함수를 사용해야 하며 일반 자바스크립트 함수를 사용할 수 없습니다.
그리고 셀렉터로 찾은 모든 요소를 한 번에 조작하고 변경한다는 특징도 있습니다.
여러 요소 중 하나만 찾아서 쓰고 싶을 때는 뒤에 .eq(x)를 쓰면 x 번째 요소를 선택해줍니다.
css 변경
<p class="hello">안녕</p>
<script>
$('.hello').css('color', 'red');
</script>
class 탈부착
<p class="hello">안녕</p>
<script>
$('.hello').addClass('클래스명');
$('.hello').removeClass('클래스명');
$('.hello').toggleClass('클래스명');
</script>
EventListener
<p class="hello">안녕</p>
<button class="test-btn">버튼</button>
<script>
$('.test-btn').on('click', function(){
어쩌구~
});
</script>
UI 애니메이션
<p class="hello">안녕</p>
<button class="test-btn">버튼</button>
<script>
$('.test-btn').on('click', function(){
$('.hello').hide();
});
</script>
CSS 로 줄 수 있는 애니메이션 효과를 간단하게 주는 것도 가능합니다.
hide는 사라짐, fadeOut 는 서서히 사라짐, slideUp 은 줄어들며 사라짐... 등 여러 효과가 있습니다.
'JavaScript' 카테고리의 다른 글
JavaScript(스크롤 이벤트) (0) | 2023.05.18 |
---|---|
JavaScript(정규식, return, 소수점) (0) | 2023.05.18 |
JavaScript(변수, 타이머) (0) | 2023.05.17 |
JavaScript(조건문, input 태그의 이벤트) (0) | 2023.05.17 |
JavaScript(셀렉터, UI 만들기, function) (1) | 2023.05.17 |