티스토리 뷰

WEB/jQuery

[jQuery] toggle()

춘햄 2021. 6. 2. 15:01

toggle() 메서드는 두 가지 함수를 반복해서 수행할 수 있게끔 해주는 메서드이다. (on/off 기능)


메서드는 다음과 같이 사용한다.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>toggle() 메서드로 토글링</title>

<style type="text/css">
.hidden {
	display: none;
}
</style>

<script src="jquery-1.6.2.js" type="text/javascript"></script>

<script type="text/javascript">
	$(document).ready(function() {
		$("#btn").toggle(function() {
			$('#myLayer').addClass('hidden');
		},

		function() {
			$('#myLayer').removeClass('hidden');
		})
	});
</script>
</head>



<body>
	<h1>버튼을 클릭할 때마다 레이어 보이기/숨기기</h1>
	<input id="btn" type="button" value="버튼" />
	<div id="myLayer" style="background-color: Yellow;">안녕</div>
</body>

</html>


위와 같이 스타일만 add, remove하는 방식의 경우는 toggleClass를 사용해도 무방하다.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>toggle() 메서드로 토글링</title>

<style type="text/css">
.hidden {
	display: none;
}
</style>

<script src="jquery-1.6.2.js" type="text/javascript"></script>

<script type="text/javascript">
	$(document).ready(function() {
		$("#btn").click(function() {
        	$('#myLayer').toggleClass('hidden');
		});	
	});
</script>
</head>



<body>
	<h1>버튼을 클릭할 때마다 레이어 보이기/숨기기</h1>
	<input id="btn" type="button" value="버튼" />
	<div id="myLayer" style="background-color: Yellow;">안녕</div>
</body>

</html>

'WEB > jQuery' 카테고리의 다른 글

[jQuery] 이벤트를 최초 한번만 실행하는 one()  (0) 2021.06.02
[jQuery] hover()  (0) 2021.06.02
[jQuery] slice()  (0) 2021.06.02
[jQuery] filter()  (0) 2021.06.02
[jQuery] addClass() & removeClass()  (0) 2021.06.02
Comments