Sheehan Alam
Sheehan Alam

Reputation: 60879

Why isn't my button click event being triggered?

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.

Upvotes: 1

Views: 176

Answers (4)

James Allardice
James Allardice

Reputation: 165971

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.

Upvotes: 3

Starx
Starx

Reputation: 78991

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.

Upvotes: 1

ANeves
ANeves

Reputation: 6365

Did you mean $("#maximize").click( , and <a id="maximize" ... ?

Upvotes: 1

Ujjwal Manandhar
Ujjwal Manandhar

Reputation: 2244

you have not bind the button with the function

how the function will call as there is no code written to trigger the function when button is clicked

var IOMaximizeButton = {
    setup: function () {
        $("#button").click(function(){
        console.log("maximize button was clicked!");
      });
    }
};
<a href="#" id="button">Maximize</a>

Upvotes: 1

Related Questions