Jump to content

adding a string rather than replacing a string


brooke_theperson

Recommended Posts

Hey, so I have a code where you click a button, it tells you to translate a word, then tells you if you are correct or incorrect. I am adding something so that when you get a word correct, it goes on the left side, when you get a word wrong, it goes on the left side. My code works, aside from one thing. When you get a word right, it lists it on the left side, but the next word replaces the previous word. Here is one of my functions:

 

 

function spanishLocation(){    var num = Math.floor(Math.random() * locations.length);    var locations_obj = locations[num];    var answer = prompt("Translate: " + locations_obj.spanish).toLowerCase();    if (answer == locations_obj.english){         document.getElementById("icorrect").innerHTML = "Correct";     document.getElementById("AddCorrect").innerHTML = locations_obj.spanish + ": " + locations_obj.english;         document.getElementById("CorrectAnswer").innerHTML = "";    }    else{        document.getElementById("icorrect").innerHTML = "Incorrect";        document.getElementById("CorrectAnswer").innerHTML = locations_obj.english;    }    }

How do I change the

document.getElementById("AddCorrect").innerHTML = locations_obj.spanish + ": " + locations_obj.english;
so that it adds the word and its translation to a div, rather than replacing it? Does that make sense?
Link to comment
Share on other sites

Actually, I just realized, I just have to use

+=
. But I still have a question, how do I make it so that if there isn't enough room on the same line, when a string is added it goes to the next line down in the div. How do I do that?
Link to comment
Share on other sites

The browser will take care of wrapping text for you, assuming the CSS rules aren't disabling that stuff. You can always add a break after each word if you want everything on its own line. It's not a very easy thing to figure out the actual dimensions that text will use or whether it will fit inside a given element, HTML and CSS just weren't designed with that in mind. You would need to do something like creating a hidden element with the same CSS font styling, put the text in it, then get the size of the element, then figure out the width of the existing text in the visible element, and use things like padding to figure out how much space is left.

Link to comment
Share on other sites

You can use CSS to give the element a specific height, and then set the overflow property to "auto". That will cause a scrollbar to show up if necessary.Since you're using innerHTML, you can just add a "<br>" after the text you add.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...