0

I have this JQuery code and a link below the JS code. It doesn't seem to work if the link is below the JS code, but it works if the JS code is below the link.

How can I get it working with the JS code above the link? I need to do it this way because I have the JS code in a file that I include using PHP include.

<div id="EditPage" class="EditPagePopup">
<iframe id="EditPageFrame" width="100%" height="80%" src=""></iframe>
<a id="JQueryClose">&#215;</a>
</div>
<script>
$("a#EditPageLink").click(function (e) {
    alert("f");
    e.preventDefault();
    $("#EditPageFrame").attr("src", $(this).attr("value"));
    $("a").removeClass("active");
    $(this).addClass("active");

    JQueryPopup('#EditPage');
});
</script>

<a id="`EditPageLink`" href="#" value="editcustomer.php?seq='.$customer["sequence"].'"
soktinpk
  • 3,778
  • 2
  • 22
  • 33

3 Answers3

3

It doesn't need to be, but it's recommended to be. Read this previously asked question.

What you should definitely do, is use jQuery's ready function to ensure the DOM has finished loading before attaching your events. For example:

$(function() {
    $("a#EditPageLink").click(function (e) {
        alert("f");
        e.preventDefault();
        $("#EditPageFrame").attr("src", $(this).attr("value"));
        $("a").removeClass("active");
        $(this).addClass("active");

        JQueryPopup('#EditPage');
    });
});

Doing that will attach the event correctly, regardless of where your script tag appears in the html.

Community
  • 1
  • 1
David Sherret
  • 101,669
  • 28
  • 188
  • 178
0

When the code is above the html, then it might get executed before the DOM is fully loaded. It's recommended to put your javascript that depends on the DOM at the bottom of the page to avoid this problem.

mowwwalker
  • 16,634
  • 25
  • 104
  • 157
0

Having scripts all the way to the bottom has become the usual practice because that way the browser can render the page and load and run scripts last.

It used to be all scripts inside the head tag, way back then. But really you can put the script wherever, having all in one place (top or bottom) makes your markup readable and maintainable.

Rodrigo
  • 234
  • 1
  • 6