0

I am trying to create clickable divs that will set a variable once they are clicked.

For example,

If my program had to do with playing with balls.

When a user inputs a name, and what kind of ball they want (lets say name= Johnny and Ball=BasketBall) and then clicks "Create a Ball", My program will create a div called "Ball0". The "Ball0" div will display Johnny's name. When a user Clicks on his name it will say "Johnny has a BasketBall.

Here is how I am trying to do this code

var ballRefrence = -1;

function createBall() {
    ballRefrence +=1;
    var myElement = document.createElement('div');
    myElement.id = 'individualBall'+ballRefrence;
    ballArea.appendChild(myElement);//ball area is where I want to list the divs
    myElement.style.width = "550px";
    myElement.innerHTML= userName+" has bought a ball!";

    createEventListner();
}


function createEventListner() {
    var iBall = document.getElementById("individualBall"+ballRefrence);
    iball.addEventListener("click",showBall,false);
}


function playCaption() {
    //I am not sure how to pull the individual up here. 
    //Since I am using the "BallRefrence"variable
    //it will always be the last person clicked..
    //(Basically I cannot say 
    //alert.(ballRefrence);
}

I guess what I am trying to say is this, I have my "BallRefrence" that goes up by 1 each time. I store all the items in an array. (so first person will go to index 0, second will go to index 1...ect) I am having problems refrencing the element, because I am not sure how to pull the corrisponding numbe from the div.

Example: After 3 clicks of "create ball" my html will look something like this.

    <div id = "individualBall0></div>
    <div id = "individualBall1></div>
    <div id = "individualBall2></div>

Since each individual div will match up to the element in the array I want, How will tell my program "When you click individualBall0, I want ball[0].." or "when you click indivdualBall2, I want ball[2]"

I hope this makes more sense.

JumpJump
  • 115
  • 6
  • And, what exactly is your question? `createBall()` looks like it should insert a new `div` and then `createEventListner()` should hook up an event handler for the newly created element (though there are much cleaner ways to write the code). – jfriend00 Feb 10 '14 at 01:46
  • @Bergi - that was my thought when reading the title, but the OP's code is creating a new element and then assigning an event listener to it so I don't think this is an issue that needs delegated event handling (though it could be used here). – jfriend00 Feb 10 '14 at 01:49
  • @Bergi: Definitely agree on the closure suggestion, but I'm not sure if the question is clear enough to know if the suggested duplicate (or close vote) is relevant. – Scott Sauyet Feb 10 '14 at 01:50
  • @jfriend00: Beat me to the edit by two seconds! :-) – Scott Sauyet Feb 10 '14 at 01:52
  • Yeah, probably the title is misleading. @Daniel: Try to make a create-listener function that takes arguments, like `makeEventListener(myElement, userName)` - don't try to rely on a global variable. – Bergi Feb 10 '14 at 01:53
  • Or use `this` in the event handler to refer to the element that triggered the event. – jfriend00 Feb 10 '14 at 01:54
  • Or put a single listener on the *ballArea* element that handles clicks based on the event target. – RobG Feb 10 '14 at 02:03
  • Voting to reopen (my first time!) as neither the tags for this question nor the code provides mention jQuery. The supplied duplicate only mentions jQuery solutions. – Scott Sauyet Feb 10 '14 at 13:09

1 Answers1

0

One solution that doesn't really follow your updated requirements (but I believe does something simpler) is on JSFiddle. This stores the username and ball type in a local closure related to the event listener for that DIV. The code is fairly simple, and it removes some clutter from the global namespace, revealing only createBall:

var createBall = (function() {
    var ballReference = -1;
    var ballArea = document.getElementById('ballArea');
    var showBall = function(userName, ballType) {
        return function(event) {
            alert(userName + ' has a ' + ballType);    
        };
    };
    return function() {
        ++ballReference;
        var userName = document.getElementById('name').value;
        var ballType = document.getElementById('ball').value;
        var myElement = document.createElement('div');
        myElement.id = 'individualBall'+ballReference;
        ballArea.appendChild(myElement);
        myElement.innerHTML= userName+" has bought a ball!";
        myElement.addEventListener("click",showBall(userName, ballType),false);
    };
}());

To perform your updated requirements, it should be pretty easy. Your event handler will run in the context of your element, so something like this:

this.id.substring('individualBall'.length) //=> '0', '1', etc

should return a string representing the index of the div. You can use that directly for indexing various arrays, or, if that makes you squeamish, turn it into an integer with parseInt, the Number constructor, or the unary + operator.


But note that the suggestions from Bergi, jfriend00, and RobG are all good. There are many good ways of going about this.

Scott Sauyet
  • 37,179
  • 4
  • 36
  • 82