Why isn't the text appearing?

Viewed 85

I'm attempting to make a "MEME Generator" but I got stuck at this point due to the fact that when i:

upload > Enter Text > Submit

All of the JS changes restore to the default state. I'm probably just missing something so if you could assist me i would help greatly

function topContent() {
  var topText = document.getElementById("userTopText").value;
  document.getElementById("topText").innerHTML = topText;
}

function changeImg() {

  document.getElementById("frame").style.background = "url(assets/Background.jpg    )";
}
body {
  margin: 0;
  padding: 0;
  font-family: Arial, sans-serif;
}

#frame {
  width: 20%;
  height: 60%;
  color: white;
  background-size: 20% 60%;
  background-repeat: no-repeat;
}

#frame h1 {
  text-align: center;
}
<div id="frame" width="20%" height="60%">
  <h1 id="topText"></h1>
</div>

<button onClick="changeImg()">Upload</button>

<form>
  <input type="text" id="userTopText">
  <button type="submit" onClick="topContent()">Enter</button>
</form>

4 Answers

The issue is to do with the default action of a <form> submit is to reload the page thus removing your image. In your case I'd use the JQuery library and prevent the form from doing that default action.

Refer to this Stack Overflow answer: Stop form refreshing page on submit

Your problem is you've got this code:

#frame {
    color: white;
}

This is turning the text white. Changing this will solve your problem.

Figured it out!!

The:

<button type="submit" onClick="topContent()">Enter</button>

For some reason the type="submit" was refreshing the page

Change style of frame so text isn't white:

#frame {
    width: 20%;
    height: 60%;
    color: black;
    background-size: 20% 60%;
    background-repeat: no-repeat;
}

Change form so button returns.

<form>
    <input type="text" id="userTopText">
    <button onClick="return topContent()">Enter</button>
</form>

Make sure function returns false, this tells the form not to then submit.

function topContent() {
    var topText = document.getElementById("userTopText").value;
    document.getElementById("topText").innerHTML = topText;
    return false;
}
Related