0

How to use "THIS" in the right way in order to select an ID inside "li"?

<li class="item">
    <div id="sale_container">text</div>
</li>

$("li.item").hover(function () {
        $("#sale_container").fadeIn(400);
    })
    $("li.item").mouseleave(function () {
        $("#sale_container").fadeOut(400);
    })

How ever it affects all li with class "item". So, i want it to take affect inside each li, when mouse is over.

This example doesn't work

$("li.item").hover(function () {
    $(this)("#sale_container").fadeIn(400);
})
$("li.item").mouseleave(function () {
    $(this)("#sale_container").fadeOut(400);
})
Andrei
  • 497
  • 2
  • 8
  • 18
  • You can't have multiple tags with the same ID, also this can be done with pure CSS. http://stackoverflow.com/questions/9250619/fade-in-out-with-css3 – asawyer Jul 24 '13 at 17:01
  • I think there will be aproblem in IE. How ever this looks nice – Andrei Jul 24 '13 at 17:03
  • Change the id to a class, and the selector from @David's answer to `$(this).find(".sale_container").fadeIn(400);` and you'll have 0 issues. – asawyer Jul 24 '13 at 17:05

5 Answers5

0

Since IDs are unique, you only need to use $('#sale_container') without any other qualifiers.

Assume you are not using an ID, then you'd use:

$(this).find(...).fadeIn(400); "..." being a selector of what you're looking for inside, which could be ("div") or a (".myClassname") etc.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • I never said it wasn't bad practice... just that no were in the specs does it mention id's are unique... I think 100% of browsers support non unique id's and Ive seen some very well written sites use non uniques id... – gbtimmon Jul 24 '13 at 17:09
  • Of course those sites were smart enough to NEVER try to grab the element by id from the global scope... always a more local one where the id WAS unique... I dont i was just sayin... – gbtimmon Jul 24 '13 at 17:18
0

Replace:

$(this)("#sale_container").fadeIn(400);

With:

$(this).find("#sale_container").fadeIn(400);

Or even:

$(this).children().fadeIn(400); // will fade any element inside .item

Note that you can only have one unique ID on one page.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
0

You can use this code:

$("li.item").hover(function () {
    $(this).find("#sale_container").fadeIn(400);
});
amatellanes
  • 3,645
  • 2
  • 17
  • 19
0

Use the find function to find an element contained inside the parent element (this).

$("li.item").hover(function () {
    $(this).find("#sale_container").fadeIn(400);
})
gbtimmon
  • 4,238
  • 1
  • 21
  • 36
0
 $("li.item").hover(function () {
        $("#sale_container",$(this)).fadeIn(400);
    }, function () {
       $("#sale_container",$(this)).fadeOut(400);
    });

FIDDLE Demo

Neeraj Dubey
  • 4,401
  • 8
  • 30
  • 49