토글(toggle)"은 주로 두 가지 상태 사이를 전환하는 기능으로, 웹 페이지에서 버튼을 클릭할 때마다 내용이 보였다가 숨겨졌다가 하는 등의 상태를 전환하는 것이 토글 기능이다.
1. 토글 메서드 없이
<!DOCTYPE html>
<html>
<head>
<title>Font Awesome 5 Icons</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
.my-cursor {
cursor: pointer;
}
.my-love {
color: red;
}
</style>
</head>
<body>
<i onclick="loveToggle(event)" class="fas fa-heart my-cursor"></i>
<script>
//토글 클래스를 코드로 만들어봄. -1 에 -1 을 곱함.
let check = -1;
// e는 이벤트 객체
function loveToggle(e) {
console.log(e.target);
if (check == -1) {
$(e.target).addClass("my-love");
} else {
$(e.target).removeClass("my-love");
}
check = check * -1;
}
</script>
</body>
</html>
변수 check를 -1 로 두고 , 함수가 실행될 때 마다 -1 을 곱해 상태를 변환한다.

좋아요 버튼을 누르지 않은 상태.

좋아요 버튼을 누르면 css my-love 가 추가되면서 색깔이 변경된다.

다시 좋아요를 누르면 my-love 가 사라지면서 색깔도 돌아온다.
2. toggleClass() 사용
<!DOCTYPE html>
<html>
<head>
<title>Font Awesome 5 Icons</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<style>
.my-cursor {
cursor: pointer;
}
.my-love {
color: red;
}
</style>
</head>
<body>
<i id="love-1" class="fas fa-heart my-cursor"></i>
<script>
//아이디가 없으면 찾을 수 없음. 근데 e를 넣으면 이벤트값이 들어옴.그래서 id가 없어도 이벤트 실행할 수 있음.
$("#love-1").click((e) => {
console.log(e);
$("#love-1").toggleClass("my-love");
});
</script>
</body>
</html>
e
는 이벤트 객체를 나타낸다. 이벤트 객체는 이벤트가 발생했을 때 관련된 정보를 담고 있다. 이벤트 핸들러 함수의 첫 번째 매개변수로 자동으로 전달되며, 이벤트의 종류, 발생 위치, 발생 시점 등 다양한 정보를 확인할 수 있다.

Share article