프로그램/Html_JavaScript

javascript 에서 코드로 이벤트 발생시키는 법.

(주)CKBcorp., 2013. 11. 9. 17:56
반응형


흠. 뭐 하다보니 필요해서.

결론부터 말하면 

Element.fireEvent( '이벤트이름' )   // IE 8 버전
혹은

Element.dispatchEvent( '이벤트이름' )  // IE 9 버전, 크롬, 파폭 등등

되겠다. ( 출처 : 언제나처럼 https://stackoverflow.com/questions/2381572/how-can-i-trigger-a-javascript-event-click )




function fireEvent(node, eventName) {

    // Make sure we use the ownerDocument from the provided node to avoid cross-window problems

    var doc;

    if (node.ownerDocument) {

        doc = node.ownerDocument;

    } else if (node.nodeType == 9){

        // the node may be the document itself, nodeType 9 = DOCUMENT_NODE

        doc = node;

    } else {

        throw new Error("Invalid node passed to fireEvent: " + node.id);

    }


     if (node.dispatchEvent) {

        // Gecko-style approach (now the standard) takes more work

        var eventClass = "";


        // Different events have different event classes.

        // If this switch statement can't map an eventName to an eventClass,

        // the event firing is going to fail.

        switch (eventName) {

            case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.

            case "mousedown":

            case "mouseup":

                eventClass = "MouseEvents";

                break;


            case "focus":

            case "change":

            case "blur":

            case "select":

                eventClass = "HTMLEvents";

                break;


            default:

                throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";

                break;

        }

        var event = doc.createEvent(eventClass);

        event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.


        event.synthetic = true; // allow detection of synthetic events

        // The second parameter says go ahead with the default action

        node.dispatchEvent(event, true);

    } else  if (node.fireEvent) {

        // IE-old school style, you can drop this if you don't need to support IE8 and lower

        var event = doc.createEventObject();

        event.synthetic = true; // allow detection of synthetic events

        node.fireEvent("on" + eventName, event);

    }

};





하지만 난 따뜻한 도시 인간이니, 좀 더 설명을 쓰도록 하지.



[ 어디선가 퍼온 짤 ]


예를 들어, 아래와 같은 button 코드가 있다고 치자.


<script>

function fnclick()

{

alert('차도남');

}

</script>

<input type="button" id="btn1" onclick="javascript:fnclick();">



그럼, 사람이 이거 클릭하면 alert('차도남') 이 뜨겠지?

그런데, alert('차도남') 을 화면에 띄우기 위한 방법이 그것뿐인가? 그냥 fnclick() 을 실행해도 되잖아?


<script>

function fnclick()

{

alert('차도남');

}


fnclick();

</script>

<input type="button" id="btn1" onclick="javascript:fnclick();">



뭘 말하려는 거냐면,


element.onclick(); 


과 


element.dispatchEvent( event );


의 차이를 설명하려는 거다. ( fireEvent() 와 dispatchEvent() 메쏘드 중, 표준은 dispatchEvent() 다. )


만일 어떠한 객체에 click 이벤트가 걸려있다고 치자. ( = element.onclick = function() { ... } );

그럼, 이 onclick 의 내용을 실행하는 건 간단하다. 그냥


<script>

element.onclick();

</script>



으로 된다. 고민할 필요도 없다.


근데, 너님이 하려는 작업은 설정된 onclick() 함수를 실행하려는 게 아니고 사용자가 html 상의 객체를 클릭했을 때 동작이 발생하게끔 하는거잖아?

예를 들어, 위의 button 객체가, 버튼이 아니고 ancher 라면 어쩔꺼냐? 즉,


<a href="http://www.daum.net" onclick="javascript:fnclick();"> 누르기 </a>



이라면?


만일 사용자가 "누르기" 글자를 눌렀다면, alert() 이 뜨고 링크가 이동하는 두 개의 개별 작업이 발생할 거다.

근데 저걸 ancher.onclick(); 으로 실행한다던가, fnclick(); 을 실행한다면, html 태그가 본래 가지고 있는 속성인 하이퍼링크의 이동 이벤트는 발생하지 않는다.


그러므로, 이러한, "클릭 자체" 의 이벤트를 발생하게 하려면, onclick 같은 걸로는 안되고 반드시 dispatchEvent() 를 써야하는 거임.


구체적인 형식은 다음과 같다.


var event = document.createEvent("HTMLEvents");

event.initEvent("이벤트이름",true,false);

document.getElementById("엘리먼트").dispatchEvent(event);



예를들어, click 이벤트를 자바스크립트 코드로 일으키려면


var event = document.createEvent("HTMLEvents");

event.initEvent("click",true,false);

document.getElementById("btn1").dispatchEvent(event);



되시겠다.


뭐, 객체가 text 라면 change 도 될테고, mousemove 나 focus 도 될테고... 문자열은 적당히 조합하면 된다.


참고는 요기 : http://stackoverflow.com/questions/9714527/why-does-fireevent-not-work-in-ie9


이상 끝.


추신 : fireEvnet 가 IE8 이하 버전에서는 안된다는 소문이 있는데, 잘은 모르겠다. 내가 확인해 본 건 아님.





반응형