user1063287
user1063287

Reputation: 10869

How to use $(this) and closest() to form the variable passed through to jScrollPane's scrollToElement?

I am wanting to scroll to the closest instance of a div using jScrollPane's scrollToElement(API link).

I was trying to use jQuery's $(this) and closest() to form the variable that would be passed through to scrollToElement.

But I think either my implementation of $(this) is incorrect or such a variable is not an acceptable parameter type as it's not triggering the scroll action.

The error message is:

Uncaught TypeError: Cannot read property 'top' of undefined

How do I use $(this) and closest() to form the variable passed through to scrollToElement?

jsFiddle

Includes example of working and non-working parameters:

http://jsfiddle.net/rwone/bUbm8/

HTML

<div id="main_content">
    <div class="click_me">CLICK ME</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <div>test</div>
    <a class="target">target</a>
</div>

jQuery

function initScrollPane(){
    var jScrollPaneSettings = {
        hijackInternalLinks: true,
        animateScroll: true,
        animateDuration: 600,
        contentWidth: '0px'
    };
    var mainContent = $('#main_content')
    mainContent.jScrollPane(jScrollPaneSettings);
    var apiMainContent = mainContent.data('jsp');
    apiMainContent.reinitialise();

    $(document).on("click",".click_me", function(e) {
        e.preventDefault();  
        // DOESN"T work
        // var myVar = $(this).closest(".target");
        // DOES work
        var myVar = $(".target:first");
        //apiMainContent.scrollToElement(".target");    
        apiMainContent.scrollToElement(myVar);
    });
}

initScrollPane();

Edit:

It is also my understanding that closest() can search down the tree which is why I used that particular method per the following link, but perhaps that understanding is incorrect:

https://stackoverflow.com/a/5139438/1063287

Upvotes: 0

Views: 1177

Answers (2)

ducdhm
ducdhm

Reputation: 1952

You use closest() wrong way. closest() for getting the closest parents(). In your case, there's 2 ways to do.

First is:

var myVar = $(this).siblings(".target");

Second is

var myVar = $(this).parent().find('.target');

Upvotes: 2

Raidri
Raidri

Reputation: 17550

You can't use closest() for this, as it works "by testing the element itself and traversing up through its ancestors in the DOM tree." (Documentation)

You need to use siblings() (Documentation) and then search for the nearest one if you have multiple targets. See this answer for an example how you could do it.

Upvotes: 0

Related Questions