Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

event listener fires only once

I’m learning Switch in JS. I created an array of names and I made a click event to pick a random name but it works only once. Another clicks repeats the same choice again and again. The random() function doesn’t seem to work. How to do it in vanilla JS in a simple way? Can anyone explain it to a learner using only basic methods?

   <button id="chooseRandom" onclick="checkPerson()">Choose</button>
  const people = ["Harriet", "Steve", "Ana", "Jessica", "Jacob", "Don"];
let randomPerson = people[Math.floor(Math.random() * people.length)];


let btn = document.querySelector("#chooseRandom")

function checkPerson () {
    switch(randomPerson) {
        case randomPerson = "Ana":
            console.log("Hi, Ana.");
            break;
        case randomPerson = "Jessica":
            console.log("Hi, Jessica.");
            break;
        case randomPerson = "Harriet":
            console.log("Hi, Harriet.");
            break;
        default:
            console.log("I'm not interested in men.");
    } 
  } 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need a new random people every time the checkPerson is called. So, you need calculate it inside of the function.

const people = ["Harriet", "Steve", "Ana", "Jessica", "Jacob", "Don"];

let btn = document.querySelector("#chooseRandom")

function checkPerson () {
    const randomPerson = people[Math.floor(Math.random() * people.length)];

    switch(randomPerson) {
        case randomPerson = "Ana":
            console.log("Hi, Ana.");
            break;
        case randomPerson = "Jessica":
            console.log("Hi, Jessica.");
            break;
        case randomPerson = "Harriet":
            console.log("Hi, Harriet.");
            break;
        default:
            console.log("I'm not interested in men.");
    } 
  } 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading