[jQuery] 팝업이 열린 상태의 URL 생성하기

hyejinJo·2023년 5월 24일
0

Javascript / jQuery

목록 보기
2/8
post-thumbnail

특정 페이지의 SNS 등 외부 공유를 위해 URL 링크를 생성하고 싶었다. 링크에 접속하면 특정 팝업이 열린 상태로 페이지가 띄어지는 구조여야 하는데, 해보지 않은 작업이라 애를 좀 먹었다.

해결 방법:

URL 검색창에 내가 정한 [팝업의 id 가 붙은 url] 을 통해 접근하면 거기서 해당 id 를 추출해 그에 해당하는 팝업이 띄워지는 구조로 만들어 해결했다.

html

// "More" 버튼을 클릭하면 해당 팝업창이 뜨는 구조

<section class="main-content">
    <h2>Section</h2>
    <ul>
        <li>
            <div class="desc">
                <h3>Content1</h3>
                <a href="#" class="btnOpen" data-id="1">More</a>
            </div>
        </li>
        <li>
            <img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg" />
            <div class="desc">
                <h3>Content2</h3>
                <a href="#" class="btnOpen" data-id="2">More</a>
            </div>
        </li>
    </ul>
</section>
// 팝업창

<div id="popupWrap" class="popup-wrap">
    <div class="popup-content" data-id="1">
        <button type="button" class="close">
            X
        </button>
        <div class="popup-content-inner">
            <h2 class="title popup-title">Popup1</h2>
          <p>
          	is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages
          </p>
         	<img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg" />
        </div>
    </div>
		<div class="popup-content" data-id="2">
        <button type="button" class="close">
            X
        </button>
        <div class="popup-content-inner">
            <h2 class="title popup-title">Popup2</h2>
            <p>
              type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of 
            </p>
         	<img src="https://cdn.pixabay.com/photo/2014/02/27/16/10/flowers-276014_1280.jpg" />
        </div>
    </div>
</div>

javascript

  1. 검색창에서 접근한 url 의 파라미터를 추출

  2. 파라미터에서 ? 제외

  3. 해당 파라미터를 자바스크립트 객체로 만들어 key 값으로 팝업 id 추출

    출처: URL 파라미터를 JavaScript 객체로 변환하는 방법

  4. 추출한 팝업 id 에 해당하는 팝업을 찾아 띄움

$(document).ready(function (){
  // url 의 파라미터를 추출, 파라미터에서 '?' 제외
  var search = location.search.substring(1);
  console.log(search)
  if (search) { // 파라미터가 있을 시
    // 파라미터 객체화
    search = JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
    if (search.id && $('#popupWrap').find("[data-id="+search.id+"]").length){
      modalOpen(search.id) // [파라미터 객체에서 찾은 id] 에 해당하는 팝업 열기
    }
  }
  $('.btnOpen').click(function(e){
    e.preventDefault()
    console.log($(this).data('id'))
    modalOpen($(this).data('id'))
  })
  $('.popup-content .close').click(function(){
    $(this).closest('.popup-content').removeClass('active').closest('#popupWrap').removeClass('active');
    $('body').removeClass('overflow-hidden')
  })
})

function modalOpen(id){
  console.log('modalOpen',id)
  $('#popupWrap').addClass('active').find("[data-id="+id+"]").addClass('active').show();
  $('#popupWrap').find("[data-id="+id+"]").siblings().hide()
  $('body').addClass('overflow-hidden')
}

예시:

아무 사이트에 접속한 후 console 에 다음의 코드를 사용하면 추출된 문자형 파라미터가 객체화된 것을 알 수 있다.

결과:

첫 번째 링크를 열면 id 값이 1인 팝업이 띄워지고, 두 번째 링크를 열면 id 가 2인 팝업 띄워진다. (실제가 아닌 예시 링크와 이미지)

profile
FE Developer 💡

2개의 댓글

comment-user-thumbnail
2024년 1월 29일

님 안녕하세요. 제가 해결하고 싶은 문제를 미리 고민해 주셨는데 https://www.sapy.kr/QnAlab 이 페이지에서 문답연구단 버튼 누를 시 뜨는 팝업 URL 도 추출 가능할까요? 저도 해보고 싶은데... 혹시 도움을 주실 수 있는지 궁금합니다 >.. <

답글 달기
comment-user-thumbnail
2024년 1월 29일

저는 디자이너라 자바 스크립트 관련해서는 지식이 없는데 어려울까요?

답글 달기