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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.