I have the following script:
// dashboard maximize
$('#dashboard-actions .btn-maximize').click(function() {
// max / restore buttons
$(this).removeClass('btn-maximize').addClass('btn-restore');
$(this).find('span').removeClass('icon-maximize').addClass('icon-restore');
// swap tables
$('#table-dashboard-actions-mini').hide();
$('#table-dashboard-actions').show();
// show form
$('#form-dashboard-actions-btm').show();
// restyle panel
$(this).parents('.panel-dashboard').addClass('panel-dashboard-max');
// animate panel
$(this).parents('.panel-dashboard').animate({
width: "100%",
}, 250, function() {
// Animation complete.
});
$(this).parents('.panel-primary').animate({
height: "725px"
}, 250, function() {
// Animation complete.
});
});
As you can see, at one point the script changes the class of the clicked button to .btn-restore
However this means that I cannot seem to bind an event to .btn-restore
I originally had this:
// dashboard restore
$('#dashboard-actions .btn-restore').click(function() {
alert('asdf');
});
And the alert statement didn't work, so I changed it to this:
$('#dashboard-actions .btn-restore').on('click', function() {
But still no joy. Can anyone see what I'm doing wrong?
As a couple of people have mentioned, event delegation is the key to binding to selectors that don't match yet. The alternative suggestion of binding to the generic selector
.button
that will always exist and then maintaining the state (maximised or restored) in a variable is also valid.Your issue with the panel opening and then immediately closing seems to be that you add the
.btn-restore
class inside the event handler immediately. It shouldn't happen, but it seems like the click event is firing again on the new selector (perhaps something to do withmouseup
andmousedown
components of theclick
event?). I'd suggest wrapping youraddClass
calls within asetTimeout()
like so to ensure the classes are changed after any events fire, essentially "pushing" the change to the end of the current execution:You'll notice the new variable
$btn
. This is required becausethis
inside yoursetTimeout
function will no longer refer to the clicked element (a quick search for "javascript scope and this" or similar will explain this further if required). It also doesn't hurt to cache the $(this) result in any case.Hope that works for you - let me know if I can be of further help.