PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 26, 2022

[FIXED] How to get dialogue to change upon clicking on an image?

 July 26, 2022     counter, dreamweaver, javascript, onclick, var     No comments   

Issue

I'm trying to create a game with dialogue, and I want my text to change as the player clicks on a next image to progress the story.

For example:

Page loads - "Hi, I'm Joe."

Clicks sliced Image once - "Nice to meet you."

Clicks 2nd time - "How are you?"

I have tried onClick but that only allows me to change it once, I've tried using var counter as well but to no avail, it overrides my previous commands, which part of this am I doing wrong here?

var clicks = 0;

function changeText() {
  {
    clicks = 1;
    document.getElementById('text').innerHTML = "Ughh... my head... What     
    happened...?";
  }
}

function changeText() {
  {
    clicks = 2;
    document.getElementById('text').innerHTML = "Testing 1 2 3";
  }
}

function play() {
  var audio = document.getElementById("audio");
  audio.play();
}
<img onClick="changeText(); audio.play()" value=Change Text src="images/awaken/images/awaken_03.jpg" alt="" width="164" height="77" id="clicks" />
<p id="text">Where... am I...?</p>


Solution

First off all - your changeText() system is flawed - you're overwriting the same function multiple times at the same time, so the only one of those that will ever get called is the last one you declare. JavaScript doesn't wait until a function gets called to continue with the program.
The audio.play() also won't work - but I'm assuming that's a work in progress. I changed your code so that instead of setting count to a specific value, it increments every time the function gets called, and it updates the text to the correct value in an array. Here's the updated changeText function:

var count = 0;
var text = [
"Where... am I...?", /* note that this will never get called, it's simply here for filling up the array*/
"This is the first text!",
"And this is the second!"
]
var changeText = function() {
   count++;
   document.getElementById('text').innerHTML = text[count];
}

In the future, you'll probably also want to check if(text[count] != 'undefined'), and if so write something like "Bye!" instead.



Answered By - Arthur F.
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing