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…
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(/rn|r/g, "n")
.trim()
.split("n");
lines = content
.replace(/rn|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
2
Answers
You’re executing
click()
before the AJAX request resolves.I would suggest simply triggering a click after registering the listener.
You have to call it after their listener attached! First, you must add a listener and then trigger your click event.