dimanche 10 décembre 2017

How to display/hide text depending on random number using if statement in javascript(no jquery)

I'm trying to display some complex text next to a picture when a button is clicked. So far I made the picture appear randomly when the button us clicked.

I cannot make the text work(it's basically a list) in the function, so I want to add the text in HTML and make it display/hide depending on the random number.

The picture and the text must correspond.

I also tried to make the text and picture(that are declared in HTML) display/hide depending on a number only with a function. But it didn't work for me.

That's the HTML i have:

<!DOCTYPE html>
<html lang = "en-US">
     <head>
        <meta charset = "utf-8">
        <title>Project</title>
        <link rel="stylesheet" type="text/css" href="index.css">
     </head>
     <body>
        <script src= "javaindex.js"></script>
          <button onclick="myFunc()" id="select" class="choosebtn">Select</button>
        </div>
        <div class="main">
          <img src="blank.jpg" name="picture">
           <div id="text">
            <p id="list1" >
            <h1> headingN</h1>
               <ul>
                  <li>elementN1</li>
                  <li>elementN2</li>
                  <li> elementN3</li>
              </ul>
           </p>
           <p id="list2" >
            <h1> heading</h1>
               <ul>
                  <li>element1</li>
                  <li>element2</li>
                  <li> element3</li>
              </ul>
           </p>
         </div>
        </div>
        <footer>Footer</footer>
     </body>
</html>

The js.file is:

function myFunc() {

                imgArray = new Array()
                imgArray[0] = "image1.jpg"
                imgArray[1] = "image2.jpg"
                imgArray[2] = "image3.jpg"
                imgArray[3] = "image4.jpg"

                document.getElementById("select").onclick = myFunc;
                randomN = Math.floor(Math.random()*4);

                 document.picture.src = imgArray[randomN];

                if ( randomN == 0 ){
                document.getElementById("list1").style.display = "block";
                }
               else if ( randomN == 1){
                document.getElementById("list2").style.display = "block";
               }
               else{
               document.getElementById("text").style.display = "none";
               }
}               




Aucun commentaire:

Enregistrer un commentaire