To add to the already working solutions with a little more detail.
Document Ready
First, make sure your code is either placed at the bottom of your body
or inside a document ready, similar to the below, to make sure the element is in the DOM at the time your code executes.:
$(document).ready(function(){
... your code here...
});
$("#mybutton")
will otherwise not be in the DOM yet when the code executes and no event will be bound.
Variable hoisting
If that is not the issue and the event is bound you may find that the way your code is written causes the error: Uncaught ReferenceError: hideelement is not defined
The reason for that is variable hoisting
$("#mybutton").on("click", hideelement);
hideelement = function(){
$(this).hide();
}
The above code is actually interpreted by the JavaScript interpreter as follows:
var hideelement; // declaration was hoisted to the top of the scope
$("#mybutton").on("click", hideelement); // at this point hideelement is still 'undefined'
hideelement = function(){ // assignment of the value stays within the lexical scope
$(this).hide();
}
JavaScript will hoist the declaration to the top of the current scope but will leave the assignment in the lexical scope where it was defined.
However, if you change your declaration to this:
$("#mybutton").on("click", hideelement);
function hideelement(){
$(this).hide();
}
JavaScript now interprets the above code as follows:
function hideelement(){
$(this).hide();
}
$("#mybutton").on("click", hideelement); // hideelements is defined
As hideelements
is no longer an assignment but only a declaration the complete function will be hoisted and as such is defined at the time it is used by your event binding.
DEMO
Naturally off course the already suggested solution in the other answer of defining your assignment lexically before the use of it will also work. i,e:
hideelement = function() {
$(this).hide();
}
$("#mybutton").on("click", hideelement);
For the sake of simplicity I intentionally did not go into global
scope and the differences with using var
.