0

This has been in my mind for a long while now and I can't seem to figure it out myself. Neither do I find any useful information about this, out there, so I hope to get some answers here instead.

I'm using jQuery which is integrated into my site, together with a lot of PHP GET parameters to control what content you're watching. However jQuery doesn't seem to be available when code inside an if-block with a GET parameter tries to reach it.

Example PHP:

if($_GET["page"]) {
    echo "<div class='box'>Click me</div>";
}

Example jQuery:

$(".box").click(function() {
    alert("Box!");
});

When you press "Click me", nothing would happen, as it the jQuery code doesn't exist. Why is this happening and is there any workarounds for this?

P. Nick
  • 955
  • 1
  • 12
  • 33
  • Do you get any errors in your console? Do you get your GET parameters with AJAX call perhaps (resulting in missing element .box from DOM on page load)? – andrew Jan 21 '16 at 12:06

1 Answers1

0

Please try below:

$(document).on("click",".box",function(e){
  alert('box');
});
Vipin Sharma
  • 421
  • 5
  • 24
  • This is correct. Will work surely..can be accepted as answer – Sanchit Jan 21 '16 at 12:11
  • 1
    It does indeed work now. Would be nice if I could get an explanation of why my code doesn't work, I want to understand what I did wrong. – P. Nick Jan 21 '16 at 12:12