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.
No, you can’t. You should save
$('#projector')in a var and use it:Notice that I use [
.data()][data] instead of.attr('data-*'). Thedata()function is created by jQuery and is a smart way to interact withdata-*attributes. For instance, if you havedata-first=trueand use.data('first')you will get a boolean ‘true’ and if you havedata-children="['foo', 'bar']"you will get an object if you use.data('children').