ModernCoder
ModernCoder

Reputation: 31

Start jquery pluggin

how to achieve this with jquery plugin system

 $('.selector').myPlugin(function(id){
     alert(id);
 });

How to code myPlugin plugin to make it work exactly like the code above.

That's all, Thanks

Upvotes: 1

Views: 47

Answers (3)

Siddharth Rathod
Siddharth Rathod

Reputation: 638

you can not get id from anonymous function as argument.

//create myPlugin function for manage your plugin
function myPlugin(id){
    alert(id);
    //enter your code here
}

$('.selector').on('click', function(){
    let id = $(this).attr('id');
    myPlugin(id);
});
<html>
  <head>
    <title>My plugin</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
      <button type="button" class="btn btn-primary selector" id="YourId" >Click me</button>
  </body>  
</html>

Try this script.

Upvotes: 0

Wesley Smith
Wesley Smith

Reputation: 19571

You would use the jQuery prototype $.fn to do that, here is an example. Note that i've set this up to return an array of ids because you show attaching this to a class which means that it may in fact be linked to multiple elements on the page

$.fn.myPlugin = function(callback) {
  var ids = [];
  if (typeof callback === 'function') {
    $(this).each(function() {
            ids.push(this.id);
    });
    var id = $(this).attr('id');
    callback(ids);
  }
};


$(function() {

  $('.selector').myPlugin(function(ids) {
    console.log(ids);
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="selector" id="someId1">
</div>
<div class="selector" id="someId2">
</div>

Upvotes: -1

T&#226;n
T&#226;n

Reputation: 1

You can define myPlugin function like this:

$.fn.myPlugin = function (callback) {
  var id = $(this).prop('id');

  if (typeof callback === 'function') {
    callback(id);
  }
};

$('.selector').myPlugin(function(id){
   alert(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="greeting" class="selector">Greeting!</div>

Upvotes: 2

Related Questions