개발공작소
article thumbnail
728x90

 

 

 

 

 

이번에 동기가 드래그 앤 드롭 기능을 구현하는 것을 보았는데, 생각해보니 나도 드래그 앤 드롭으로
뭘 만들어 본 적이 없어서 이번에 그냥 재미삼아 만들어 보려고 한다.
실제 이것저것 만드는 기능은 바닐라js로 만들 생각이지만, 제이쿼리에 sortable 함수도 있길래 그냥
간단히 정리만 해보려고 한다.

 

아래와 같은 목차로 진행되니 보도록 하자.

 

  • 기본문법
  • 예제
  • 그외 sortable의 편리한 속성들

 

 

제이쿼리의 sortable 함수를 활용한 드래그 앤 드롭 구현

 

당연하지만 제이쿼리의 함수를 사용하는 것이기 때문에, 제이쿼리 라이브러리를 추가해줘야 한다.

cdn을 남겨놓을테니 필요한 사람은 가져다 쓰도록 하자.

 

 

제이쿼리 cdn코드

<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js" integrity="sha256-xLD7nhI62fcsEZK2/v8LsBcb4lG7dgULkuXoXB/j91c=" crossorigin="anonymous"></script>

 

 

기본문법

$([열에 해당하는 컬럼]).sortable({
    items : $([행에 해당하는 컬럼])
});

//열에 해당하는 컬럼 : <table>에서 <tr>과 같은 값을 의미
//행에 해당하는 컬럼 : <table>에서 <td>과 같은 값을 의미

 

샘플

<table>
    <tr id="trValue">
        <td class="tdValue">첫번째 항목</td>
        <td class="tdValue">두번째 항목</td>
        <td class="tdValue">세번째 항목</td>
        <td class="tdValue">네번째 항목</td>
    </tr>
</table>

<script>
    $('#trValue').sortable({
    	items : $('.tdValue')
    });
</script>

 

 

샘플코드

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<!-- 부트스트랩 및 제이쿼리 cdn 코드 시작 -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js" integrity="sha256-xLD7nhI62fcsEZK2/v8LsBcb4lG7dgULkuXoXB/j91c=" crossorigin="anonymous"></script>
<!-- 부트스트랩 및 제이쿼리 cdn 코드 종료 -->
<style>
	.btn-toggle-nav {
		width : 150px;
	}
	
	body {
	  min-height: 100vh;
	  min-height: -webkit-fill-available;
	}
	
	html {
	  height: -webkit-fill-available;
	}
	
	main {
	  display: flex;
	  flex-wrap: nowrap;
	  height: 100vh;
	  height: -webkit-fill-available;
	  max-height: 100vh;
	  overflow-x: auto;
	  overflow-y: hidden;
	}
	
	.b-example-divider {
	  flex-shrink: 0;
	  width: 1.5rem;
	  height: 100vh;
	  background-color: rgba(0, 0, 0, .1);
	  border: solid rgba(0, 0, 0, .15);
	  border-width: 1px 0;
	  box-shadow: inset 0 .5em 1.5em rgba(0, 0, 0, .1), inset 0 .125em .5em rgba(0, 0, 0, .15);
	}
	
	.bi {
	  vertical-align: -.125em;
	  pointer-events: none;
	  fill: currentColor;
	}
	
	.dropdown-toggle { outline: 0; }
	
	.nav-flush .nav-link {
	  border-radius: 0;
	}
	
	.btn-toggle {
	  display: inline-flex;
	  align-items: center;
	  padding: .25rem .5rem;
	  font-weight: 600;
	  color: rgba(0, 0, 0, .65);
	  background-color: transparent;
	  border: 0;
	}
	.btn-toggle:hover,
	.btn-toggle:focus {
	  color: rgba(0, 0, 0, .85);
	  background-color: #d2f4ea;
	}
	
	.btn-toggle::before {
	  width: 1.25em;
	  line-height: 0;
	  content: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='rgba%280,0,0,.5%29' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M5 14l6-6-6-6'/%3e%3c/svg%3e");
	  transition: transform .35s ease;
	  transform-origin: .5em 50%;
	}
	
	.btn-toggle[aria-expanded="true"] {
	  color: rgba(0, 0, 0, .85);
	}
	.btn-toggle[aria-expanded="true"]::before {
	  transform: rotate(90deg);
	}
	
	.btn-toggle-nav a {
	  display: inline-flex;
	  padding: .1875rem .5rem;
	  margin-top: .125rem;
	  margin-left: 1.25rem;
	  text-decoration: none;
	}
	.btn-toggle-nav a:hover,
	.btn-toggle-nav a:focus {
	  background-color: #d2f4ea;
	}
	
	.scrollarea {
	  overflow-y: auto;
	}
	
	.fw-semibold { font-weight: 600; }
	.lh-tight { line-height: 1.25; }
