Creating long strings of text
I can use the plus sign (+) to add text and variables together into one long piece of text. For example:
result = "Hello " + "world"
Will cause result
to equal Hello world
. You can use the same technique to combine text with variables, like this.
mytext = prompt("what is your favorite color", "")
result = "Your favorite color is " + mytext
//Define contents of page
contents =
'<body bgcolor="beige">' +
'<h2>Hello</h2>' +
'Click on the message below to close this window<br>' +
'<A HREF="javascript:window.close()" >' +
message +
'</A>'
The example above shows an entire HTML page defined into one variable, named contents
. There are 2 reasons why I put a plus sign at the end of each line, instead of simply writing one long line of text.
- The document is much easier to read and edit this way.
- There is a limit on how long a line of JavaScript can be.
I don't know exactly what the limit is, but I know that I get errors when I create very long lines in my script. The plus sign helps me break the definition of contents
into 7 small lines instead of 1 big one.
Notice the bottom 3 lines. They create a HREF
link around your text. message
is the contents of your sample text. If message="Hello"
then the last 3 lines would read
<A HREF="javascript:window.close()"> Hello </A>
function myLink(text) {
result = ' <
A HREF = "mypage.htm" > ' +
text +
' </A>'
}
As you can see, the <A HREF>
tag can be used to trigger javascript events instead of creating a link to another page. We will discuss this in more detail later.