Reputation: 218
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
Upvotes: 1
Views: 1709
Reputation: 388316
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
Upvotes: 2