Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading