Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Assigning onClick to TD

Status
Not open for further replies.

econnections

IS-IT--Management
Apr 28, 2006
30
GB
Hello,

Is it possible to assign onclick to TD using a function?

The reason I ask is that my table represents a calander and I only want to cells populated with dates to have onclick assigned. The number of cells vary depending on the month.

I know I can assign values to a cell using:

document.getElementById('x').innerHTML;

but I'm not sure I can assign event handlers?


Can anyone offer help with this, please?
 
Here is one way to assign an onclick to the element with an id of 'x'...
Code:
document.getElementById('x').onclick = function() {alert('beep');}
You can also assign an existing function:
Code:
document.getElementById('x').onclick = beepMe;
function beepMe() {
alert('beep');
}

Cheers,
Jeff

[tt]Jeff's Page @ Code Couch
[/tt]

What is Javascript? FAQ216-6094
 
Thanks Jeff. I've just written that into my test programme along with a variance for onmouseover:

document.getElementById('x').onmouseover= function(){ this.style.cursor='pointer' };

Great! thanks again.
 
If all you're doing is setting the cursor style for the table elements then you'd be much better suited using CSS for it instead, the javascript is just completely unnecessary.
Code:
<html>
<head>
<style type="text/css">
td {
   cursor:pointer;
   border:1px solid black;
}
</style>
</head>
<body>
   <table>
      <tr>
         <td>This</td>
         <td>is</td>
         <td>a</td>
         <td>test</td>
      </tr>
   </table>
</body>
</html>

-kaht

[small]How spicy would you like your chang sauce? Oh man... I have no idea what's goin' on right now...[/small]
[banghead]
 
Can this me modified to it is only applied to certain TD's within the table. ie using <TD class='style1'>

I'm not sure what to put in the <style> section to limit the behaviour.

Is it:

<style>
TD#style1 {.... }
 
sure:
Code:
<html>
<head>
<style type="text/css">
td[!].blah[/!] {
   cursor:pointer;
   border:1px solid black;
}
</style>
</head>
<body>
   <table>
      <tr>
         <td class="blah">these</td>
         <td class="blah">have</td>
         <td class="blah">a</td>
         <td class="blah">pointer</td>
      </tr>
      <tr>
         <td>these</td>
         <td>cells</td>
         <td>do</td>
         <td>not</td>
      </tr>
   </table>
</body>
</html>

-kaht

[small]How spicy would you like your chang sauce? Oh man... I have no idea what's goin' on right now...[/small]
[banghead]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top