[JS] 체크일때만 링크 활성화

2021. 11. 17. 15:14Javascript/이벤트

<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>체크일때만 링크 활성화</title>
</head>
<style>

</style>
<body>
<input type="checkbox">
<span>링크 활성화</span>
<br>
<a href="http://www.naver.com">네이버</a>
<script>
  document.addEventListener('DOMContentLoaded', () => {
      const checkbox = document.querySelector('input')
      const link = document.querySelector('a')
      let state = false

      checkbox.addEventListener('change', event => {
          state = event.target.checked
      })

      link.addEventListener('click', event => {
          if (!state) event.preventDefault()
      })
  })
</script>
</body>
</html>

 

'Javascript > 이벤트' 카테고리의 다른 글

[JS] 이벤트 연결 (증가/감소)  (0) 2022.02.05
[JS] 이벤트 연결 해제  (0) 2022.02.04
[JS] reset 버튼  (0) 2022.01.20
[JS] 우클릭방지  (0) 2021.11.17