Chap 5. jQuery 이벤트

김승현·2021년 11월 21일
0

click 이벤트

  • 마우스로 클릭했을때를 의미

EX) click 이벤트

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>

    <style>
        #p1 {
            border: 1px solid red;
            width: 300px;
            height: 300px;
            background-color: yellow;
        }
    </style>
</head>

<body>
    <p id="p1"></p>

    <script>
        var pSwitch = true;

        $('#p1').click(function() {
            if (pSwitch) {
                pSwitch = false;
                $(this).css('background-color', 'blue');
            } else {
                pSwitch = true;
                $(this).css('background-color', 'yellow');
            }
        });
    </script>

</body></html>




hover 이벤트

  • 마우스가 올라 갔을때, 빠져 나갔을때

🕵️‍♂️ 작성 방법

$('선택자').hover(inFunction, \[outFunction])
  • function 하나만 정의하면 올라갔을때
  • function 2개 정의하면 올라갔을때, 빠져나갔을때

EX) hover 이벤트


<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>

<body>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

    <style>
        .hoverClass {
            background-color: black;
            color: white;
        }
    </style>

    <H1>Test1</H1>
    <H1>Test1</H1>

    <script>
        $('h1').hover(function() {
            $(this).addClass('hoverClass');
        }, function() {
            $(this).removeClass('hoverClass');
        });
    </script>

</body></html>




trigger 이벤트

  • 이벤트 강제적으로 발생

EX) trigger 이벤트

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>

<body>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>



    <style>
        div {
            width: 100px;
            height: 100px;
            border: 1px solid black;
        }

    </style>

    <div id="div1"> </div>
    <div id="div2"> </div>
    <button id="btn">트리거</button>

    <script>
        $(function() {
            $('#div1').click(function() {
                $(this).css('background-color', 'red');
                $(this).css('border', '3px dashed pink');
            });
            $('#div2').click(function() {
                $(this).css('background-color', 'blue');
                $(this).css('border', '3px dotted yellow');
            });
            $('#btn').click(function() {
                $('#div1').trigger('click');
                $('#div2').trigger('click');
            });
        });

    </script>

</body>

</html>




event.preventDefault(), event.stopPropagation()

  • event.preventDefault()
    • 이벤트가 발동했을때 그 순간 이벤트를 제거할 수 있는 함수
    • 그 순간만 동작하지 못하도록 막음
  • event.stopPropagation() : 이벤트 전달 제거
    • 이벤트 버블링을 막는 함수

EX) event.preventDefault()

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>

<body>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>


    <h1>
        <a href="http://www.naver.com">네이버로 이동</a>
    </h1>

    <button id="btn">On</button>

    <script>
        $(function() {
            var switchBtn = true;
            $('#btn').click(function() {

                if (switchBtn == true) {
                    //눌려진 버튼이 현재 on상태라면
                    //off 상태로 바꾸어 주어라.
                    switchBtn = false;
                    $(this).text('Off');
                } else {
                    //눌려진 버튼이 현재 off상태라면
                    //on 상태로 바꾸어 주어라.
                    switchBtn = true;
                    $(this).text('On');
                }
            });
            $('a').click(function() {
                if (switchBtn == false) {
                    event.preventDefault(); //기본 이벤트를 동작하지 않도록!!
                    alert('Off 상태일때에는 사용할 수 없습니다.');
                }
            });
        });
    </script>

</body></html>

EX) event.stopPropagation()

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>

<body>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

    <style>
        div {
            border: 1px solid black;
            height: 100px;
            width: 100px;
        }
    </style>

    <div>
        <p style="background-color : red">클릭</p>
    </div>

    <script>
        $(function() {
            $('p').click(function() {
                alert("p 이벤트가 동작합니다.");
                event.stopPropagation(); //이벤트 전달을 막음
            });
            $('div').click(function() {
                alert('div 이벤트가 동작합니다.');
            });
        });
    </script>

</body></html>




on() , off()

  • 이벤트 연결 및 해제하는 함수

EX) on() , off()

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>

<body>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>


    <style>
        #print {
            width: 200px;
            height: 200px;
            border: 1px solid black;
        }
    </style>

    <div id="print">
    </div>
    <button id="onBtn">이벤트 on</button> <button id="offBtn">이벤트 off</button>

    <script>
        $('#onBtn').click(function() {
            $('#print').css('background-color', 'purple');
            $('#print').on('click', function() {
                alert('이벤트 동작');
            });
        });

        $('#offBtn').click(function() {
            $('#print').css('background-color', 'white');
            $('#print').off('click');
        });
    </script>

