Attaching an Event Handler to DOM Elements

I am working on a tic tac toe game which is almost complete. The only thing I have no doubt about is adding an event handler for onclick

from my .js file instead of calling it directly from an HTML attribute. Here is the bit of HTML that uses onclick

:

<div id="left">
        <div id="board">
            <div id="one" onclick="playerMove(this)">

            </div>
            <div id="two" onclick="playerMove(this)">

            </div>
            <div id="three" onclick="playerMove(this)">

            </div>
            <div id="four" onclick="playerMove(this)">

            </div>
            <div id="five" onclick="playerMove(this)">

            </div>
            <div id="six" onclick="playerMove(this)">

            </div>
            <div id="seven" onclick="playerMove(this)">

            </div>
            <div id="eight" onclick="playerMove(this)">

            </div>
            <div id="nine" onclick="playerMove(this)">

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

      

Any thoughts on this would be greatly appreciated.

0


source to share


6 answers


Use this:

document.getElementById('element_id').onclick = function(){ playerMove(this); };

      



For each Div, change 'element_id' to 'one', 'two', ...

0


source


If you are using jQuery, then something like this should work:



$(document).ready(function() {
  $('#board div').click(playerMove);
});

      

+2


source


In plain javascript (no cross platform libraries), event handlers can be added via javascript code using addEventListener

(modern browsers) or attachEvent

(older versions of IE).

Here's a simple function that adds a cross-browser event handler:

// add event cross browser
function addEvent(elem, event, fn) {
    if (elem.addEventListener) {
        elem.addEventListener(event, fn, false);
    } else {
        elem.attachEvent("on" + event, function() {
            // set the this pointer same as addEventListener when fn is called
            return(fn.call(elem, window.event));   
        });
    }
}

      

Usage example (called after the DOM page has loaded):

addEvent(document.getElementById("one"), 'click', playerMove);

      

Or, to set event handlers for all sections of the board, you can do this:

var divs = document.getElementById("board").children;
for (var i = 0, len = divs.length; i < len; i++) {
    // element nodes only
    if (divs[i].nodeType === 1) {
        addEvent(divs[i], 'click', playerMove);
    }
}

      

+2


source


You really should be using jQuery for this. If you are using jQuery it would be as easy as:

$('#board > div').click(playerMove);

      

If you want to stick with vanilla JS, you can do:

var items = document.getElementById('board').children;
for(x in items) {
    items[x].onclick = function() {
        playerMove(items[x]);
    };
}

      

+1


source


Try:

document.getElementById('one').onclick();

      

To bind an event handler in js file:

var board = document.getElementById('board'),
      divs = board.getElementsByTagName('div'),
      i, len = divs.length;
for (i = 0; i < len; i++) {
      divs[i].onclick = function() {
           playerMove(this); 
      };
}

      

0


source


Your answer is on the next 5 lines. Give it a try :) If someone is copying / converting my code to a new post or my post to j-query, this is welcome without issue.

var yourDivID = document.getElementById('your_Div_ID');
yourDivID.addEventListener('click', function (){  playerMove(this); }, false);
function playerMove(divElement)
{
    alert(divElement.id);
}

      

I tried to put a complete demo Here at jsfiddle.net , You can click any div of nine to check its event , if the link doesn't work then you can check the following code (working for me WIN7 and FireFox)

<html>
<head>
<title> Add Events Dynamically </title>
<script type="text/javascript">
    function add_DivClick_Events() {
        var nodes = document.getElementById('board').childNodes;
        for (var i = 0; i < nodes.length; i++) {
            if (i % 2 == 1) {
                nodes[i].addEventListener('click', function () {
                    playerMove(this);
                }, false);
            }
        }    
    }
    function playerMove(divElement)
    {
        alert(divElement.id);
    }  
    </script>
    <style type="text/css">
    #board div
    {
        width:20px;
        height:20px;
        border:2px solid;        
    }
    </style>
</head>
     <body onload='add_DivClick_Events()'>   
        <div id="left">
        <div id="board">
            <div id="one">

            </div>
            <div id="two">

            </div>
            <div id="three">

            </div>
            <div id="four">

            </div>
            <div id="five">

            </div>
            <div id="six">

            </div>
            <div id="seven">

            </div>
            <div id="eight">

            </div>
            <div id="nine">

            </div>
        </div>
    </div>
    </body>    
 </html>

      

0


source







All Articles