✿∘˚˳°∘°

44일차 : EVENT 본문

국비수업/JavaScript

44일차 : EVENT

_HYE_ 2023. 1. 30. 17:09

20230130

 

1. event

 

1 - 1 ) 이벤트모델 : 고전이벤트모델 / 인라인이벤트모델 / 표준이벤트모델

    <h1>이벤트</h1>
    <hr>
    <h3>고전 이벤트 모델 : 요소의 이벤트 속성에 함수를 연결</h3>
    <h3>인라인 이벤트 모델 : 요소작성 시 내부에 작성하는 방식</h3>
    <h3>표준 이벤트 모델 : w3c에서 고익적으로 지정한 이벤트모델</h3>
    <button id="btn1">고전이벤트</button>
    <!-- 인라인 : 이벤트(onclick)를 내부에 작성 -->
    <button onclick="console.log('인라인 이벤트');">인라인이벤트1(바로)</button>
    <button onclick="func1();">인라인이벤트2(함수연결)</button>
    <button id="btn2">표준이벤트모델</button>
    <button id="btn3">비교용 버튼1</button>
    <button id="btn4">비교용 버튼2</button>
//1. 고전이벤트모델
// 해당 dom객체의 이벤트 속성에 함수를 연결
const btn1 = document.querySelector("#btn1");
//해당 요소를 가져와서
btn1.onclick = function(){
//그 요소의 속성(onclick)에 작성
    console.log("고전이벤트 동작!");
}

function func1(){
    console.log("인라인이벤트모델 동작!");
}

const btn2 = document.querySelector("#btn2");
btn2.addEventListener("click", function(){
    console.log("표준이벤트모델");
});

const btn3 = document.querySelector("#btn3");
const btn4 = document.querySelector("#btn4");

btn3.onclick = function(){
    console.log("고전이벤트111");
}
btn4.addEventListener("click", function(){
    console.log("표준이벤트111");
});

//아래에 있는 이게 동작(단일이벤트연결)
btn3.onclick = function(){
    console.log("고전이벤트222");
}

//위아래 둘다 동작(여러이벤트연결)
btn4.addEventListener("click", function(){
    console.log("표준이벤트222");
});

 

1 - 2 ) 기본이벤트 제거

- a태그의 href 제거(confirm질문에서 '네'를 클릭했을 경우에만 이동가능하도록)

   <!-- a태그의 href를 막기 -->
    <a id="a" href="javascript:void(0)">네이버로이동</a>
    <!-- 이동취소를 눌러도 네이버로 이동한다. -->
    <!-- href를 사용하지 않으면 모든게 해결되지만, 그러면 효과가 다 사라짐(파란색,밑줄)-->
    <!-- href에 직접적인 링크를 달지않고 스크립트를 따라가도록 해줌 : javascript:void(0)-->
const a = document.querySelector("#a");
a.addEventListener("click", function(){
    const sel = confirm("네이버로 이동하시겠습니까?");
    if(sel){
        console.log("네이버로 이동");
        location.href = "http://www.naver.com";
    }else{
        console.log("취소");
    }
});

- form태그의 submit 제거(비밀번호/비밀번호확인 값이 동일해야만 넘어갈 수 있도록)

    <!-- form태그의 submit을 막기(방법3가지) -->
    <!-- 방법2.(이벤트의 관점). 폼이 전송되는 그순간을 이벤트로 잡을 경우 -->
    <form action="/changePw.html" method="post" onsubmit="return checkPw();">
        현재비밀번호 : <input type="password" name="userPw1"><br>
        새비밀번호 : <input type="password" name="userPw2"><br>
        <!-- 방법3. 매개변수 -->
        <input type = "submit" value="비밀번호 변경" id="changeBtn">
        
        <!--
        벙법1(이벤트의 관점) submit을 이벤트로 잡을 경우 
        <input type = "submit" value="비밀번호 변경" onclick="return checkPw();">
        <!-- 현재비번과 새비번이 같거나 할경우 폼을 넘겨주면 안된다 -->
        <!-- submit의 기본이벤트를 제거할때는 onclick = "return 함수();" -->
    </form>
