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)
    <div class="formClass">
        <div id="mywistpetal">

This fails however:

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

<button onclick="mywFunction()">Petals!</button>
    function mywFunction() {

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


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 Cancel reply