Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event is not working on Ajax loaded content

I am loading content using ajax from external HTML Files. Dont know why after loading content, click event is not working in safari (mobile safari as well) on any of the newly loaded elements (ul, li, images etc). However this is working in mozilla.

I am not able to understand the exact issue behind this. Please advice me the solution. Below is the code for reference.

Note: I am using the below code under jquery ready function. Is jquery is the cause of issue??

var currentBottle = this.title; var request = createRequest(); if (request == null) { alert("Unable to create request"); return; } request.onreadystatechange = showContent; request.open("GET", currentBottle + ".html", true); request.send(null);

function showContent() { if (request.readyState == 4) { if (request.status == 200) { document.getElementById("food_scroller").innerHTML = request.responseText; } } }

like image 595
user504023 Avatar asked Dec 08 '22 00:12

user504023


2 Answers

Event binding breaks down when the content of a page loaded through ajax. You have to bind the events again in the document using the below procedure.

do this

$(document).on('click', '.classname' ,function (e) {
    // write your logic
});

instead of

$('.classname').on('click' ,function (e) {
    // write your logic
});
like image 174
Umar Raza Avatar answered Dec 09 '22 12:12

Umar Raza


In Safari the content-type can sometimes matter, make sure the response type is set as text/html. Also in your AJAX loaded content you should try not to have <script> tags I don't think Safari respects those sometimes.

Maybe try to use jQuery's $.load() to GET HTML content cross-browser compatible (below is equivalent to your createRequest and showContent functions):

var currentBottle = this.title;
$.load(currentBottle + ".html",
    function(responseText,textStatus,XMLHttpRequest){
        $("#food_scroller").html(responseText);
        //bind you on click events here
        $("#food_scroller").find("ul, li, images").click(myClickFunction);
  }
);
like image 25
Steven Avatar answered Dec 09 '22 14:12

Steven