본문 바로가기
Library & Framework/jQuery

[jQuery] 드래그 가능한 리스트 목록 만들기 (ft. jQuery UI - sortable)

by 썸머워즈 2020. 10. 3.
반응형

- 드래그 가능한 리스트 목록 만들기 -


<ul> ~ <li> 태그로 이루어진 리스트로 (꼭 이 구조가 아니여도 된다.)

드래그로 순서를 바꿀수 있는 목록을 만들어 보도록 하자.

드래그 기능은 jQeury UI에서 제공해주고 있는 sortable() 메서드를 사용할 것이다.

 

실제 코드를 봐보자.

▷ 드래그 가능한 리스트 만들기 코드

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
   <link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
   <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
   <script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" ></script>
</head>
<style>
    ul li{
        list-style: none;
        width: 200px;
        height: 30px;
        font-size: 20px;
    }
    li:hover {
        cursor: pointer;
    }

    .itemBoxHighlight {
        border:solid 1px black;
        width:200px;
        height:30px;
        background-color:yellow;
    }
</style>
<body>
<h1>mine-it-record</h1>
<ul id="sortable">
  <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span><span class="inner">mine 1</span></li>
  <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span><span class="inner">mine 2</span></li>
  <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span><span class="inner">mine 3</span></li>
  <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span><span class="inner">mine 4</span></li>
  <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span><span class="inner">mine 5</span></li>
</ul>
</body>
<script>
    //$("#sortable").sortable();
    //$("#sortable").disableSelection(); // 아이템 내부의 글자를 드래그 해서 선택하지 못하도록 하는 기능

    $("#sortable").sortable({
        placeholder:"itemBoxHighlight", /* 이동할 위치 css 적용  */
        start:function(event,ui){
            // 드래그 시작 시 호출
        },
        stop:function(event,ui){
            // 드래그 종료 시 호출
            reorder();
        }
   });

    /* 번호 재입력(내부적으로) */
    function reorder() {
        $("#sortable li").each(function(i, box) {
            $(box).val(i + 1);
        });
    }
</script>
</html>

 

위와 같이 구성을 해놓고 실행해보면 화면은 다음과 같다.


이제 위 코드에 대해 상세하게 알아보도록 하자.

 

위 예제는 jQeuryUI 홈페이지에서도 제공해주는 소스코드이다.

https://jqueryui.com/sortable/

 

Sortable | jQuery UI

Sortable Reorder elements in a list or grid using the mouse. Enable a group of DOM elements to be sortable. Click on and drag an element to a new spot within the list, and the other items will adjust to fit. By default, sortable items share draggable prope

jqueryui.com

 

sortable() 이라는 메서드 안에는 많은 옵션들이 존재하는데

그 중에서도 위 코드에서 사용한 placeholder 옵션과, start, stop 옵션에 대해 알아보자면

 

 $("#sortable").sortable({
   placeholder:"itemBoxHighlight", /* 이동할 위치 css 적용  */
   start:function(event,ui){
   	// 드래그 시작 시 호출
   },
   stop:function(event,ui){
     // 드래그 종료 시 호출
     reorder();
   }
 });

 

placeholder 는 주석에 쓰여있는것처럼 itemBoxHighlight 라는 이름을 주어 css를 적용시키기 위함이다.

이 css는 마우스 드래그를 했을때 이동될 영역 즉, 이미지에서 보여지는 노란색 부분이 해당 css와 placeholder를 의미하는것이다.

 

start 와 stop은 말 그대로 드래그의 시작과 종료 시점을 의미하며 제어가 가능하다.

 

좀 더 다양한 옵션들은 아래 링크를 통해 확인해보도록 하자

https://api.jqueryui.com/sortable/

 

Sortable Widget | jQuery UI API Documentation

Description: Reorder elements in a list or grid using the mouse. The jQuery UI Sortable plugin makes selected elements sortable by dragging with the mouse. Note: In order to sort table rows, the tbody must be made sortable, not the table. Theming The sorta

api.jqueryui.com

 

그리고 소스 마지막에 reorder라고 정의한 부분이 있는데

꼭 필요한 건 아니고 순서 값이 필요해 넣어둔 메서드이다.

 

/* 번호 재입력(내부적으로) */
function reorder() {
  $("#sortable li").each(function(i, box) {
 	 $(box).val(i + 1);
  });
}

반응형


댓글

TOP