Attach To Click Event Outside Page
Solution 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');
});
});
Solution 2:
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.
Solution 3:
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');
});
})
Post a Comment for "Attach To Click Event Outside Page"