</body></html>




mousedown() , mouseup()

  • mousedown() : 마우스 버튼이 내려갈때(눌려질때)
  • mouseup() : 마우스 버튼이 올라갈때(눌렸다가 때어질때)

EX) mousedown() , mouseup()

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>

<body>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>


    <style>
        div {
            border: 5px solid black;
            height: 100px;
            width: 100px;
        }
    </style>

    <div></div>

    <script>
        $(function() {
            $('div').mousedown(function() {
                $(this).append("<img src='../image/mayo.png' width=100% height=100%/>");
            });
            $('div').mouseup(function() {
                $(this).empty();
            });

        });
    </script>

</body>

</html>




keydown(), keypress(), keyup()

  • 키보드 버튼이 눌러지거나 떼어질때 발생하는 이벤트

    • keydown() : 키보드가 눌려질때
    • keypress() : 글자가 입력될때
    • keyup() : 키보드가 떼어질때

  • 키보드 이벤트 실행 순서

    1. 사용자가 키보드를 누름
    2. keydown 이벤트 발생
    3. 글자가 입력됨
    4. keypress 이벤트 발생
    5. 사용자가 키보드에서 손을 뗌 (눌렀던 버튼에서 손을 뗌)
    6. keyup 이벤트 발생

EX) keydown(), keypress(), keyup()

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>

    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

    <style>
        #print {
            border: 1px solid red;
            width: 400px;
            height: 300px;
        }
    </style>
</head>

<body>

    <div id="print"></div>
    <input type="text" id="inputData"><button id="btn">작성</button><span>0</span>

    <script>
        $('#btn').click(function() {
            var inputData = $('#inputData').val();
            var $selector = $('#print');
            var text = $selector.html();
            text += inputData + '<br>';

            $selector.html(text);
        });

        $('#inputData').keyup(function() {
            var $selector = $(this).next().next();
            var inputDataLength = $(this).val().length;
            $selector.html(inputDataLength);
        })
    </script>
</body>

</html>




입력 양식 이벤트

  • 입력하는 폼 약식에 발생하는 이벤트

focus() :입력 양식에 초점을 맞추면 발생
focusin() : 입력 양식에 초점을 맞춰지기 바로 전에 발생
focusout() : 입력 양식에 초점이 사라지기 바로 전에 발생
submit() : form 태그에서 submit 버튼을 누르면 발생


EX) focusin(), focusout()

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>

<body>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>


    <H1>회원가입</H1>
    ID : <input type="text" id="userId"><label></label><br>
    PW : <input type="text" id="userPw"><label></label><br>
    NAME : <input type="text" id="userName"><label></label><br>

    <script>
        $(function() {
            $('input').focusin(function() {
                $(this).css('border', '4px solid blue');

                switch ($(this).attr('id')) {
                    case 'userId':
                        $(this).next().html('영어+숫자만 입력하세요');
                        $(this).next().css('color', 'red');
                        break;
                    case 'userPw':
                        $(this).next().html('영어+숫자+특수문자만 입력하세요');
                        $(this).next().css('color', 'red');
                        break;
                    case 'userName':
                        $(this).next().html('한글만 입력하세요');
                        $(this).next().css('color', 'red');
                        break;
                }
            });

            $('input').focusout(function() {
                $(this).css('border', '');

                $(this).next().html('');
            });

        });
    </script>

</body></html>

EX) submit()

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>

<body>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

    <H1>회원가입</H1>
    <form action="./join.do">
        ID : <input type="text" id="userId" /><label></label><br>
        PW : <input type="password" id="userPwd" /><label></label><br>
        NAME : <input type="text" id="userName" /><label></label><br>
        <input type="submit" value="회원가입" /> <input type="reset" value="취소" />
    </form>
    <script>
        $(function() {
            $('form').submit(function() {
                var userId = $('#userId').val();
                if (userId == "") {
                    alert("공백은 안됩니다.");
                    return false;
                } else {
                    return true;
                }
            });
        });
    </script>

</body></html>
profile
개발자로 매일 한 걸음

0개의 댓글