lundi 21 juin 2021

How can I run a random function when a button is clicked?

I have a popup window when clicked should display a random person's info out of 40 possible outcome. I tried using the switch statement:

$("#ball").click(function){

var n = Math.floor(Math.random()*2);

switch(n) {
    case 0:
    function(){
        document.getElementById("popupAvatar").innerHTML = "<img src='images/catalog/22Josephine.png' alt='' />";
        document.getElementById("popupInfo").innerHTML = '<h1>Josephine</h1><h2>"Decisions cultivate experience."</h2><a href="#">Go To Profile</a>';
    }
    break;

    case 1:
    function(){
        document.getElementById("popupAvatar").innerHTML = "<img src='images/catalog/22Josephine.png' alt='' />";
        document.getElementById("popupInfo").innerHTML = '<h1>TWO</h1><h2>"Decisions cultivate experience."</h2><a href="#">Go To Profile</a>';
    }
    break;

    case 2:
    function(){
        document.getElementById("popupAvatar").innerHTML = "<img src='images/catalog/22Josephine.png' alt='' />";
        document.getElementById("popupInfo").innerHTML = '<h1>Josephine</h1><h2>"Decisions cultivate experience."</h2><a href="#">Go To Profile</a>';
    }
    break;

But it doesn't seem to work.

I tried jQuery, with different functions assigned to different variables, but not sure how to call a random one when the button is clicked.

    var gacha1 = function(){
        $(".gachaPopup .avatar").html("<img src='images/catalog/22Josephine.png' alt='' />");
        $(".artistinfo .boxed").html('<h1>Josephine</h1><h2>"Decisions cultivate experience."</h2><a href="#">Go To Profile</a>');
    }

var gacha2 = function(){
        $(".gachaPopup .avatar").html("<img src='images/catalog/21Emily.png' alt='' />");
        $(".artistinfo .boxed").html('<h1>Emily</h1><h2>"Decisions cultivate experience."</h2><a href="#">Go To Profile</a>');
    }

var gacha3 = function(){
        $(".gachaPopup .avatar").html("<img src='images/catalog/20Erica.png' alt='' />");
        $(".artistinfo .boxed").html('<h1>Erica</h1><h2>"Decisions cultivate experience."</h2><a href="#">Go To Profile</a>');
    }

$("#ball").click(gacha2);

Any help appreciated, thank you so much.




Aucun commentaire:

Enregistrer un commentaire