Dan P.
Dan P.

Reputation: 1775

Select the next element with a specific class after clicking on an element

HTML looks like (spans inside the expandable text class are generated via JS)

<span class="expandable-text">
    <span class="more">read more</span>
    <span class="details">blablabla</span>
</span>

Current jQuery:

$('.expandable-text').on('click', '.more', function() {     
    setTimeout(function () {
        // bad as it selects all elements with that class...
        // $('.details').css('display', 'inline');
        $(this).next('span').css('display', 'inline');
    }, 50);
});

Also tried $(this).parent().find('.details').css('display', 'inline');

How should I be selecting that element with the details class, right next to the element I just clicked ?

Edit: Both the span elements inside the expandable-text are dynamically generated. Fiddle: http://jsfiddle.net/NTP9y/2/

Upvotes: 0

Views: 180

Answers (2)

BoltClock
BoltClock

Reputation: 723598

Your .next('span') is correct — if you know that each .more is necessarily followed by a span.details then you could omit the argument and just do .next(), but there's no difference if you don't.

The problem in your code is that this isn't properly scoped within the timeout callback.

The solution is to call $(this) and assign it to a variable outside of setTimeout(), then passing that variable into the timeout function:

$('.expandable-text').on('click', '.more', function() {
    var details = $(this).next('span');
    setTimeout(function () {
        details.css('display', 'inline');
    }, 50);
});

Upvotes: 1

Tot&#242;
Tot&#242;

Reputation: 1854

There are many ways to do this, one is $(this).siblings('.details').css(...) like here http://jsfiddle.net/sfarsaci/NTP9y/

Upvotes: 0

Related Questions