티스토리 뷰

hide() 와 show()

자바스크립트와 css를 이용해서 숨기기 기능을 넣으려면 이벤트부터 , css property를 display: none/block;로 설정하는 번거로운 작업을 해야 했을텐데, jQuery를 사용하게 되면 이 작업을 보다 간단하게 할 수 있다.

$("#hide").click(function(){
  $("p").hide();
});

$("#show").click(function(){
  $("p").show();
});

Callback 함수 이용하기

Callback method를 사용하면 앞에 제시된 시간이 흐른 뒤에 함수가 실행된다. 이벤트가 종료되었을 시점에 어떤 작업을 수행하라고 명령하고 싶을 때 사용하면 된다.
    예시)  hide(2000, function(){    });

$(selector).hide(speed,callback);
$(selector).show(speed,callback);

예제) element 서히 사라지고, 다 사라진 후에 alert 메시지가 나타나게 한 것 

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#bt1").click(function(){
    $("#p1").hide(2000, function(){alert('test')});
  });
  $("#bt2").click(function(){
    $("#p1").show();
  });
});

</script>
</head>
<body>

<button id="bt1">Hide</button>
<button id="bt2">Show</button>

<p>1 This is a paragraph with little content.</p>
<p id="p1">2 This is a paragraph with little content.</p>
<p>3 This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>

</body>
</html>

Call back method으로 만들어야 일정 시간이 흐른 뒤에 작업이 수행되도록 할 수 있다. UI 에서는 call back method 중요하다고 한다.

Callback method을 사용할 때와 사용하지 않을 때- 구분하도록 하자!

  • Callback method를 사용했을 때는 hide()에 명시된 일정 시간이 흐른 후 callback function의 작업이 실행되지만
  • Callback method를 사용하지 않았을 때는 hide()와 상관없이 뒤의 작업이 실행된다

jQuery toggle

한번 누르면 숨겼다가, 다시 누르면 다시 보여준다.

$("button").click(function(){
  $("p").toggle();
});

toggle에서 위의 함수들과 마찬가지로 callback function을 사용할 수 있다.

$(selector).toggle(speed,callback);

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

jQuery: animate, stop, chaining  (0) 2020.07.30
jQuery: sliding  (0) 2020.07.30
jQuery: Fading  (0) 2020.07.30