Pushistic
Pushistic

Reputation: 11

java script: swapping technique, adding random text

In my code I have the image that swaps to another one image each time I click on it with the mouse. I have difficulties with adding a random text to the second (swapped) image. The text should not appear when i see the first image. Here is my code. There are some mistakes in java script when I was trying to write a code for the random text. Please, help me to correct.

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <link rel="stylesheet" href="css/styles.css">
  </head>
  <body>
    <h1></h1>
    <div id="cookie" class='whole'></div>
    </div> 
    <p id="demo"></p>
    <script src="js/cookies.js"></script>
  </body>
</html>

js code:

var lock = document.getElementById('cookie');
    var state = 'orange';

    function swapImage(){

            if (state === 'orange'){
            lock.className = 'cracked';
            state = 'blue';
        }else{
            lock.className = 'whole';
            state = 'orange';
        }
      }

lock.addEventListener('click', swapImage, false);

var r_text = new Array ();
r_text[0] = "All the leaves are brown";
r_text[1] = "And the sky is grey";
r_text[3] = "On a winter's day";
r_text[4] = "I'd be safe and warm";
r_text[6] = "California dreaming, On such a winter's day";
var i = Math.floor(7*Math.random())

function fortune() {

document.write(r_text[i]);

 }
var elText = document.getElementById('cookies');
elText.addEventListener('click', fortune, false); 

css:

  #cookie{
     width: 360px;
     height: 216px;
     margin: 100px auto; 
     margin-top: 10px;
   }

.whole {
    background: url("../images/whole.png");
}
.cracked {
    background: url("../images/cracked.png");
}

Upvotes: 1

Views: 65

Answers (1)

StackSlave
StackSlave

Reputation: 10627

You have to run var i = Math.floor(7*Math.random()) inside your fortune function, or i will be the same as it was before.

Upvotes: 1

Related Questions