Search code examples
javascriptobjectdomdocument

Assigning object to dom element and retrieving it in function


I'm trying to build a parallax plugin by myself using vanilla js. Basically I have set it all up so it works, but what i would like to do is add some helper functions to use later on for each parallax section.

What I'm trying to achieve is being able to write something like:

document.getElementById('test').parallax.getImage();

Inside my js plugin I have defined:

var parallax = {

getImage : function(element, event){
    var img = null;
    var section = element;

    for (var i = 0; i < section.childNodes.length; i++) {
        if (section.childNodes[i].className == "parallax-image") {
          img = section.childNodes[i];
          break;
        }        
    }
    return img;
},

}

and later on in initiation i assign the object to the dom element:

function setupParallax(){
    // this get all sections
    var sections = self.methods.getSections();

    for (var i = sections.length - 1; i >= 0; i--) {
        sections[i].parallax = parallax;
    }
}

So in the getImage() function of the parallax object, I want to retrieve the element the parallax object is assigned to. How do I go about that?


Solution

  • To extend the native Element by a parallax namespace object which has methods like .getImage()

    document.getElementById('test').parallax.getImage()
    

    you can use Fn.prototype.call() to forward the current section Element to a set of (_parallax) methods which will be accessible by using Element.parallax

    const Parallax = (selector) => {
    
      const
        _el = document.querySelector(selector),
        _sections = _el.querySelectorAll('.parallax-section'),
        _parallax = section => ({
          getImage() {
            return section.querySelector('.parallax-image');
          },
          // more section parallax methods here
        }),
        methods = {};
    
    
      methods.getSections = () => _sections;
      methods.someOtherMethod = (arg) => {
        return arg;
      }
    
      // Init
      [..._sections].forEach(section => section.parallax = _parallax.call(null, section));
    
      // Expose methods
      return methods;
    
    };
    
    
    // Init Parallax on some parent
    const myPar = Parallax('#container');
    
    // Testing stuff:
    console.log( document.getElementById('test').parallax.getImage() );
    console.log( myPar.getSections() )
    <div id="container">
    
      <div class="parallax-section">
        <img class="parallax-image" src="//placehold.it/20x20/0bf">
      </div>
    
      <div id="test" class="parallax-section">
        <img class="parallax-image" src="//placehold.it/20x20/f0b">
      </div>
    
    </div>

    The above's getImage() is the exact simpler way of your getImage() method. If section.querySelector('.parallax-image') finds no image, it will return null - just like your code does.