[Bootstrap] 부트스트랩 모달 열었을 때 커서 깜빡임 속성 [= focus()] 주기

2022. 12. 16. 10:16·🚀 from error to study/Java

 

 

 

 

 

 


💡 현재 상황

코멘트를 수정하기 위해 부트스트랩을 사용해 모달창을 띄웠음

그냥 띄워 주기만 하니까 안내창이랑 별반 다르게 보이지 않아 코멘트 수정 내용을 입력하는 곳에 커서 깜빡임 효과를 주고 싶음

근데 onclick을 사용해 모달이 띄워진 시점에 $("#모달아이디값").find("#textarea아이디값").focus() 을 주니 먹히지 않음

 

 

 

📍 해결 방법

부트스트랩 모달이 사용자에게 보여질 때를 집어 이벤트를 주면 됨

모달이 열리고 나서 자동으로 실행되는 이벤트 속성인 shown.bs.modal을 이용하여 해결함

 

이벤트 타입 설명
show.bs.modal 모달이 열릴 때 바로 실행되는 이벤트
shown.bs.modal 모달이 열리고 나서(열림이 끝났을 때) 실행되는 이벤트
hide.bs.modal 모달이 닫힐 때 바로 실행되는 이벤트
hidden.bs.modal 모달이 닫히고 나서(모달의 닫힘이 끝났을 때) 실행되는 이벤트

 

 

 

 

⏳ 코드의 흐름 파악하기

 

💻 1. 페이지에서 수정 버튼을 누르면

<button type="button" id="updateMyCommentButton" data-toggle="modal" data-target="#myCommentModal">수정</button>

 

 

 

💻 2. 코멘트 수정 모달창이 뜸

<!-- 코멘트 수정 모달창 -->
<form id="updateMyCommentForm" action="" method="post" name="updateMyCommentForm">
  <div class="modal fade" id="myCommentModal">
    <div class="modal-dialog modal-xl">
      <div class="modal-content">

        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title" style="color:black;">코멘트 수정</h4>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>

        <!-- Modal body -->
        <div class="modal-body">
          <textarea id="updateMyComment" name="updateMyComment" style="width:1100px; resize:none;" autofocus>${ myComment.reviewContent }</textarea>
        </div>

        <!-- Modal footer -->
        <div class="modal-footer">
            <input type="hidden" name="myReviewNo" id="myReviewNo" value="${ myComment.reviewNo }">
            <button type="button" class="btn btn-danger" data-dismiss="modal" onclick="myCommentSubmit(3);">수정</button>
            <button type="button" class="btn" data-dismiss="modal">취소</button>
        </div>

      </div>
    </div>
  </div>
</form>

 

 

 

💻 3. 코멘트 수정 모달창에서 수정 버튼을 누르면 모달창을 감싼 form 태그의 값이 controller로 넘어감

 function myCommentSubmit(num) {
				        	
    const myReviewNo = $("#commentArea").find("#myReviewNo").val();
    const myComment = $("#commentArea").find("#myCommentTextarea").val();

    // console.log(myReviewNo);
    // console.log(myCommentTextarea);

    if(num == 1) {

        // console.log("작성 버튼 클릭");

        if(confirm("작성한 코멘트를 등록하시겠습니까?")) {

            $.ajax({

                url : "insertMyComment.co",
                data : {
                    myReviewNo : myReviewNo,
                    myComment : myComment
                },
                type : "post",
                success : function(result) {

                    if(result > 0) {

                        alert("코멘트가 성공적으로 등록되었습니다!");
                        location.reload();

                    } else {

                        alert("코멘트 작성에 실패하였습니다. 잠시 후 다시 시도해 주세요.");
                        location.reload();

                    }

                },
                error : function() {

                    console.log("코멘트 작성용 ajax 통신 실패!");

                }

            });
        }

    } else if(num == 2) {

        console.log("삭제 버튼 클릭");

        if(confirm("코멘트를 삭제하시겠습니까?")) {

            $("#starScoreArea").attr("action", "deleteMyComment.co").submit();

        }
    } else {

        console.log("수정 버튼 클릭");

        if(confirm("입력한 내용으로 코멘트를 수정하시겠습니까?")) {

            $("#updateMyCommentForm").attr("action", "updateMyComment.co").submit();

        }

    }

}

 

 

