DanMad DanMad - 1 month ago 6
Javascript Question

Select only the string from array that has triggered jQuery function()

I have looked for a previous answer to this question with no success. I am not very familiar with JS, or jQuery for that matter (but I'm learning).

I am trying to assign a class of

.active
to all
<td>
cells in whatever column the mouse enters into.

Here is a simplified version of my markup:

<table>
<thead>
<tr>
<th>&nbsp;</th>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td class="js col one">1</td>
<td class="js col two">2</td>
<td class="js col three">3</td>
</tr>
<tr>
<th>2</th>
<td class="js col one">2</td>
<td class="js col two">4</td>
<td class="js col three">6</td>
</tr>
<tr>
<th>3</th>
<td class="js col one">3</td>
<td class="js col two">6</td>
<td class="js col three">9</td>
</tr>
</tbody>
</table>


Here is my script:

var arr = ['.one', '.two', '.three'];
var tableCol = $('.js.col' + arr);

tableCol.mouseenter(function() {
tableCol.addClass('active');
});
tableCol.mouseleave(function() {
tableCol.removeClass('active');
});


I have placed the differing classes into an array because in my real code there are a lot more than 3 different columns and I don't want to repeat myself.

The problem I am facing is that on
.mouseenter
of any of these columns, triggers the
.addClass
for all strings in the array. Is there a way to only
.addClass
to the specific string from the array that has triggered the function?

I hope I have made myself clear. Thank you in advance.

Answer

Here is another solution. This one utilizes the classes to highlight the columns.

var arr = ['.one', '.two', '.three'];
var tableCol = $('.js.col' + arr);

tableCol.mouseenter(function() {
        var colClass = "." + $(this).attr("class").split(" ").join(".")
        $(colClass).addClass('active')
});
tableCol.mouseleave(function() {
    $(tableCol).removeClass('active');
});