...

View Full Version : Setting onMouseDown



blueprint
04-14-2009, 10:46 PM
Hi fellow coders!

Im new to this forum and fairly new to JavaScript programming. I recently ran into this problem with setting onMouseDown with JS. Please be indulgent with my JS terminology as JS is not my native language.

Thing is I have this intricate loop generating div's from ajax output, for each of these div, I want to assign an onMouseDown function. The JS code I have written looks like this:

8<------------------------------------------------------
...
var e=document.createElement('tbody');
while(i2<i3)
{

var f=document.createElement('tr');
var g=document.createElement('td');

g.setAttribute("id","N"+i2);
g.className="tiny-text";
g.style.cursor="pointer";
g.innerHTML="Number "+i2;
g.onMouseDown=displayDivBox();

f.appendChild(g);
e.appendChild(f);
i2++;
}
...

function displayDivBox(event)
{
var el;
if (!event) event = window.event;
if (event.target) el = event.target;
else if (event.srcElement) el = event.srcElement;
...
}
8<------------------------------------------------------

Now the basic idea would be to generate these div's so that when they are clicked, displayDivBox is called. What actually happens here is that displayDivBox is called when <g> is generated, i.e. event is null or undefined. Moreover, setting onMouseDown this way does not seem to stick to <g> because nothing happens when the div's are clicked.

So, can this be done in some way or did I get something completely wrong?

Im using IE 7.0.5730.11 to run this code.

Any help or hints are greatly appreciated!

Thanks

blueprint
04-22-2009, 09:42 PM
Ok, After some digging, I found out the way to do it is like:

...
g.onmousedown=displayDivBox;
...

i.e. without the "()". Including the parethesis would actually imply a call to displayDivBox to return a function for onmousedown. Without the parenthesis, a function to be called for onmousedown is assumed instead. So, function name + "()" generates a call to that function.

You may wonder why this approach to create these elements, why not simply generate this code directly from php- output. It would be much easier to do, but in this case it would be a massive amount of elements that would have to be pre- created. I did try this out to start with, but the browser needed annoyingly much time to render, so in the end this method was choosen instead, i.e click on an element, fetch data from server through ajax- pipe, then create the elements needed from that data.

Anyone knows if there is a limit to how many elements a browser can handle? Render start to get a problem by quite low numbers, even with supa-dupa CPU, especially noticable with a couple of nested tables.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum