suonpera suonpera - 12 days ago 7
CSS Question

line break in javascript

Is it possible to create a line break in the text = "something"? For example, I want the good morning greeting to be: Good Morning! (Line break) How are you today?.

I've tried with \n like so: text = "good morning!" + "\n" + "How are you today?".

Any suggestions?

Here's my code:



var myDate = new Date();
var text = "";

/* hour is before noon */
if (myDate.getHours() < 12) {
text = "Good Morning!";
}

/* Hour is from noon to 5pm (actually to 5:59 pm) */
else if (myDate.getHours() >= 12 && myDate.getHours() <= 17) {
text = "Good Afternoon!";
}

/* the hour is after 5pm, so it is between 6pm and midnight */
else if (myDate.getHours() > 17 && myDate.getHours() <= 24) {
text = "Good Evening!";
}

/* the hour is not between 0 and 24, so something is wrong */
else {
text = "Hallo!";
}

$("#rowheader h1").text(text);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rowheader">
This is where the magic happens
<h1></h1>

</div>




Answer

You can insert a single line break in the text variable and use .html() instead of .text() like this:

var myDate = new Date();
var text = "";

/* hour is before noon */
if (myDate.getHours() < 12) {
  text = "Good Morning! <br /> How are you today?";
}

/* Hour is from noon to 5pm (actually to 5:59 pm) */
else if (myDate.getHours() >= 12 && myDate.getHours() <= 17) {
  text = "Good Afternoon! <br /> How are you today?";
}

/* the hour is after 5pm, so it is between 6pm and midnight */
else if (myDate.getHours() > 17 && myDate.getHours() <= 24) {
  text = "Good Evening! <br /> How are you today?";
}

/* the hour is not between 0 and 24, so something is wrong */
else {
  text = "Hallo!";
}

$("#rowheader h1").html(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="rowheader">
    <h1></h1>
</div>