1

I want to make simple plugin to show alert if class is binding by a jquery plugin.

below is my html code

 <html>
 <head>
 <script src="js/modal-load.js"></script>
 <script>
  $(document).ready(function(){
      $('.modal-link').modalLoad();
  })
 </script>
 </head>
 ....
 <body>
      <div class="hblock-1 text-4 text__uppercase color-7">
            <a class="login btn btn-primary modal-link" href="/login-modal.php" data-toggle="modal" data-target="#login-modal">Log in</a>
            <a href="index.html#" class="register btn btn-primary modal-link">Register</a>
      </div>
 </body>

This is my plugin script

 (function($){

     $.modalLoad = function(element, options){

         var defaults = {
             foo: 'bar',
             onFoo: function() {}
         }

         var plugin = this;

         plugin.settings = {};

         var $element = $(element),
             element = element;

         plugin.init = function(){
             plugin.settings = $.extend({},defaults, options);
             plugin.add_bindings();
         }


         plugin.add_bindings = function(){
             this.click(function(){
                 alert('a');
             })
         }

         plugin.create_modal = function(){
             $('body').append('<div class="modal-wrapper"></div>');
         }

         plugin.init();

     }

     $.fn.modalLoad = function(options){

         return this.each(function(){
             if(undefined == $(this).data('modalLoad')){
                 var plugin = new $.modalLoad(this, options);
                 $(this).data('modalLoad', plugin);
             }
         });

     }

 })(jQuery);

In html code, i've initialized modalLoad plugin. But when particular class that i've bind, it won't be triggered by click event.

What's wrong with my code? is any mistake with my DOM selector in add_bindings part?

Thanks for advance

*edited

1
  • You have a missing ) at the end of $(document).ready(function(){ $('.modal-link').modalLoad(); }-- $(document).ready(function(){ $('.modal-link').modalLoad(); }) Commented Mar 23, 2015 at 7:07

1 Answer 1

2

You need to attach the click handler to $element not this. Inside add_bindings, this refers to the plugin object not the clicked element so this will not have a method named on(You should get an error like Uncaught TypeError: undefined is not a function in your console)

    plugin.add_bindings = function () {
        $element.click(function (e) {
            alert('a');
            e.preventDefault()
        })
    }

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.