How Do I Make A Button Reusable?
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 sc
Solution 1:
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.
Solution 2:
As has already been stated, your main issue is just that the creation of the insult is outside of your function, so it is only created once, rather than each time the function is called. I really enjoy re-factoring code, I wanted to offer you this: (click here for live demo)
I have written your app using an object oriented pattern and cleaning up a lot of mess and inefficiency. I think it will do you a lot of good to study this and learn all you can!! By the way, don't ever use inline javascript (the click function in your html) unless you're using a framework that makes sense of it (like AngularJS).
<p id="insult">Your insult will appear here!</p>
<button type="button"id="generate">Generate Insult</button>
and the js:
var generator = { //only one global variable!!init: function() { //this sets up your app for usevar elem = document.getElementById('insult');
var obj = this; //cache reference to the generator object (the "this" pointer will be changed within the click functionvar button = document.getElementById('generate');
button.addEventListener('click', function() {
elem.innerText = obj.generateInsult();
});
},
generateInsult: (function() { //use an IIFE to give a nice closure to these variablesvar generateInsult = function() {
return"Thou art a "+adjs1[r(adjs1)]+", "+adjs2[r(adjs2)]+", "+nouns[r(nouns)]+"!";
};
functionr(arr) {
returnMath.floor(Math.random() * arr.length);
}
var adjs1 = ["artless", "bawdy", "beslubbering"];
var adjs2 = ["base-court", "bat-fowling", "beef-witted"];
var nouns = ["apple-john", "baggage", "barnacle"];
return generateInsult;
}())
};
generator.init(); //I suggest running this on document ready to be sure the elements are loaded. If not, this will not work. Keep that in mind!
Post a Comment for "How Do I Make A Button Reusable?"