Reputation: 6555
New to jQuery and I want to create an external js file that when a button is click it shows an alert message.
This is what I have tried:
(function($){
events: function(){
$('#myModal').bind('click', function(e){
alert("test");
});
}
})(jQuery,window,document);
I get an error:
SyntaxError: function statement requires a name
What I'm I doing wrong and is this the correct way?
Upvotes: 0
Views: 5065
Reputation: 298166
You can make events
a key in an object:
(function($){
var o = {
events: function(){
$('#myModal').bind('click', function(e){
alert("test");
});
}
};
})(jQuery,window,document);
Or a named function:
(function($){
function events() {
$('#myModal').bind('click', function(e){
alert("test");
});
}
})(jQuery,window,document);
Or get rid of the function
stuff altogether:
(function($){
$('#myModal').bind('click', function(e){
alert("test");
});
})(jQuery,window,document);
Without knowing what events:
was for, it's hard to say.
Upvotes: 2
Reputation: 165971
I'm not entirely sure what you're aiming for, but what you've got is a labelled function declaration with no identifier (hence the syntax error).
If all you need to do is bind an event handler, why do you need that function at all? Is this what you were aiming for?
(function($){
$('#myModal').bind('click', function(e){
alert("test");
});
})(jQuery,window,document);
Alternatively, you may have intended events
to be the key of an object:
(function($){
var someObj = {
events: function () {
$('#myModal').bind('click', function(e){
alert("test");
});
}
};
})(jQuery,window,document);
But it's hard to tell without knowing what you actually want to acheive.
Upvotes: 3
Reputation: 40318
You can bind the event as follows
(function($){
$('#myModal').bind('click', function(e){
alert("test");
});
})(jQuery,window,document);
or
$('#myModal').click( function(e){
alert("test");
});
Upvotes: 1