</style>
<body>
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
  <symbol id="bootstrap" viewBox="0 0 118 94">
    <title>Bootstrap</title>
    <path fill-rule="evenodd" clip-rule="evenodd" d="M24.509 0c-6.733 0-11.715 5.893-11.492 12.284.214 6.14-.064 14.092-2.066 20.577C8.943 39.365 5.547 43.485 0 44.014v5.972c5.547.529 8.943 4.649 10.951 11.153 2.002 6.485 2.28 14.437 2.066 20.577C12.794 88.106 17.776 94 24.51 94H93.5c6.733 0 11.714-5.893 11.491-12.284-.214-6.14.064-14.092 2.066-20.577 2.009-6.504 5.396-10.624 10.943-11.153v-5.972c-5.547-.529-8.934-4.649-10.943-11.153-2.002-6.484-2.28-14.437-2.066-20.577C105.214 5.894 100.233 0 93.5 0H24.508zM80 57.863C80 66.663 73.436 72 62.543 72H44a2 2 0 01-2-2V24a2 2 0 012-2h18.437c9.083 0 15.044 4.92 15.044 12.474 0 5.302-4.01 10.049-9.119 10.88v.277C75.317 46.394 80 51.21 80 57.863zM60.521 28.34H49.948v14.934h8.905c6.884 0 10.68-2.772 10.68-7.727 0-4.643-3.264-7.207-9.012-7.207zM49.948 49.2v16.458H60.91c7.167 0 10.964-2.876 10.964-8.281 0-5.406-3.903-8.178-11.425-8.178H49.948z"></path>
  </symbol>
</svg>

<div class="flex-shrink-0 p-3 bg-white" style="width: 280px;">
    <a href="/" class="d-flex align-items-center pb-3 mb-3 link-dark text-decoration-none border-bottom">
      <svg class="bi me-2" width="30" height="24"><use xlink:href="#bootstrap"></use></svg>
      <span class="fs-5 fw-semibold">Collapsible</span>
    </a>
    <ul class="list-unstyled ps-0">
      <li class="mb-1">
        <button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#home-collapse" aria-expanded="false">
          Home
        </button>
        <div class="collapse" id="home-collapse" style="">
          <ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
            <li><a href="#" class="link-dark rounded">홈텍스트1</a></li>
            <li><a href="#" class="link-dark rounded">홈텍스트2</a></li>
            <li><a href="#" class="link-dark rounded">홈텍스트3</a></li>
          </ul>
        </div>
      </li>
      <li class="mb-1">
        <button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#dashboard-collapse" aria-expanded="false">
          Dashboard
        </button>
        <div class="collapse" id="dashboard-collapse" style="">
          <ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
            <li><a href="#" class="link-dark rounded">대시보스텍스트1</a></li>
            <li><a href="#" class="link-dark rounded">대시보스텍스트2</a></li>
            <li><a href="#" class="link-dark rounded">대시보스텍스트3</a></li>
            <li><a href="#" class="link-dark rounded">대시보스텍스트4</a></li>
          </ul>
        </div>
      </li>
      <li class="mb-1">
        <button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#orders-collapse" aria-expanded="false">
          Orders
        </button>
        <div class="collapse" id="orders-collapse" style="">
          <ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
            <li><a href="#" class="link-dark rounded">오더텍스트1</a></li>
            <li><a href="#" class="link-dark rounded">오더텍스트2</a></li>
            <li><a href="#" class="link-dark rounded">오더텍스트3</a></li>
            <li><a href="#" class="link-dark rounded">오더텍스트4</a></li>
          </ul>
        </div>
      </li>
      <li class="border-top my-3"></li>
      <li class="mb-1">
        <button class="btn btn-toggle align-items-center rounded collapsed" data-bs-toggle="collapse" data-bs-target="#account-collapse" aria-expanded="false">
          Account
        </button>
        <div class="collapse" id="account-collapse">
          <ul class="btn-toggle-nav list-unstyled fw-normal pb-1 small">
            <li><a href="#" class="link-dark rounded">New...</a></li>
            <li><a href="#" class="link-dark rounded">Profile</a></li>
            <li><a href="#" class="link-dark rounded">Settings</a></li>
            <li><a href="#" class="link-dark rounded">Sign out</a></li>
          </ul>
        </div>
      </li>
    </ul>
  </div>
  
	<script>
		$('.btn-toggle-nav').sortable({
			items : $('.link-dark')
		});
	</script>
</body>
</html>

 

 

결과화면

 

<좌> 기본정렬 
<우> 드래그 앤 드롭으로 정렬순서 변경

 

 

 

그외 sortable 함수의 편리한 속성

 

$([열에 해당하는 컬럼]).sortable({
    items : $([행에 해당하는 컬럼]),
    axis : 'x' // x축 또는 y축으로 설정
    start:function(event, ui){
        console.log("드래그를 시작하였습니다.");
        console.log(ui.item.index()); // 인자 ui를 이용하여 드래그와 드랍 위치값을 구할 수 있다.
    },
    stop:function(event, ui){
        console.log("드랍 하였습니다.");
        console.log(ui.item.index());
    },
    update: function(event,ui) { // 변경이 일어났을 때 호출하는 함수
    	console.log("변경이 감지 되었습니다.");
    }
});

 

 

 

제이쿼리 sortable함수 참조하기 좋은 사이트 링크

 

https://johnny.github.io/jquery-sortable/

 

jQuery Sortable

Sort vertically Define the nested containers differently Exclude some items from being sortable Heads Up! The itemSelector should always match every sibling of any item. If you want to exclude some items, use the exclude option. See the first example here

johnny.github.io

 

728x90
profile

개발공작소

@모찌바라기

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!