function checkPw(){
    const pw1 = document.querySelector("[name=userPw1]");
    const pw2 = document.querySelector("[name=userPw2]");
    const pw1Value = pw1.value;
    const pw2Value = pw2.value;

    if(pw1Value == pw2Value){
        return false;//submit을 막음
    }else{
        //아무것도 작성하지않으면 submit
        //else자체를 작성하지 않아도된다.
    }
}
const changeBtn = document.querySelector("#changeBtn");
//매개변수 e : event
changeBtn.addEventListener("click", function(e){
    const pw1 = document.querySelector("[name=userPw1]");
    const pw2 = document.querySelector("[name=userPw2]");
    const pw1Value = pw1.value;
    const pw2Value = pw2.value;
    if(pw1Value == pw2Value){
        //현재 이벤트가 가지고있는 기본이벤트를 제거하는 함수
        e.preventDefault();
    }
});

 

1 - 3 ) 이벤트버블링 제거

이벤트 버블링 : 세번째div를 클릭했는데 두번째/첫번째 이벤트까지 같이 발생하는 상황

이 상황을 제거하는 법

    <div class="div-test div1">첫번째
        <div class="div-test div2">두번째
            <div class="div-test div3">세번째</div>
        </div>
    </div>
const divTest = document.querySelectorAll(".div-test");
for(let i=0; i<divTest.length; i++){
    divTest[i].addEventListener("click", function(){
        alert(divTest[i].innerText);
        //문제발생 : 세번째를 클릭하면 1/2/3 의 클릭이벤트가 모두 발생
        //이벤트버블링 : 클릭이벤트가 부모쪽으로 퍼져나가는 현상
        window.event.stopPropagation(); //이벤트 전달을 막음(버블링제거)
    });
}

 

1 - 4 ) 클릭, 더블클릭, mouseenter / mouseleave

- 마우스 클릭을 하면 이벤트 / 마우스 더블클릭을 하면 이벤트

- mouseenter / mouseleave : css의 hover와 비슷한기능

(단, hover의 경우 마우스가 나왔을때 자동으로 원상복구되지만 이벤트는 안되므로 각각 설정을 해줘야한다.)

    <div id="div1" class="test-div">클릭</div>
    <div id="div2" class="test-div">더블클릭</div>
    <div id="div3" class="test-div">mouseenter/mousecleave</div>
const div1 = document.querySelector("#div1");
div1.addEventListener("click", function(){
    console.log("클릭이벤트");
});

const div2 = document.querySelector("#div2");
div2.addEventListener("dblclick", function(){
    console.log("더블클릭이벤트");
});

const div3 = document.querySelector("#div3");
div3.addEventListener("mouseenter", function(){
    //마우스를 올리면 실행
    //hover와 차이점 마우스가 나와도 원상복구X 나올때 이벤트를 따로 해야함(mouseleave) 
    div3.style.backgroundColor = "black";
});
div3.addEventListener("mouseleave", function(){
    div3.style.backgroundColor = "transparent";
});

 

1-4 1-5 1-6

1 - 4 ) focusin / focusout

 

    아이디 : <input type="text" name="input1" id="input1">
    <span id="idCheck"></span>
    <br>
    비밀번호 : <input type="password" name="input2" id="input2">
    <br>
    비밀번호 확인 : <input type="password" name="input3" id="input3">
    <span id="pwCheck"></span>
const input1 = document.querySelector("#input1");
input1.addEventListener("focusin", function(){
//focusin : 이 input에 focus가 들어가면
//주의점 - 포커스를 했을때 바뀌고 나와도 바뀐상태 그대로이다 focusout을 해줘야함
    //this : 이벤트를 호출해서 사용하는 요소 자신을 의미(현재 input1)
    this.style.backgroundColor = "pink";
});
input1.addEventListener("focusout", function(){
    this.style.backgroundColor = "transparent";
});

 

1 - 5 ) 아이디 중복체크

(확인을 위해 아이디배열에 아이디 user01, user02, user03을 미리 넣어주었다)

//아이디 중복체크를 위한 임시 배열
const userArr = new Array();
userArr.push("user01");
userArr.push("user02");
userArr.push("user03");

- 방법1 : focusin

