StandardNerd StandardNerd - 1 year ago 45
jQuery Question

jquery find image title attribute and toggle class of according list item

I have a list of images with title attributes and a separate list of names.

On mouse hover on the images i want to toggle css class on a list item on the name list.

Therefor i have to take the value of the current title tag and have to search for the according text in the names list.

<ul class="staff-photos">
<li class="standard">
<%= image_tag("footer/edith_hansmann.jpg", alt: "Edith Hansmann", title: "Edith Hansmann") %>
<li class="standard">
<%= image_tag("footer/christine_jean.jpg", alt: "Christine Jean", title: "Christine Jean") %>

<ul class="staff-names">
<li><span class="hover-name">EDITH HANSMANN</span> | Head of Design</li>
<li><span class="hover-name">CHRISTINE JEAN</span> | Head of Marketing</li>

My javascript:

// mouse hover on staff page image toggles CSS class of staff name list item
$('ul.staff-photos img').hover(function() {
var name = $(this).attr('title');

I have trouble with comparing the according list item:


How can i achieve that the according list item get toggled?

Answer Source

The issue is with your logic around the match, as you get the text of all the span elements in a single string instead of comparing them individually.

You can achieve what you require by using the filter() method to find the span elements with text() that matches the hovered img elements' title attribute. Try this:

$('ul.staff-photos img').hover(function() {
    var name = $(this).attr('title').toLowerCase();
    $('.hover-name').filter(function() {
        return $(this).text().toLowerCase() == name;

Working example