Skip to content

Instantly share code, notes, and snippets.

@jineeshjohn
Created November 20, 2011 06:47
Show Gist options
  • Save jineeshjohn/1379905 to your computer and use it in GitHub Desktop.
Save jineeshjohn/1379905 to your computer and use it in GitHub Desktop.
Event delegation sample
<style>
#mytable{
border-bottom:1px solid #000;
border-right:1px solid #000;
}
#mytable td{
border-top:1px solid #000;
border-left:1px solid #000;
padding:15px;
}
</style>
<table id="mytable" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>
<script>
// Generic function to get target event
function getEventTarget(evt) {
evt = evt || window.event;
return evt.target || evt.srcElement;
}
//Toggle background color
function toggleBgColor(evt){
var targetElem = getEventTarget(evt);
if(targetElem.tagName.toLowerCase() === 'td') {
targetElem.style.backgroundColor =
targetElem.style.backgroundColor?"":"#CC33CC";
}
}
var table = document.getElementById("mytable");
// mouseover event
table.onmouseover = toggleBgColor;
// mouseout event
table.onmouseout = toggleBgColor;
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment