Search code examples
jqueryfunctionreferencethisself

jQuery reference to self in custom function initialize


another challenge - this is more for cleaner looking code than a "how do I". Here's the idea.

<section id="projector" data-start-at="7">....</section>

in JS

$('#projector').projector_slider({'startFrom' : parseInt( REF TO DATA-START-AT )});

I am calling a custom function on a HTML element. Simple. The function has an option called "startFrom" indicated by an INT. The INT is stored in an attribute attached to the HTML element. What I want is to NOT have to find $('#projector') in the DOM again.

Is there a way I can get a reference to the Projector inside the function call - something like $(this).attr('data-start-at)?

Obv I can solve this by looking up the element again and accessing it directly, Im asking the question in the hopes of learning a new 'this' reference trick while cleaning up my JS.


Solution

  • No, you can't. You should save $('#projector') in a var and use it:

    var projector = $('#projector');
    
    projector.projector_slider({
        startFrom: parseInt(projector.data('start-at')),
    });
    

    Notice that I use [.data()][data] instead of .attr('data-*'). The data() function is created by jQuery and is a smart way to interact with data-* attributes. For instance, if you have data-first=true and use .data('first') you will get a boolean 'true' and if you have data-children="['foo', 'bar']" you will get an object if you use .data('children').