I am relatively new to the world of programming. I have a sturdy knowledge of HTML and CSS, and recently picked up JavaScript. I am working on a series of text generators as a school project; my goal is to be able to, on the website, click a button and have the computer spit out random text each time you click the button. However, while I have a good grasp on HTML and JavaScript, my knowledge on how to combine the two to give a webpage functionality is virtually nonexistent.
I created a "Shakespearean Insult Generator" using JavaScript, which is functional, and I figured out how to add a button to a page so that when you click the button, it prints a randomly generated insult to the page:
<script>
var adjective1 = ["artless", "bawdy", "beslubbering"...
var adjective2 = ["base-court", "bat-fowling", "beef-witted"...
var noun = ["apple-john", "baggage", "barnacle"...
var insult = "Thou art a " + adjective1[Math.floor(Math.random() * 60)] + ", " + adjective2[Math.floor(Math.random() * 60)] + ", " + noun[Math.floor(Math.random() * 60)] + "!";
var genInsult = function() {
x=document.getElementById("replace");
x.innerHTML=insult;
};
</script>
<p id= "replace">Your insult will appear here!</p>
<button type="button" onclick="genInsult()">Generate Insult</button>
However, once you press the button once, you cannot press it again to generate another insult unless you refresh the page.
So my question is: how can I make this button reusable by using JavaScript?
I've tried searching for an answer to my question, but the problem is that I'm so new to JavaScript that I often have trouble understanding other people's questions and the answers to them. Also, a lot of responses reference jQuery, a language I do not know. If anyone has a solution within the realm of JavaScript, I would be extremely grateful!
I might not know a heck of a lot now, but I am very eager to learn!
Move this:
var insult = "Thou art a " + adjective1[Math.floor(Math.random() * 60)] + ", " + adjective2[Math.floor(Math.random() * 60)] + ", " + noun[Math.floor(Math.random() * 60)] + "!";
within your genInsult() function and you should be good. Right now it's outside so it will only generate once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With