Breaking a string into multiple lines inside a javascript code - javascript

I am trying to format (beautify, tidy, clear up.. you name it) a snippet of HTML inside my javascript code or, in other words, spread it out on multiple lines rather than having it written on one line so it can be read easily.
Basically, it's a piece of html code that I am trying to append to the page by calling the jQuery's .append(); method.
And here's what I am trying to do:
$('.videos').append('<li>
<span>' + count + '</span> -
<a href="' + vList[i].player + '">
<span class="title">' + videoTitle + '</span>
</a>
</li>');
Appearantly, it won't work that way. I am getting Uncaught SyntaxError: Unexpected token >
When It is written as follows, everything works fine.
$('.videos').append('<li><span>' + count + '</span> - <span class="title">' + videoTitle + '</span></li>');
It's kind of weird that when I tried to do the exact thing here,
var albumURL = API + '/video.get?=owner_id=' + userID +
'&album_id=' + aList[i].album_id +
'&access_token=' + accessToken;
I had no problem at all.
I know this issue is not that big of a deal but I am trying to get around with it just for the sake of simplicity.
Any suggestions?

If you have a multiline string, you need to use the multiline string syntax.
However, it's better to store your HTML in templates and not code :) That makes them more readable, more reusable and more maintainable.
What about something like - in your HTML:
<script type="text/template" id="videoTemplate">
<li>
<span>{{count}}</span>
<a href="{{videoURL}}">
<span class="title">{{videoTitle}}</span>
</a>
</li>
</script>
Then in JavaScript
var template = $("#videoTemplate").html();
$(".videos").append(template.replace("{{count}}",count).
replace("{{videoURL}}",vList[i].player).
replace("{{videoTitle}}",videoTitle));
That way, you get a clearer separation of the template you're using and your code. You can change the HTML independently and reuse it in other parts of code more easily.
The code does not have to even be aware of template changes and a designer can change the design without knowing JavaScript.
Of course, if you find yourself doing this often you can use a templating engine and not having a .replace chain.
ES2015 also introduces template strings which are also kind of nice and serve the same purpose in principle:
const videoTemplate = `<li>
<span>${count}</span>
<a href="${vList[i].player}">
<span class="title">${videoTitle}</span>
</a>
</li>`;

If you want to write a multiline string you should use the "\":
example:
$('.videos').append('<li> \
<span>' + count + '</span> - \
<a href="' + vList[i].player + '"> \
<span class="title">' + videoTitle + '</span> \
</a> \
</li>');

New answer:
With ES6 you can actually use string concatenation that is line-break insensible:
var html = `
<li>
${count}
</li>
`;
and the line breaks will not be a problem. Prior to ES6 I used mostly arrays and concat them. Its faster:
var html = [
'<li>',
count
'</li>'
].join('');
Old answer:
In javascript you cannot break lines without concatenating them with a + or using \. Try this:
$('.videos').append('<li>' +
'<span>' + count + '</span> - ' +
'<a href="' + vList[i].player + '">' +
'<span class="title">' + videoTitle + '</span>' +
'</a>' +
'</li>');

If you simply want to split rendered output onto new lines then append \n where you want the newline to appear, like this...
$('.videos').append('<li>\n<span>' + count + '</span> -\n\n<span class="title">' + videoTitle + '</span>\n\n</li>\n');
And if you want your JS to look nice you could try this, which will also ensure that your rendered HTML is indented.
var item = '';
item += '<li>\n';
item += ' <span>' + count + '</span> -\n';
item += ' <a href="' + vList[i].player + '">\n';
item += ' <span class="title">' + videoTitle + '</span>\n';
item += ' </a>\n';
item += '</li>\n';
$('.videos').append(item);

you can try like this
$('.videos').append( ['<li>',
'<span>' + count + '</span> - ' ,
'<a href="' + vList[i].player + '">' ,
'<span class="title">' + videoTitle + '</span>' ,
'</a>' ,
'</li>'].join('') );

From New Perspectives on HTML5, CSS, and JavaScript 6th Edition, Chapter 9 Getting Started with JavaScript:
"If you want to break a text string into several lines, you can indicate that the text string continues on the next line by using the following backslash \ character.
Example of proper line break:
      window.alert("Welcome \
      to Tulsa");

If you are rendering HTML using backticks and want to pass a variable inside it's very easy just add the backticks around the variable and concatenate it. let's take an eye on the below example
var x = 1;
$(wrapper).append(`
<div class="card">
<div class="card-body">
<h5 class="card-title">Plot `+ x +` </h5>
</div>
</div>
`);

Related

js: can I assign a class or an id to an html-element that's part of a variable definition?

NOTE: My knowledge of programming is scant.
I've got this line of code somewhere:
var item = "<h3>" + '' + postTitle + " </h3> <p>" + postContent + "</p>";
postUrl , postTitle and PostContent have previously been declared.
I'd like to wrap it all up inside a <div> tag that has some class or id assigned to it, as in...
var item = "<div id="special"> <h3>" + '' + postTitle + " </h3> <p>" + postContent + "</p> </div>";
But that doesn't seem to work.
Is it because of the quotations getting messed up or is it the wrong way to go altogether?
You have two options:
Escaping the " quotes inside your string literal, like this: "<div id=\"special\"> <h3>"
Or using single quotes ' for either the outer string or inner one (you have the choice), like this: '<div id="special"> <h3>' or "<div id='special'> <h3>"
I personally prefer '<div id="special"> <h3>' because the generated HTML will contain the " quotes (which is the HTML standard) while keeping the JavaScript more readable and maintainable (compared to using escaped quotes)

Can't pass js value "pageUid" in f:link.page viewhelper

I get some values from js and formatting page. I used fluid viewhelper for create link. My js look like
function buildEstablishments(title, page) {
...
$('#myid').append(
'<div class="col-md-6 col-sm-6 col-xs-6">' +
'<f:link.page pageUid="' + page + '" title="' + title + '" >More</f:link.page>' +
'</div>'
);
}
Everything works good, but I can't pass value "pageUid" in f:link.page viewhelper. Parametr ' + page + ' is exists and has a value. How can even pass values? Thanks.
You can not, in simple words all Fluid syntax works on server side and JS works on client side, that means that server side job is done long, long before it goes to the client (if you're using caching it may be months or years before client side will load it), you can use it rather like this:
In your Fluid view:
<div onclick="buildEstablishments('{someTitle}', '{f:uri.page(pageUid: somePageUid)}')">Foo Bar Baz</div>
Where of course {someTitle} and {somePageUid} are resolvable Fluid variables
so you can use it in your JS script like:
function buildEstablishments(title, href) {
// ...
$('#myid').append(
'<div class="col-md-6 col-sm-6 col-xs-6">' +
'<a href="' + href + '" title="' + title + '" >More</a>' +
'</div>'
);
}

Building string with javascript

I have the following Problem:
I'm trying to build a simple string like that:
for(var x in classicde) {
specificWines += "<li><a onClick='displayWine(" + "'GV'" + ")'>" + classicde[x] + "</a></li>";
}
Then I insert this string in the DOM structure with:
var list = document.getElementById("leftmenu-list");
list.innerHTML = specificWines;
The result is the following(something like that i have shortened it):
<ul id="leftmenu-list">
<li><a onclick="displayWine(" gv')'>Classic1</a></li>
</ul>
So there is a problem within the onclick event and i am not able to find the issue.
Your quotes are wrong around 'displayWine(" + "'GV'" + ")' it should be 'displayWine(" + "\"GV\"" + ")' so the single quotes contains double quotes and do not break the attribute on render. \ is used to escape the quote so it doesn't break the JS code.
for(var x in classicde) {
specificWines += "<li><a onClick='displayWine(" + "\"GV\"" + ")'>" + classicde[x] + "</a></li>";
}
Otherwise as you see you end up with the single quote breaking the attribute. If you pass a string inside a string you need to make sure you use different quotes.
This should now render as
<li><a onclick='displayWine("gv")'>Classic1</a></li>

jQuery append trouble with url parameter

I've been working for hours trying to get the single and double quotes nested correctly in order for this search result display to work, with having a dynamically appended "uniqueId" in part of the URL string on output.
Basically, the part of the JS code that is giving me trouble is this:
$('#results-list').append("<li rel='" + this.uniqueId + "'>" + this.dateTimeStamp + " — " + this.message + " — " + "<a class='iframeSmaller' href='commentDetails.php?uniqueId='" + this.uniqueId + "''>XXX</a>" + "</li>");
I want to have the "this.uniqueId" after the equal sign so that it generates a dynamic URL, which I then am going to link to a "details" page for that unique ID.
Can anyone please help me with the "this.uniqueId" syntax to get this correctly inserted into the URL for output?
Sorry if I am being unclear, I am learning all of this by the day :)
thanks!
ps... this does work, but it has a hardcoded uniqueID... what I want is a dynamic one based on the row, which is working as far as the "rel" part goes, just not the anchor part...
$('#results-list').append("<li rel='" + this.uniqueId + "'>" + this.dateTimeStamp + " — " + this.message + " — " + "<a class='iframeSmaller' href='commentDetails.php?uniqueId=32'>XXX</a>" + "</li>");
thanks again for any help with this syntax (or if there's a better way to go about what I'm trying to do)...
The quoting in your HTML for the anchor isn't quite right. You have this:
+ "<a class='iframeSmaller' href='commentDetails.php?uniqueId='" + this.uniqueId + "''>XXX</a>" +
I think it should be this (fix quoting on the link URL):
+ "<a class='iframeSmaller' href='commentDetails.php?uniqueId=" + this.uniqueId + "'>XXX</a>" +
You could see what's going on better if you build the string into a variable and then do a console.log() on the string of HTML you've built or look at its contents in the debugger.
Replace this part of your code:
... uniqueId='" + this.uniqueId + "''>XXX</a>" + "</li>");
for this one:
... uniqueId=" + this.uniqueId + "'>XXX</a>" + "</li>");

Blinking page title

I'm trying to get some notifications working for AJAXChat. To do this all I want to do is get the title of the page to blink until focused. To do this I'm using the jquery-titlealert plugin. The problem is the html that is generated for the onload event is generated inside a js file shown here
return '<div id="'
+ this.getMessageDocumentID(messageID)
+ '" class="'
+ rowClass
+ '">'
+ this.getDeletionLink(messageID, userID, userRole, channelID)
+ dateTime
+ '<span class="'
+ userClass
+ '"'
+ this.getChatListUserNameTitle(userID, userName, userRole, ip)
+ ' dir="'
+ this.baseDirection
+ '" onload="$.titleAlert('New Message');">'
+ userName
+ '</span>'
+ colon
+ this.replaceText(messageText)
+ '</div>';
return
When I use this, it breaks the page. If I replace ('New Message') with (New Message) the page loads again but the notification isn't working. I think this is because its displaying a Javascript function inside Javascript. Anyone see anything here I'm missing?
Have you tried escaping your quotes? I.e.:
+ '" onload="$.titleAlert(\'New Message\');">'
Any single quote (') inside a single quoted string (or double quote (") inside a double quoted string) needs a backslash (\) before it. See the MDN String Literals documentation for more information about strings and proper character escaping.
You need to escape the quotes.
Change this
'" onload="$.titleAlert('New Message');">'
to this
'" onload="$.titleAlert(\'New Message\');">'
Try escaping the apostraphe's correctly:
+ '" onload="$.titleAlert(\'New Message\');">'

Categories

Resources