0

Let's say I want to make a plain JavaScript plugin.

  var myPlainJsPlugin = (function (param1,param2) {
   /*code here*/
 });

How do I attach this plugin, just after the document is loaded, to all elements with the class 'elmClass', without jQuery?

I am talking basically about making a plain JavaScript plugin and using it similar to using a jQuery plugin:

$('.elmClass').jQueryPlugin(); 

I am trying to give up jQuery for a certain project.

Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252
  • what do you mean attach it? click, hover loaded? which event and what should it do? should it just extend the HTMLElement? – Saar Oct 19 '15 at 14:42
  • Thats not a *plugin* - its just a *function*! – Jamiec Oct 19 '15 at 14:47
  • On load. Unobtrusively. – Razvan Zamfir Oct 19 '15 at 14:47
  • It's not very clear what you're asking yet :) – Dave Newton Oct 19 '15 at 14:48
  • 1
    You could take selector as a parameter, then use document.querySelectorAll to get the elements and do whatever you want... however its hard to answer without more clarification – drys Oct 19 '15 at 14:48
  • Do you want to RUN the myPlainJsPlugin() function when the user clicks on an element with the elmClass function? Still not quite clear on exactly what you mean by "attach" it. – KDot Oct 19 '15 at 14:52

2 Answers2

0
 window.onload = function(){
     var els = document.getElementsByClassName("elmClass");

     Array.prototype.forEach.call(els, function(el) {
           // Add code here 
           // e.g: el.onclick = doSomething();
     });
 };    `

`

Source: Link

Community
  • 1
  • 1
0

Try this:

    var elemtsWithClass = document.querySelectorAll(".elmClass");
    for(var x=0; x<elemtsWithClass.length; x++){
            elemtsWithClass[x].addEventListener("click", function(e) {}); 
    });
develask
  • 3
  • 3