September 26, 2011
Why isn't my button click event being triggered?
Question by Sheehan Alam
I have the following js file:
var IOMaximizeButton = {
setup: function () {
$(this).click(function(){
console.log("maximize button was clicked!");
});
}
};
$(document).ready(function() {
IOMaximizeButton.setup();
});
Here is the body of my HTML:
<body>
<a href="#" data-role="button" data-icon="delete">Maximize</a>
<iframe id='iframe-primary' name='iframe-primary' src='foo.html' />
<iframe id='iframe-secondary' name='iframe-secondary' src='bar.html' />
</body>
I want that javascript to execute when my button is clicked. But it doesn’t seem to be triggering. Why?
I have imported my JS file at the bottom of the HTML page btw.
Answer by James Allardice
In your object, this
refers to the instance of the object itself, so you’re trying to bind a click event to the JavaScript object, rather than a DOM element. I’m guessing you actually want something like this:
var IOMaximizeButton = {
setup: function () {
$("#yourButton").click(function(){
console.log("maximize button was clicked!");
});
}
};
Here’s a working example.
Answer by Starx
Your function is not attached to any selector, so I cannot catch any events. $(this) is a blank object.
Try changing $(this) to some specific selectors.