JavaScript plugin options

110 views Asked by At

A want to create a pure JavaScript plugin. Is it possible to set options in HTML file like if I set options for jQuery? If yes, how?

Example options in jQuery:

$(document).ready(function(){
    $("#myID").myFunction({
      folded: true,
      defaultSlide: 1
    });
});
3

There are 3 answers

0
hsz On

You can set extra attributes to the specified HTML element and just read them when you need:

<div id="myID" data-foo="bar"></div>

And in JavaScript:

var element = document.getElementById('myID'),
    foo = element.getAttribute('data-foo');
0
T.J. Crowder On

If you're talking about the

{
  folded: true,
  defaultSlide: 1
}

in the quoted code, that has nothing to do with jQuery at all, it's just a JavaScript object initializer. Yes, your function can accept one and work with it:

function myFunction(options) {
    // use options.folded
    // use options.defaultSlide
}

The first part of your quoted code, the $(...), is jQuery. To do something similar without jQuery, you'll obviously need to write that bit.

Here's an example that accepts options and sets the color of matching elements:

function myFunction(selector, options) {
  var list = document.querySelectorAll(selector);
  var color = options.color || "red";
  var i;
  for (i = 0; i < list.length; ++i) {
    list[i].style.color = color;
  }
}

myFunction(".foo", {color: "blue"});
setTimeout(function() {
  myFunction(".bar", {color: "#008000"});
}, 300);
<div class="foo">foo</div>
<div class="bar">bar</div>
<div class="foo">foo</div>
<div class="bar">bar</div>
<div class="foo">foo</div>
<div class="bar">bar</div>

3
IonDen On

Yes, it is possible. Check for example config for this pure JS plugin: http://ionden.com/a/plugins/ion.sound/demo_advanced.html

// create sound
ion.sound({
    sounds: [
        {name: "witchdoctor"}
    ],

    path: "static/sounds/",
    preload: true,
    multiplay: false
});