Reputation: 8156
Why isn't this working? ---HTML--------
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="j.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$.createHello();
});
</script>
</body>
</html>
---JS---------j.js-------
(function($){
$.fn.createHello= function() {
$('body').append('<div id="hello">Hello world</div>');
$('#hello').click(funciton(){
alert("Hello you clicker");
});
};
})(jQuery);
Any solutions, or better ways to do the same thing?
Upvotes: 2
Views: 64
Reputation: 35309
Change the click
to delegate
since you are creating the hello element on the fly. Below is the updated code. Also function was misspelled,
$.createHello = function() {
$('body').append('<div id="hello">Hello world</div>');
$('body').delegate('#hello', 'click', function(){
alert("Hello you clicker");
});
}
$(document).ready(function(){
$.createHello();
});
Personally this is how I would write it:
$.fn.createHello = function() {
$(this).append('<div id="hello">Hello world</div>');
$(this).delegate('#hello', 'click', function(){
alert("Hello you clicker");
});
}
$(document).ready(function(){
$('body').createHello();
});
This allows you to tie it to any element on the page and call createHello()
I also suggest checking out the plugin authoring reference for some good tips.
Upvotes: 1
Reputation: 69905
createHello
plugin is appending a div with some content to the body element. In order to attach a click event you should select the element and the refer to it using this
keyword inside the plugin code. Try something like this
Add this markup in your test page
<div id="hello">Click me</div>
JS
$.fn.createHello= function() {
$('body').append('<div id="hello">Hello world</div>');
this.click(funciton(){
alert("Hello you clicker");
});
};
$("#hello").createHello();
Upvotes: 0
Reputation: 95027
since you defined the plugin using $.fn.myPlugin
, you have to select an element for the plugin to work on. If you wish for the plugin to work in the way that you are using it, define it with
$.myPlugin = function(){
// your code here
}
Upvotes: 1