Search code examples
jqueryhtml-tablecolorbox

Colorbox popup on specific table column instead of row


I created Colorbox popup when a user click on anywhere in the table row by using below code. Now I want to open the popup only if someone click the 2nd column.

$(".inline").colorbox({inline:true, width:"50%"});

<tr class="inline" href="#123">
    <td>Name</td>
    <td>Address</td>
</tr>

<div style='display:none'>
     <div id='123' class="colorbox_content">
          <p><strong>Title Here</strong></p>
          <p>Description</p>
     </div>
</div>

I try to apply class on td and also tried to change jQuery from $(".inline") to $("table td #2") but nothing worked.


Solution

  • Try:

    $('table > tbody > tr > td:nth-of-type(2)').colorbox({inline:true, width:"50%"});
    

    You can get away with a shorter selector, you'd have to experiment. There is a > tbody in there whether you put one there or not, because the browser will place it there by default. When traversing the DOM, that's an important thing to remember about tables.

    SNIPPET

    $('table > tbody > tr > td:nth-of-type(2)').css('background', 'red');
    td {
      border: 2px solid black
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    <table>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
    </table>