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

Hiding button by "Id" works, but clicking it not

I execute the top portion here automatically.

In this script I can easily hide "showLine" via document.getElementById("showLine").style.visibility="hidden"; no problemo,

but document.getElementById("showLine").click(); will not fire no matter what I do…

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

The button does not press onload..

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

//Autoexecute on pageload
<script type="text/javascript">
  $(document).ready(function () {
    document.getElementById("showLine").click();
    //document.getElementById("showLine").style.visibility="hidden";
  });
</script>

//script with button "showLine"
<script>
  var lines;
  var randomNumber;
  var lastRandomNumber;
  $(document.body).ready(function () {
    $.ajax({
      url: "https://ry3yr.github.io/OSTR/Diarykeepers_Homepage/Daymusic_array.js",
    }).done(function (content) {
      lines = content
        .replace(/\r\n|\r/g, "\n")
        .trim()
        .split("\n");
      lines = content
        .replace(/\r\n|\r/g, "quote")
        .trim()
        .split("quote");
      // ^^ line rmvl ^^^
      if (lines && lines.length) {
        $("#showLine").on("click", function () {
          while (randomNumber === lastRandomNumber) {
            randomNumber = parseInt(Math.random() * lines.length);
            if (lines.length === 1) {
              break;
            }
          }
          lastRandomNumber = randomNumber;
          $("#trivia").html(lines[randomNumber]);
        });
      }
    });
  });
</script>

<button id="showLine">CurrListening</button>
<p id="trivia"></p>

So how do I fix this clicking not working ?

PS:
I commented out the button, cause I used the visibility just for test purposes

>Solution :

You’re executing click() before the AJAX request resolves.

I would suggest simply triggering a click after registering the listener.

$("#showLine")
  .on("click", function () {
    while (randomNumber === lastRandomNumber) {
      randomNumber = parseInt(Math.random() * lines.length);
      if (lines.length === 1) {
        break;
      }
    }
    lastRandomNumber = randomNumber;
    $("#trivia").html(lines[randomNumber]);
  })
  .trigger("click");
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