토글은 주로 두가지 상태 사이를 전환하는 기능으로, 웹 페이지에서 버튼을 클릭 할 때 마다 내용이 보여졌다가 숨겨졌다가 하는 등의 상태를 전환하는것이 토글 기능이다.
토글 메서드 없이 로우한 코드
<!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>
하트를 안 눌렀을 때

fas fa-heart my-cursor의 색깔이 검은색

하트를 눌렀을 때

fas fa-heart my-cursor의 색깔이 빨간색
my-love가 추가 되면서 색상이 빨간색으로 변했다.

하트를 다시 눌렀을 때

fas fa-heart my-cursor의 색깔이 검은색
my-love가 빠지면서 다시 색이 돌아온다.

toggloeClass( )를 사용한 코드
<!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>
$("#love-1").click((e) => {
console.log(e);
$("#love-1").toggleClass("my-love");
});
</script>
</body>
</html>
e 는 이벤트가 발생할 때 자동으로 전달되는 이벤트 객체다.
이벤트 핸들러 함수의 첫 번째 매개변수로 자동 전달 되고, 이벤트의 종류, 위치, 발생 시점 등 다양한 정보를 확인 할 수 있다.
하트를 안 눌렀을 때


하트를 눌렀을 때


하트를 다시 눌렀을 때


Share article