-2

I have the following button in my ASPX page -

 $('#btnHello').click(function () {
   alert('Hi there');
 });

Which works as expected and presents the alert, however I want to move this event into my global.js file with the exact same logic. I am referencing this file at the top of my ASPX page however the event is not firing. How can I achieve this?

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
Ebikeneser
  • 2,582
  • 13
  • 57
  • 111

3 Answers3

1

Use event delegation:

$(<parent_of_btnHello>).on("click", "#btnHello", function () {
    alert('Hi there');
});

..where <parent_of_btnHello> should be an element that is loaded when the handler is added. For example:

$("body").on("click", "#btnHello", function () {
    alert('Hi there');
});

It also can be $(document) or $("html") or any container of your button, that is loaded the the code from global.js file is executed.

You may check this answer too.


Another way is to put your initial code inside of $(document).ready(function () { ... });:

 $(document).ready(function () {
   $('#btnHello').click(function () {
      alert('Hi there');
    });
 });
Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
0

Most likely there is no such element when you are trying to bind an event.

Try to wrap your code with document.ready

$(function() {
   $('#btnHello').click(function () {
      alert('Hi there');
   });
})
Vytalyi
  • 1,637
  • 3
  • 20
  • 33
0

What you're executing is a function, at the very beginning:

 $('#btnHello').click(function () {
    alert('Hi there');
 });

You're hooking up your alert function to the element #btnHello.

But at the time it executes, #btnHello hasn't been loaded. It doesn't exist yet. So nothing gets hooked up.

You can get around this either by executing your code at the very end, or (more reliably, I think) deferring this code's execution until the document has finished loading:

$(function () {
    $('#btnHello').click(function () {
       alert('Hi there');
     });
 });

You would put this in your global.js, but it wouldn't execute until your page is completely loaded.

Ann L.
  • 13,760
  • 5
  • 35
  • 66