a-kile a-kile - 1 year ago 60
HTML Question

Button is not changing the html?

I'm trying to make a function where the button can be clicked so that new text/and elements can be added to the page, but it's not working, I've tried to check why, but all of my syntax seems to be correct. But yet it's not working

Recipes = {};

function Recipe(name, origin, auther, ingredients, directions) {
this.name = name;
this.origin = origin;
this.author = auther;
this.ingredients = ingredients;
this.directions = directions;

Recipe.prototype.printRecipe = function(){
var text = "";
for (var i=0; i < Object.keys(this).length; i++) {
text += "<br/>" + this[Object.keys(this)[i]];
return text;

var Salad = new Recipe("Fruit Salad", "Unknown", "Unknown", "Apples, Bananas, Berries, Milk, Sugar, Dry fruits", "<ul><li>sdasds</li></ul>");

function AddRecipe(){
document.getElementById("text").innerHTML = Salad.printRecipe();

<p id="text">
To be vanished by javascript

<button onclick="AddRecipe()">Display Recipe</button>

Answer Source

As @nnnnnn mentioned in the comments, JSFiddle defaults you placing your code within an onload event handler. Everything except Recipes is defined in that scope. When the onload handler is finished, everything local to that scope is lost unless you store it somewhere accessible outside that scope.

For a simple fix, add this at the bottom of your code:

window.AddRecipe = AddRecipe;

This will put AddRecipe in the global scope, making it accessible to the button's onclick event. Due to AddRecipe's closure, everything that was with it is still accessible to AddRecipe even if it's hidden from everything else.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download