JQuery can load function fine, but onclick not

This works fine:

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
<script type="text/javascript">
if (new Date().getMonth()===0)
{
$(document).ready(function(){
    $("#mywistpetal").load("https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/site/effects/wisteria_petal_rain.html");
});
}
</script>
    <div class="formClass">
        <div id="mywistpetal">
        </div>

This fails however:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button onclick="mywFunction()">Petals!</button>
<script>
    function mywFunction() {
        $("#mywistpetal").load("https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/extrafiles/site/effects/snowflake.html");
    }
</script>


<div class="formClass">
    <div id="mywistpetal">

    </div>
</div>

Why ?

Is it different ?
(I removed the onload as this is user tiggered)

>Solution :

When your second example function is called, the browser has not yet "seen"/"read" the div with id mywistpetal so it is undefined.
Browser reads page from top to bottom and executes your code before reading the rest of the html code.
For this reason you must either

  • wait for dom to be ready using the $(document).ready event handler (all page is read, to the end), as in your first example or
  • put the script tag after the div you want to use

Leave a Reply