본문 바로가기

DEVELOP

[javascript & jQuery] $(document).on 으로 동적 이벤트 걸기

728x90

스크립트를 짤 때 보통 이벤트는 $(document).ready(function(){}); 에 걸곤 했었다. 


하지만 변수로 해당 이벤트를 제어해야 할 경우에 $(document).ready(function(){}); 안에서 변수 선언을 해주어야 해당 이벤트가 작동이 된다는 문제점이 있어서 중복 함수나 이벤트가 내 소스에 넘쳐 났었다.



그러니까, 이런 식으로 코드를 짠다면 변수 color를 인식하지 못한다. 


(직접 짠 코드입니다. 사용할 경우 출처를 밝혀주세요!)


var color = '#f00';


$(document).ready(function(){

    $(this).parent('.script-enter-object').css({

        borderColor: color

    });

});



그래서, 아래와 같이 짤 수 밖에 없었다. 


$(document).ready(function(){

var color = '#f00';

    $(this).parent('.script-enter-object').css({

        borderColor: color

    });

});



하지만 $(document).on 을 사용한다면 다른 js 파일에 있는 color의 변수 선언도 인식하여 $(document) 외부에 변수 선언이 가능해진다. 


on이벤트는 생각보다 활용성이 뛰어난 것 같다. (on의 활용 : https://jintrue.tistory.com/entry/event%EC%99%80-%ED%95%A8%EA%BB%98-%EC%82%AC%EC%9A%A9%ED%95%98%EB%8A%94-on)



적용한 결과를 아래에서 확인 할 수 있다.


(직접 짠 코드입니다. 사용할 경우 출처를 밝혀주세요!)


a.js


//############ document function /############//

$(document).on('mouseenter', '.script-enter', function(){

    $(this).parent('.script-enter-object').css({

        borderColor: color

    })

});



b.js


// custom color setting

    var color = '#ab444b';



아래와 같이 마우스호버 했을 경우 해당 border 색상이 #ab444b 로 변경되는 이벤트가 적용된 것을 확인 할 수 있다.