0

Will try to explain the issue, sorry if it doesn't make sense: I'm trying to update a variable inside an object while looping. Trying to target all the parents of class elements to use on scrollmagic plugin. This is what my code looks like:

var childElement = $('.child');
var myparents = [];

    var getParent = function () {
        childElement.each(function() {
            var theParent = $(this).closest('.parent');
            myparents.push(theParent);
        });         
    }();    

    for (var i=0; i<childElement.length; i++) {
        // also using the loop to add animation to every element, 
        // that's why the loop through other elements
        new ScrollMagic.Scene({
            // here is where I would need to access each
            triggerElement: myparents[i],
            triggerHook: 'onEnter'
        })
    }

The elements are added successfully to the array, and can use them, but can't access them inside this scrollmagic (object?). Thanks a lot to anyone for providing assistance.

1
  • Just because you call a method (ScrollMagic.Scene) and pass in an object {triggerElement: thing, triggerHook: thing2} doesn't mean those values will necessarily be available as properties of your object. That would depend on the scrollmagic API. Commented Dec 11, 2015 at 13:47

2 Answers 2

1

You could easily use a shorter version of your code that is less prone to errors and way easier to use 'as a self-contained module', since it's not polluting the scope.

$('.child').each(function(){
    var $child = $(this),
        $parent = $child.closest('.parent');
    $child.data('scrollMagic',new ScrollMagic.Scene({
        triggerElement: $parent[0],
        triggerHook: 'onEnter'
    });
});

whenever you now need access to the scrollMagic object when you know the child, you can just access $(<childElement>).data('scrollMagic')

However, if the object itself is available in the onEnter hook depends on how the scrollMagic plugin is implemented. That has nothing to do with this code.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad to help! if you continue down the path of jQuery/webdev/javascript in general: keep this example in mind of how you can easily create self-contained code :-)
0

Why don't you use like this :

var childElement = $('.child');
 childElement.each(function() {
    var theParent = $(this).closest('.parent');
    new ScrollMagic.Scene({
       triggerElement: theParent,
       triggerHook: 'onEnter'
    });
 });

2 Comments

This was actually my first approach, but unfortunately didn't work
can you try to pass a parameter inside each(function(passedParamter) ..) and use $(passedParameter).closest instead of $(this) ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.