Nasir
Nasir

Reputation: 4865

Having trouble getting Jquery .closest() working?

I'm having trouble getting Jquery .closest() to work.

Here's my code, it's simple and I can't see any reason why it shouldn't work:

Jquery

show:function(a,fx){
        $('.more-content').hide();

        $(a).toggle(function() {
                t = $(this).closest(".more-content")
                if (fx.match('show')) {
                    t.show()
                };
                if (fx.match('slide')) {
                    t.slideDown()
                };
                if (fx.match('fade')) {
                    t.fadeIn()
                };
                $(this).html('Less')
            }, function() {
                if (fx.match('show')) {
                    t.hide()
                };
                if (fx.match('slide')) {
                    t.slideUp()
                };
                if (fx.match('fade')) {
                    t.fadeOut()
                };
                $(this).html('More')
            });
        } 

HTML

    <p><strong class="goal">The Goal</strong><br />
    To support those who are NEET <span class="more-content">We do this by providing education or training to enable said people to be...</span>
    <span class="more">More</span>

    <br /><br />
    To build community cohesion in the local area. <span class="more-content">This will lead to a community where people have the opportunity...</span> 
    <span class="more">More</span>
    </p>

Confused, so any help is greatly appreciated, Thanks

Upvotes: 0

Views: 77

Answers (1)

Jasper
Jasper

Reputation: 75993

If the a variable being passed into the show method is the .more elements then you want to use select a sibling element, not an ancestor element.

var t = $(this).prev(".more-content");

Also you are creating a global variable (t) to save the current element for your toggle functions but this is not a good way to do that. Just select the proper t element in both functions:

var fx = 'slide';

$(a).toggle(function() {
    var t = $(this).prev(".more-content");

    if (fx.match('show')) {
        console.log('1');
        t.show();
    };
    if (fx.match('slide')) {
        console.log('2');
        t.slideDown();
    };
    if (fx.match('fade')) {
        console.log('3');
        t.fadeIn();
    };
    $(this).html('Less')
}, function() {
    var t = $(this).prev(".more-content");
    if (fx.match('show')) {
        t.hide()
    };
    if (fx.match('slide')) {
        t.slideUp()
    };
    if (fx.match('fade')) {
        t.fadeOut()
    };
    $(this).html('More')
});

Here is a demo: http://jsfiddle.net/At3bL/1/

Upvotes: 2

Related Questions