user3686630 user3686630 - 7 months ago 137
Javascript Question

JavaScript onTap functions

Still new to the forums, so I'll try my best to get across the problem. Basically I'm developing a mobile web app, and have several ontap functions for reloading the webpage after buttons clicked. Here is the code for two of my smaller onTap functions for demonstration purposes (so you don't have to sift through hundreds of lines of code). The licenses_button ontap function works perfectly fine, with no forms of errors whatsoever, but the back_button ontap function, and all other buttons that aren't created on the initial main page of the app won't act as button's and I have no idea why. Any advice? (I know the back_button has little to no content, I just removed a lot of it for debugging purposes and even this fails to work). Thanks for any advice!

$("#licenses_button").onTap(function(event){
$("#play_button").remove();
$("#banner").remove();
$("#licenses_button").remove();
$(".cloud").remove();
$(".cloudalternate").remove();


$("body").append("<div id='back_button'>Back</div");
});


$('#back_button').onTap(function(event) {

$('#back_button').remove();

});

Answer

$(selector).onTap(callback); attaches the handler to the selected elements at the moment it is called. Elements that are not yet created at this time cannot be selected (obviously since they do not exist yet) and thus, won't get the handler. You need to attach the handler after you added an element.

For example:

$("#licenses_button").onTap(function(event){
    $("#play_button").remove();
    $("#banner").remove();
    $("#licenses_button").remove();
    $(".cloud").remove();
    $(".cloudalternate").remove();

    // Create the button.
    var backButton = $("<div id='back_button'>Back</div");
    // Append it to the body.
    $("body").append(backButton);
    // Attach the handler to the new button.
    backButton.onTap(function(event) {
        backButton.remove();
    });
});