0

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?

0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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");
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.