I am attempting to create a div element and when it is clicked it creates a new element. In my case the new element is a styled p element. When the p element is clicked it creates a new li element within the p element. I made this work by having one large function but I am attempting to structure my code. My new structuring is clarifying but presenting me problems.
The below code works except when I click on the grey circles it does not create a new small green circle, which is what it should do. The error I get says the synth variable is not accessible. However, when I make the synth variable global I get another problem, I can only launch the createSynth function once…. and hence I can’t create multiple grey circles.
So in short I think the trick is to make the synth variable local and globally accessible (or at least accessible to the function that needs it…global variables are BAD!) From what I’ve read this is the perfect case for using a closure. However my understanding of closures is hazy and I figure this might be the optimal example for me to actually get my hands on one and "really get it" assuming I can be lead to water so-to-speak. Below is the code as well as a JS fiddle with the html and css element.
I think I could probably solve this by just passing a function to an argument (some how) but I am always curious how others more experienced than I am solve problems and structure code.
http://jsfiddle.net/taoist/rfFtY/1/
$(function() {
var orangeButton;
var applicationArea = document.getElementById("applicationArea"),
orangeButton = document.getElementById("orangeButton"),
counter = 1;
var createSynth = function() {
var synth = document.createElement("p");
synth.id = "synth" + (counter++);
applicationArea.appendChild(synth);
$(synth).draggable({ snap: true });
$(synth).draggable({ grid: [ 20,20 ]});
};
var createParameter = function () {
var synthParams = document.createElement("li");
synthParams.id = "synthParams" + (counter++);
synth.appendChild(synthParams);
$(synthParams).draggable({ snap: true });
$(synthParams).draggable({ grid: [ 20,20 ] });
};
orangeButton.addEventListener("click",createSynth, false);
synth.addEventListener("dblclick",createParameter, false);
});
I would solve it this way:
I added event listener to synth at the end of this function, so every created synth can react to events.
I used “this” instead of “synth”. As createParameter will handle an event for particular synth, that synth will become “this” in that function.
JSFiddle: http://jsfiddle.net/sU3uy/1/