tags:

views:

31

answers:

2

Hi,

Here's what I want:

I have an element in my html code, and I want to assign a function to the onClick event, depending on some conditions to be known down the road.

For example

<a href="" id = "element"><img .....>

//other code

</a>

Then I want to do something like this

 <logic:equals some_condition>
      <script>
           var e = document.getElementById("element");

           e.onClick = my_function();

      </script>
 </logic>

But I cant get it working. Is there any special syntax?

I've tried with

 e.onClick = my_function;
 e.onClick = function(){my_function();}

Sadly i'm in IE 6.

Thanks in advance.

A: 

onclick is case sensitive

David Dorward
Is this a comment, an answer?
Tom
Nah, this is definitely a comment. xD
ign
It's an answer. The original code doesn't work because it is assigning the function to `onClick`, which isn't an event that ever fires. You have to assign it to `onclick`. (There might be other issues, but that is an obvious cause of brokenness)
David Dorward
@David: Funny thing, the rest of the html page is filled with working `onClick`s. Did some googling and some examples appear with lower case c, some with uppercase. Is this an IE6 'feature' ?
Tom
*boggle* must be a Microsoft thing. I've never seen it work (possibly it only works in quirks mode)
David Dorward
+1  A: 
  1. You should give <script> a type attribute:
  2. The method to get the reference to an element by id is called getElementById
  3. onclick (as all of JavaScript) is case-sensitive:
  4. You assign a reference of a function to event handlers, thus you leave the parenthesis away other wise it will call the function then and there.

.

<script type="text/javascript">
  var e = document.getElementById("element");
  e.onclick = my_function;
</script>

EDIT: If the logic is server-side its probaly easier to set then event handler in the HTML code then:

<a href="" <% if (some_condition) print "onload='my_function();'" %>>

(That is pseudo code, depending on you server-side language)

RoToRa
Thanks, I actually meant getElementById, but made a typo.
Tom