John
John

Reputation: 1

Selector issue using a loop in jQuery

In my jQuery code (see below), I can't manage to change the color of the "typetravaux" class content.
The opacity change on hover is OK, but the color change does not work (I tried 2 different ways, but none of them is working).

Can you guys tell me what I am doing wrong ? Thanks !

CSS :

.typetravaux {
  width: 100%;
  color: #ffffff;
}

HTML:

<div class="solutions">
    <div class="bloc1">
      <span class="typetravaux">PLOMBERIE</span>
       <div class="picture"><img src="img/plomberie.png" class="prestapicture"></div>
     </div>
    <div class="bloc2">
      <span class="typetravaux">CHAUFFAGE</span>
       <div class="picture"><img src="img/chauffage.jpg" class="prestapicture"></div>
     </div>
    <div class="bloc3">
      <span class="typetravaux">CLIMATISATION</span>
       <div class="picture"><img src="img/climatisation.jpg" class="prestapicture"></div>
     </div>
</div>

jQuery :

$prestapicture = $('.prestapicture');

for (y=0; y < $prestapicture.length; y++) {
    $prestapicture.eq(y).on("mouseover", function() {
      $(this).css("opacity", "0.3");
      $(this).prev(".typetravaux").css("color","black") // **does not work**
    
    })
    
    $prestapicture.eq(y).on("mouseout", function() {
      $(this).css("opacity", "1");
      $(".typetravaux").eq(y).css("color","white"); //**does not work either**
    
    })
}

Upvotes: 0

Views: 45

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

prev uses the previous sibling, but the .typetravaux elements aren't siblings of the .prestapicture elements, they're siblings of those elements' parent .picture elements.

You could fix that like this:

$(this).parent().prev(".typetravaux").css("color","black");
//      ^^^^^^^^^

...but it's quite fragile, minor changes to the HTML break it.

Instead, I'd either:

  1. Add a class to the container div and do this:

    $(this).closest(".container").find(".typetravaux").css("color","black");
    

    or

  2. Add a class to that container for when you want this different styling, and use a descendant combinator (a space) in CSS to do the CSS changes.

    .pic-hovered .typetravaux {
        color: black;
    }
    

In general, I would avoid using css() for styling. Use classes, and put the style rules in your CSS.

Upvotes: 1

Related Questions