View Full Version : Adding an onclick event to a div from within javascript

09-05-2007, 05:38 AM

I have 2 questions: First is a coding issue and the second is a design question.

I am trying to add an onclick event to a div from within javascript. Basically i have 2 divs containing arrows ("<<" and ">>"), used to toggle the week of a calendar. At the moment the ajax communication and handling of the response is working fine. After i processed this, i want to switch the arrows, basically add onclick to the previously non-active arrow and then nullify the previously active arrow. How do i go about doing this? Below is my attempt at solving it, with no luck.

function switch_direction(direction)
var leftobj = document.getElementById("left");
var rightobj = document.getElementById("right");

if(direction == "right")
rightobj.className = "toggle_off";
leftobj.className = "toggle_on";
rightobj.onclick = null;
leftobj.onclick = "init()";
rightobj.className = "toggle_on";
leftobj.className = "toggle_off";
rightobj.onclick = "init()";
leftobj.onclick = null;

Design question:

At the moment i have a sort of a controller function (using a switch), init(), which is called by all events. I detect the event and find the id of the element the event was triggered on. I am not too sure if this a good idea, as i have a calendar with a div for every 30mins in a day (and 7 days of the week). Thats 336 divs, which at the moment i intend to add the onclick="init()" function to.
I am pretty new to javascript (about 2 days), so any assistance or contructive criticism is appreciated.

function init()
var evt = window.event || arguments.callee.caller.arguments[0];
if(evt != null)
var target = evt.target || evt.srcElement;

var element_id = target.id;

case "right":
case "left":

09-05-2007, 08:22 AM
Any one?

09-05-2007, 08:35 AM
looking for something like this? This will programmatically attach onclick events to many divs at once from within your JS code (this is to give you the idea):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang=en>
<meta name="robots" content="noindex,nofollow" />
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<style type="text/css">
div {width:200px;padding:20px;cursor:hand;background-color:#eee;margin:15px 0}

<br />
<p id="count" style="font:bold 20px Times;color:red;text-indent:20px">1</p>
<script type="text/javascript">
function AttachAllDivEvents()
var divCollection = document.getElementsByTagName("div");
for (var i=0; i<divCollection.length; i++)
function AttachDivClickEvent(divObj)
divObj.onclick = function()
document.getElementById("count").innerHTML = parseInt(document.getElementById("count").innerHTML) + 1;
window.onload = AttachAllDivEvents;