Web Develop Wolf Web Develop Wolf - 3 months ago 8
HTML Question

Click Not Firing on Button

I have a html button that is hooked up to a JQuery function at the top of my page, but the click does not seem to be firing? Is there something I'm missing?

$(function(){
$('#ctl00_content_hidePast').click(function() {
var dt = new Date($.now() - 30 * 60000);
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("td.bgtime").each(function() {
var bookingTime = ($(this).text().split(':'));
var d = new Date();
d.setHours(+bookingTime[0]);
d.setMinutes(bookingTime[1]);

var state = $("#ctl00_content_hdnPastBookingToggle").val();

if ($(d) > time) {
var timeRow = $(this).parent();
$(timeRow).toggle("slow",
function() {
if (state.val === "0") {
state.val = "1";}
else if (state.val === "1") {
state.val = "0";
};
});
};
});
});
});


And the button:

<button id="ctl00_content_hidePast"><i class='fa fa-eye-slash'></i> Hide/Show Past Bookings</button>

Answer

try

$(function(){
                $(document).on('click','#ctl00_content_hidePast', function() {
                    var dt = new Date($.now() - 30 * 60000);
                    var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
                    $("td.bgtime").each(function() {
                        var bookingTime = ($(this).text().split(':'));
                        var d = new Date();
                        d.setHours(+bookingTime[0]);
                        d.setMinutes(bookingTime[1]);

                        var state = $("#ctl00_content_hdnPastBookingToggle").val();

                        if ($(d) > time) {
                            var timeRow = $(this).parent();
                            $(timeRow).toggle("slow",
                                function() {
                                    if (state.val === "0") {
                                        state.val = "1";} 
                                    else if (state.val === "1") {
                                        state.val = "0";
                                    };
                                });
                        };
                    });
                });
            });

In this case you bind the event to the document. This is usually used when you have dynamic dom elements. You don't need to bind the click event to the document. Actually it's recommended to attach it to non dynamic parent. For example the div that will contain the buttons. In that case the code would be:

  $(document).on('click','div that contains the buttons selector', function() ..

It just makes things lighter. But since I don't have the dom structure I gave you answer that will work in any case.

Comments