The Gaming Hideout
The Gaming Hideout

Reputation: 584

JavaScript Change img src automatically

Problem

I am almost complete with my project, but I have yet another problem which I can't figure out. I need to have the image src change automatically when a prompt box closes. Here is what I mean.

Example

Lets say I have this code.

HTML

<button id="begin" onClick="javascript:fight();">Begin</button>
<img id="scenario" src="http://www.thegaminghideout.com/school/stage1.png">

JAVASCRIPT

function fight()  {
  var img = document.getElementById("scenario");
  var start = document.getElementById("begin");
  img.src = "http://www.thegaminghideout.com/school/map.jpg"; /* This changes it when the function is called */
  var decision1 = function()  {
    var decision = prompt("What do you do now? ATTACK, SLEEP, or PASS?").toUpperCase();
    if(decision === "ATTACK")  {
      attack();
    }
    if(decision === "SLEEP")  {
      sleep();
    }
    if(decision === "PASS")  {
      skip();
    }
  }

Question

How can I change the src of an img automatically when a (the) prompt dialog box closes? Or, check whether it's open or not?

What I tried

Things to Note

function fight() {
  var img = document.getElementById("scenario");
  var start = document.getElementById("begin");
  img.src = "http://www.thegaminghideout.com/school/map.jpg"; /* This changes it when the function is called */
  decision1();
  var decision1 = function() {
    var decision = prompt("What do you do now? ATTACK, SLEEP, or PASS?").toUpperCase();
    if (decision === "ATTACK") {
      attack();
    }
    if (decision === "SLEEP") {
      sleep();
    }
    if (decision === "PASS") {
      skip();
    }
  }
}
<img id="scenario" src="http://www.thegaminghideout.com/school/stage1.png">
<button id="begin" onClick="javascript:fight();">Test</button>

http://jsfiddle.net/d8sxxykj/

Upvotes: 2

Views: 1325

Answers (2)

Pipo
Pipo

Reputation: 193

Try,

$("#scenario").attr("src", "http://www.thegaminghideout.com/school/stage1.png");

instead of

img.src = "http://www.thegaminghideout.com/school/stage1.png";

Hope it helps!

Upvotes: 0

void
void

Reputation: 36703

function fight()  {

  var start = document.getElementById("begin");
  var decision1 = function()  {
    var img = document.getElementById("scenario");
    var decision = prompt("What do you do now? ATTACK, SLEEP, or PASS?").toUpperCase();
    if(decision === "ATTACK")  {
    img.src = "http://www.thegaminghideout.com/school/map.jpg";
    attack();
    }
    if(decision === "SLEEP")  {
    img.src = "something.jpg";
    sleep();
    }
    if(decision === "PASS")  {
    img.src = "something.jpg";
    skip();
    }
}  

Upvotes: 3

Related Questions