user3011784
user3011784

Reputation: 839

bizarre behaviour of javascript in load ajax data on first try

I have a page (shop.php) where on DIV click, I do an overlay popup and I load ajax data from another PHP page (detail.php) like this:

HTML of shop.php:

<div class="box-item2" 
 style="background:url(<?=$img_path?>); 
        background-size:cover;
        background-position: 50% 50%; 
        overflow:hidden;
        width:100%; height:420px; "

onclick="clicked(this);"

id="<?=$prod_id?>">


    <div class="overlay">&nbsp;</div>
    <span class="txtover">VIEW DETAILS</span>
</div>  

MY JS FUNCTION of shop.php:

function clicked(div) {

   var id = div.id;
   $("#overlay3-content").html("");
   $.ajax({
       type: "GET",
       url: "detail.php",   
       data: {id: id},
       dataType: "html",   //expect html to be returned                
       success: function(response){                    
           $("#overlay3-content").html(response); 
            }
      });

   $("#overlay3").css("display", 'block').css("opacity", '1');
   $("#mask").css("display", 'block').css("opacity", '1');
   $("#container_close").css("display", 'block').css("opacity", '1');
}

When I execute this, there is no problem, the Overlay Popup loads well with the code from detail.php.

HOWEVER, inside detail.php, I use another javascript function to change a div background-image on a thumbnail click. JS Code as follow:

JS CODE from inside detail.php

$('.image_thumb').click(function(){

  var url = $(this).attr("id");
  $('#image_main').css('background-image', 'url(url)');
});

MY PROBLEM. When I first load my page shop.php (after a refresh), I click a DIV and the popup Opens, but the JS function inside (detail.php) to click on a thumbnail to change the background-image doesn't work.

If I exit the overlay Popup (without refreshing), and re-open the overlay popup, then the JS function on detail.php to change the background-image works.

It seems that I need to open the popup, close it, and re-open it again for it to work properly and I have no idea why. If I try my code by going directly to detail.php (by bypassing the load popup process of shop.php), then it works right away. No problem there

So it seems that the load popup is missing something on the first try to execute the JS of detail.php

Any ideas ? Thanks

Upvotes: 1

Views: 43

Answers (2)

user3011784
user3011784

Reputation: 839

I found my mistake. Somehow I had this in my detail.php page that was causing the problem.

once I removed it, everything worked

Upvotes: 0

cssyphus
cssyphus

Reputation: 40038

Just a guess, but try it like this:

$(document).on('click', '.image_thumb', function(){
  var url = $(this).attr("id");
  $('#image_main').css('background-image', 'url(url)');
});

Upvotes: 1

Related Questions