New text line in JavaScript with localStorage

Viewed 61

I want to create some text output from a JS string, but have it on two lines.

My JavaScript:

    function checkMessage(element) {
        var aTag= element.parentElement.previousElementSibling.firstChild;
        if (element.src == "x.jpg") 
        {
            element.src = "y.jpg";
            var aText = 'First \n Second';
            //aText = aText.replace("<br />", ' ');
            aTag.innerHTML = aText;
            localStorage.setItem(aTag.id, aText);
        }

My problem is that for some reason \n isn't working (I read this was JS's alternate to <br />), it only seems to add a space. I have tried instead using 'First <br /> Second' and although this works on the image click, upon the page refreshing, it writes out on one line literally "First <br /> Second". I also tried replacing the <br /> after the click, but it just does as anticipated... removes the line seperation anyway. Is my issue because of the way localStorage is working?

Additional code info:

$(document).ready(function() {
    aElements = $('body').find('p').each(function(index, element) {
        storageItem = localStorage.getItem(element.id);
        if (storageItem) {
           $('#' + element.id).text(storageItem);
        }
    });
});

PHP:

foreach ($things as $key => $thing) {
    echo "<div class='grid-container'>";
        echo "<div class='item4'><p id='a$i'>Message</p></div>";
        echo "<div class='item5'><img src='x.jpg' onclick='checkMessage(this)'  /></div>";
    echo "</div>";
    $i ++;
}

How do I go about splitting my text into two lines and it staying that way upon refresh?

1 Answers

You're close. You have the args the wrong way round in replace()

var aText = 'First \n Second';
aText = aText.replace(" \n ", "<br />");

First arg is what you want to match and the second is what you want to replace it with.

Also try using .html() instead of .text() to insert the text. That will parse any HTML in your string, where .text() just inserts the literal value.

$('#' + element.id).html(storageItem);
Related