Search code examples
javascriptjquerymouseentermouseleave

Trigger mouseenter and mouseleave for repeating elements


I am fetching data from MySql and I am displaying it in a table. I would like that for each <td> that contains a certain id to display some extra info on mouseenter and hide it on mouseleave using jQuery. Here is the HTML output:

<table>
    <tbody>
        <tr>
            <th>Option 1</th>
            <th>Option 2</th>
            <th>Option 3</th>
        </tr>
<?php   
    while ($row = mysqli_fetch_assoc($result)) {
?>  
    <tr>
        <td id="triggerTooltip"><?php echo $row['option1']; ?>
            <div class="tooltip">
                <p>Extra info</p>
            </div>
        </td>                   
        <td><?php echo $row['option2']; ?></td>
        <td><?php echo $row['option3']; ?></td>
    </tr>
<?php
    }
?>
    </tbody>
</table>

The default display property for the tool-tip is set to none. Here is the jQuery I am using:

$('#triggerTooltip').mouseenter(function() {
    $(this).closest('.tooltip').show();
}).mouseleave(function() {
    $(this).closest('.tooltip').hide();
});

I tried using $(this).find('.tooltip') and it works, but only for the first occurrence of the #triggerTooltip. I think I am getting it wrong. Can you please help me to figure this out? Thank you.


Solution

  • The above answer is correct here, this behaviour could also be implemented with CSS if you wanted, with a rule like:

    .triggerTooltip .tooltip {
        display: none;
    }
    
    .triggerTooltip:hover .tooltip {
        display: block;
    }