//중복검사1. focusin(입력하고 다음으로 넘어갔을 때)
input1.addEventListener("focusout", function(){
    const inputId = this.value;
    const searchResult = userArr.indexOf(inputId);
    //indexOf : 값을 넣으면 그값이 배열의 몇번째에 있는지 찾아줌(없으면 -1리턴)
    const idCheck = document.querySelector("#idCheck");
    if(searchResult == -1){
        console.log("아이디 중복X");
        idCheck.innerText = "사용 가능한 아이디 입니다.";
        idCheck.style.color = "green";
    }else{
        console.log("아이디 중복O")
        idCheck.innerText = "이미 사용중인 아이디 입니다.";
        idCheck.style.color = "red";
    }
});

- 방법2 : change

//중복검사2. change : input이 바뀌었을 때 
//focusout보다는 change를 주로사용
//focusout을 사용하면 나갔다가 다시들어와서 또 나갈때 계속 카운트되지만
//change는 input값이 바뀌지 않으면 카운트되지않는다.
input1.addEventListener("change", function(){
    const inputId = this.value;
    const searchResult = userArr.indexOf(inputId);
    const idCheck = document.querySelector("#idCheck");
    if(searchResult == -1){
        console.log("아이디 중복X");
        idCheck.innerText = "사용 가능한 아이디 입니다.";
        idCheck.style.color = "green";
    }else{
        console.log("아이디 중복O")
        idCheck.innerText = "이미 사용중인 아이디 입니다.";
        idCheck.style.color = "red";
    }
});

- 방법3 : keyup

//중복검사3. 한글자 입력할 때 마다 중복체크
input1.addEventListener("keyup", function(){
    const inputId = this.value;
    const searchResult = userArr.indexOf(inputId);
    const idCheck = document.querySelector("#idCheck");
    if(searchResult == -1){
        console.log("아이디 중복X");
        idCheck.innerText = "사용 가능한 아이디 입니다.";
        idCheck.style.color = "green";
    }else{
        console.log("아이디 중복O")
        idCheck.innerText = "이미 사용중인 아이디 입니다.";
        idCheck.style.color = "red";
    }
});

 

1 - 6 ) 비밀번호 / 비밀번호확인 일치

// 비밀번호확인을 입력한 경우 비밀번호에 입력한 값과 같은지 비교해서 화면에 표시
// 1. 이벤트가 언제 동작할건지 시점잡기 
// 2. 비밀번호 입력값과, 비밀번호확인 입력값이 같은지 비교
const input3 = document.querySelector("#input3");
input3.addEventListener("keyup", function(){
    const input2 = document.querySelector("#input2");
    const in2Val = input2.value;
    const in3Val = this.value;
    const pwCk = document.querySelector("#pwCheck");
    if(in2Val == in3Val){
        pwCk.innerText = "비밀번호 일치";
        pwCk.style.color = "green";
        this.style.border = "1px solid green";
    }else{
        console.log(in2Val);
        console.log(in3Val);
        pwCk.innerText = "비밀번호가 일치하지 않습니다.";
        pwCk.style.color = "red";
        this.style.border = "1px solid red";
    }
});

 

1 - 7 ) 체크박스(전체동시체크)

    <p>
        약관동의111111
    </p>
    <input type="checkbox" name="agree" id="agree1">
    <label for="agree1">약관동의1</label>
    <p>
        약관동의2222222
    </p>
    <input type="checkbox" name="agree" id="agree2">
    <label for="agree2">약관동의2</label>
    <hr>
    <input type="checkbox" id="allCheck">
    <label for="allCheck">약관동의 전체체크</label>
const agree1 = document.querySelector("#agree1");
//click이 아닌 change(체크값이 바뀔때)를 사용해도 된다
agree1.addEventListener("change", function(){
    const status = this.checked;
    //check가 되어있으면 t 안되어있으면 f
    console.log(status);
});
// 아래코드 즉, 약관전체동의를 했는데 위코드가 동작하지 않음
// 이유 : 이벤트란 웹페이지에서 사용자의 행동에 의해 바뀌는 행위 -> 다른스크립트에 의해 변화하는건 이벤트가 동작하지 않는다.
//        사람이 직접적으로 관여를 해야함

const allCheck = document.querySelector("#allCheck");
allCheck.addEventListener("change", function(){
    const status = this.checked;
    console.log("전체체크 체크박스 값 : "+status);
    const agree = document.querySelectorAll("[name=agree]");
    for(let i=0; i<agree.length; i++){
        agree[i].checked = status;
        /*
        if(status){
            agree[i].checked = true;
        }else{
            agree[i].checked = false;
        }
        */
    }
});
Comments