더보기
// 코멘트 수정 폼이 열렸을 때 textarea에 포커싱을 줌으로써 사용자가 수정 폼임을 더욱 편하게 확인... 하기 실패
 $("#updateMyCommentButton").on("click", function() {

    console.log("모달 열렸당");
    $("#updateMyCommentForm").find("#updateMyComment").focus();

 });

이렇게 1에서 수정 버튼을 눌렀을 때 이벤트를 주면  (=모달이 띄워지는 시점에 이벤트를 주는 거겠지? 생각했는데)

모달이 제대로 띄워지기 전에 포커스를 주는 건지 먹히지 않았음

 

 

 

 

현재 내가 원하는 것은 코멘트 수정 모달창이 띄워졌을 때 커서 깜빡이는 이벤트 실행이므로 하기와 같이 코드 실행

$("#myCommentModal").on("shown.bs.modal", function () {		
    $("#updateMyComment").focus();
});

 

 

 

하지만 이렇게만 줬을 때는 먹히지 않음!

모달창은 해당 모달창을 띄워 줄 시점에 사용자의 눈에 보이게 설정값이 변경될 뿐이지 늘 그 자리에 있는 놈(?)이기 때문에

$(function({});) 과 같이 페이지가 로드되었을 때의 설정도 줘야 하는 것 같음

 

 

 

🙆🏻‍♀️ 이 코드 됩니다

 $(document).ready(function() {
		
    $("#myCommentModal").on("shown.bs.modal", function () {		
        $("#updateMyComment").focus();
    });	
});

이렇게 모든 코드를 적용해 보면

 

 

 

모달창이 띄워졌을 때 자동으로 포커스를 맞춘다 ♡^___^♡

저작자표시 비영리 변경금지 (새창열림)
'🚀 from error to study/Java' 카테고리의 다른 글
  • [java] ArrayList 0번째 인덱스에 새로운 값 넣고 한 칸씩 미는 법
  • [Spring] form 태그를 submit 했을 때 Controller에서 alert창 띄우게끔 유도하는 2가지 방법
  • java.lang.ClassCastException: java.util.ArrayList cannot be cast to VO 객체 경로
  • [java] controller에서 jsp로 값을 보내지 못함
천재강쥐
천재강쥐
  • 천재강쥐
    디버거도 버거다
    천재강쥐
  • 전체
    오늘
    어제
    • Category (467)
      • 진짜 너무 궁금한데 이걸 나만 몰라...? (0)
      • 💾 Portfolio (2)
      • 🐤 CodingTest (28)
        • Java (20)
        • ᕕ(ꐦ°᷄д°᷅)ᕗ❌ (5)
      • 🚀 from error to study (142)
        • AI (1)
        • Cloud (2)
        • DB (12)
        • Front-End (16)
        • Github (14)
        • Java (39)
        • Mac (7)
        • Normal (29)
        • Server (22)
      • 📘 certificate (44)
        • 📘 리눅스마스터1급 (1)
        • 📘⭕️ 정보처리기사 (40)
        • 📘⭕️ SQLD (3)
      • 📗 self-study (234)
        • 📗 inflearn (35)
        • 📗 생활코딩 (8)
        • 📗 KH정보교육원 당산지원 (190)
      • 🎨 Scoop the others (0)
        • 📖 Peeking into other people.. (0)
        • 🇫🇷 (0)
        • 📘⭕️ 한국사능력검정시험 심화 (11)
        • 오블완 (4)
  • 인기 글

  • hELLO· Designed By정상우.v4.10.1
천재강쥐
[Bootstrap] 부트스트랩 모달 열었을 때 커서 깜빡임 속성 [= focus()] 주기
상단으로

티스토리툴바