user1301428
user1301428

Reputation: 1783

CSS property not working when chaining in jQuery

This is the jQuery code:

$("#web").hover(
  function () {
    $(this).css({
             'background-color': '#ecf5fb',
             'cursor': 'pointer',
             'border': '1px solid #378ac4'
           })
           .children("a").children("img").attr("src", "1.png")
           .end().children("p").css("opacity", "1.0");

           $('#commentweb').stop(true, true).fadeIn();
  }, 
  function () {
    $(this).css({
             'background-color': '#e8e3e3',
             'border': '1px solid grey'
             })
             .children("a").children("img").attr("src", "2.png")
             .end().children("p").css("opacity", "0.5");

             $('#commentweb').stop(true, true).fadeOut();
  }
);

The problem is that the opacity is not changed, while everything else works. But if instead of this code I write

$(this).css({
         'background-color': '#ecf5fb',
     'cursor': 'pointer',
     'border': '1px solid #378ac4'
       })
       .children("a").children("img").attr("src", "1.png");
$(this).children("p").css("opacity", "1.0");

it works. Why is this happening?

Here is the fiddle: http://jsfiddle.net/mMB3F/6/

Upvotes: 0

Views: 113

Answers (2)

Musa
Musa

Reputation: 97672

If you want to go back up to the original selection you have to call .end() twice as you call children twice on the chain.

$("#web").hover(
  function () {
    $(this).css({
             'background-color': '#ecf5fb',
             'cursor': 'pointer',
             'border': '1px solid #378ac4'
           })
           .children("a").children("img").attr("src", "1.png")
           .end().end().children("p").css("opacity", "1.0");

           $('#commentweb').stop(true, true).fadeIn();
  }, 
  function () {
    $(this).css({
             'background-color': '#e8e3e3',
             'border': '1px solid grey'
             })
             .children("a").children("img").attr("src", "2.png")
             .end().end().children("p").css("opacity", "0.5");

             $('#commentweb').stop(true, true).fadeOut();
  }
);

http://jsfiddle.net/mMB3F/8/

Upvotes: 2

kinakuta
kinakuta

Reputation: 9037

You need to add an additional .end() in there if you want to get back to the original jquery object - each filtering action is putting a new jquery object on the stack - each call to .end() "pops" the last one off the stack. Here's an updated fiddle: http://jsfiddle.net/mMB3F/7/

Upvotes: 1

Related Questions