CSRenA
CSRenA

Reputation: 147

How do I make a JavaScript created list item clickable?

I've been going through all the related questions but none of the solutions have been working for me. I am extremely new to JavaScript and I'm confused as to how to make a list that I created with JavaScript have clickable items. The most recent attempt included attempting to make an alert pop up on click but instead it just pops up the second the page loads. Please help! Here is my current code:

<!DOCTYPE html>
<html>
<head>
 <link rel="stylesheet" href="css/m-buttons.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
div.links{
margin: auto;
 border: 3px solid #003366;
text-align: left;
max-width: 700px;
}
p{
font-size: 40px;
text-align: center;
}
li{
font-size: 1w;
}
body{
font-family: verdana;
}
</style>
</head>
<body>
<div class = "links">
<ul id="blah"></ul>
<script>
var testArray = ["One","Two","Three","Four","Five","Six","Seven"];
function makeLongArray(array){
for(var i = 0; i < 1000; i++){
array.push(i);
}
}
makeLongArray(testArray);
function makeUL(array) {
    // Create the list element:
    var list = document.createElement("UL");
    list.setAttribute("id", "blah");

    for(var i = 0; i < array.length; i++) {
        // Create the list item:
        var item = document.createElement("LI");

        // Set its contents:
        item.appendChild(document.createTextNode(array[i]));

        // Add it to the list:
        list.appendChild(item);
        list.onclick = alert("Help."); //this is the code causing the issue.
    }

    // Finally, return the constructed list:
    return list;
}

// Add the contents of options[0] to #foo:
document.getElementById("blah").appendChild(makeUL(testArray));
</script>
</div>
</body>
</html>

Upvotes: 0

Views: 1760

Answers (3)

Yuriy Krivenko
Yuriy Krivenko

Reputation: 1

Here is my solution:

function toggleDone(event) {
  var ev = event.target;
  ev.classList.toggle("done");
}

ul.addEventListener("click", toggleDone);

Upvotes: 0

Phil
Phil

Reputation: 3736

Your existing code will execute alert('Help.') every time you execute this line of code list.onclick = alert("Help.");

What you need to do is assign a function to onclick. This function then get executed when onclick is executed. As follows:

item.onclick = function() {console.log('hello world');};

Now each list item's onclick event has a function assigned to it that outputs hello world to the console everytime the list item is clicked.

Upvotes: 2

kinggs
kinggs

Reputation: 1168

You need to assign a function to the onclick event:

list.onclick = function(){ alert("Help."); }

Upvotes: 1

Related Questions