concatenate a variable to a html string in javaScript - javascript

Please be gentle with me, it is my first time uploading a question to stack overflow, and since I am rather new in programming I might be a bit vague in the terms.
My problem is that I have a function that places some markers on a map, this happens automatically when I load the site, these markers are different and contain different "trophies", that I have placed in a pop-up locked to the marker. However I want the program to be able to collect the trophies, therefore I would like to call a function with the specific trophy as my parameter in my javaScript file when I click a button in my pop up. HTML.
So far it looks like this:
function createMarker(coords, trophy) {
var id
// check if array is empty and set id to 0 if it is
if (markers.length < 1) id = 0
// else make id based on array length
else id = markers[markers.length - 1]._id + 1
// custom popup content with HTML that can be styled
var popupContent =
'<div id= "divTrophy">'+
'<img src=' + trophy +'></img>' +
'<button onClick="trophyCollection('+trophy+')">Collect trophy</button>'+
'<button onclick="closePopUp()">Close pop up</button>'+
'</div>'
'<button onClick="trophyCollection('+trophy+')">Collect trophy</button>'+
The problem is in this line where I am for some reason not allowed to concat this way, which confuses me because it works fine in the line above in the <img>.
I really hope someone can help me, create my little treasure hunt around DK.

Try using string interpolation. Something like this.
`your_html_string ${your_dynamic_value} your_html_string`
You can find more info on interpolation here.
How to interpolate variables in strings in JavaScript, without concatenation?

Try escaping them it should work, example
'<button onClick="trophyCollection(\''+trophy+'\')">Collect trophy</button>'+

You can insert your entire HTML inside of a backtick string and interpolate values like this:
let popupContent =
`<div id= "divTrophy">
<img src=${trophy}></img>
<button onClick="trophyCollection(${trophy})">Collect trophy</button>
<button onclick="closePopUp()">Close pop up</button>
</div>`

As suggested you can try template literals:
var popupContent = `<div id="divTrophy">
<img src="${trophy}"/>
<button onClick="trophyCollection('${trophy}')">Collect trophy</button>
<button onclick="closePopUp()">Close pop up</button>
</div>`
Do note that as trophy is a string you still need to wrap it in quotes.

Related

Adding Emoji List to HTML Element without lag

Is there a way to add an emoji list to an element without lag? I've seen this in many websites but don't know how they did it.
When I want to add an emoji to the list, I create a button with some style and onclick events, and then put the emoji in the button's innerHTML.
The code which needs to be repeated 2260 times:
document.getElementById('emojicard').innerHTML += '<button class="w3-button w3-center" style="width: 64px;"'
+'onclick="document.getElementById('+"'inputarea'"+').value += this.innerHTML;">' + emojis[emojiIndex]+'</button>';
emojiIndex++;
document.getElementById('emjprogbari').innerHTML = emojiIndex + ' out of ' + emojis.length;
document.getElementById('emjprogbar').style.width = (100*emojiIndex/emojis.length)+'%'
I usually have to do it in an updating function, but it creates lag. If I put it somewhere else, the website freezes for a while. (I have 2260 emojis in the list)
I don't want to add all of the emojis in that element manually, because, as I have said, there are 2260 emojis in my list and I will add more to that list. Please answer.
Keep appending html on the page will cost a big effort to the browser, the better way is appending html to the variable and print it out at the end.
Start by defining a variable:
var html = '';
Start your loop:
html += '<button class="w3-button w3-center" style="width: 64px;"'
+'onclick="document.getElementById('+"'inputarea'"+').value += this.innerHTML;">' + emojis[emojiIndex]+'</button>';
emojiIndex++;
document.getElementById('emjprogbari').innerHTML = emojiIndex + ' out of ' + emojis.length;
document.getElementById('emjprogbar').style.width = (100*emojiIndex/emojis.length)+'%'
Print out the html:
document.getElementById('emojicard').innerHTML = html;

Appending the javascript onclick event to anchor tag

Im trying to append the onclick event to my Phonegap Application. Where it will link to external browser.
My Code:
pair +='<div class="card_background" style="background-image: url("http://placehold.it/600x200");" valign="bottom" class="card-header color-white no-border"><div class="card_overlay"></div><div class="animated_background"></div><h3 class="card-title">'+ results.rows.item(i).title +'</h3></div><div class="card-content"><div class="card-content-inner"><p class="color-gray event_details">Event Location: <strong>'+ results.rows.item(i).eventlocation +'</strong></p><p class="color-gray event_details">Event Date: <strong>'+ date + " " + month + " " + year +'</strong></p>Google<br/></div></div>';
inside loop,
Later I append it to div
Im trying to add :
Google
It gives me error
Thanx in advance
I've simplified your code somewhat. Consider the following:
var pair = '';
var eventOrganiserLink = '[EVENT ORGANISER LINK]';
pair += 'Google';
This would generate the following:
Google
The onclick attribute opens with double quote ("), which means it will look for the first double quote after that to close it. That's right after window.open( meaning that part is the only thing that will be set as the onclick attribute. See how the colors in the onclick attribute in the code box here at StackOverflow don't really match up?
It is a little tricky because we're mixing quotes (setting the pair variable) and double quotes (as text inside that variable, which will be used as html later on - so it needs to be valid).
You can use single quotes for the first window.open parameter and escape them in the assignment to your pair variable, like so:
var pair = '';
var eventOrganiserLink = '[EVENT ORGANISER LINK]';
pair += 'Google';
This would yield:
Google
Note the single quotes around [EVENT ORGANISER LINK]. Also note the colors now match up.

How do I dynamically append a large block of HTML to a div?

I'm trying to learn web development, so I don't have much experience with the various languages and markups yet. I'm making a website with a blog that reads JSON data from the Tumblr v2 API. After getting the JSON data from Tumblr I want to add some of the data from each post to my own website's blog, here's the code that I've been trying to use..
<script>
function loadBlogPosts(){
$.getJSON("http://api.tumblr.com/v2/blog/[MY_BLOG]/info?api_key=[MY_KEY]",
function(blogData){
$.each(blogData.posts, function(){
$(#main_content).append( [BUNCH OF NESTED HTML] );
});
}
);
}
</script>
Before writing this, I thought it would be a good idea to make a 'layout' of each blog post in divs. So i came up with this:
<div class="post">
<div class="post_header">
<div class="post_title"></div>
<div class="post_author"></div>
<div class="post_date"></div>
</div>
<div class="post_content"></div>
<div class="post_footer"></div>
</div>
But that's where I'm stuck. I know what I want to do, but I don't have enough experience with JavaScript/JQuery/JSON/HTML to know how to do it. I want parse the JSON blog data and, for each post, take the post content and apply it to that div structure while writing/appending it to the "main_content" div.. I tried copy-pasting that group of divs into the append function surrounded by quotes, but it became a real mess of quotes and slashes, and it didn't look like it was working correctly..
So, whats the best way for me to do that? Is there a good way of applying a big chunk of nested HTML elements while populating them with content from my JSON data? If not, what should I do? I'm still very new to HTML, JavaScript, and web coding in general, so I may be going about this completely wrong!
If you want HIGH PERFORMANCE:
In pure javascript the highest performing method is probably using createDocumentFragment()
function postEl(json){ // create a function for the POST element
var post=document.createElement('div');
post.className='post';
var postHeader=document.createElement('div');
postHeader.className='post_header';
var postTitle=document.createElement('div');
postTitle.className='post_title';
postTitle.tectContent=json.title;
//more code
postHeader.appendChild(postTitle);
//more code
post.appendChild(postHeader);
return post;
}
function appendPosts(){ // append each post to a fragment. and then to the main
var frag=document.createDocumentFragment();
for(/*each post*/){
frag.appendChild(postEl(/*jsonPost*/));
}
document.getElementById('main_content').appendChild(frag);
}
Precreating the structure should also increase the performance.
cloneNode
https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode
https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment
cloning the node also increases the performance by setting the valuse directly without recreating each individual node.
function appendPosts(js){
var node=document.createElemtnt('div'),
frag=document.createDocumentFragment();
node.innerHTML='<div class="post_header"><div class="post_title"></div><div class="post_author"></div><div class="post_date"></div></div><div class="post_content"></div><div class="post_footer"></div>';
for(var a=0,b;b=js.posts[a];++a){
var newNode=node.cloneNode(true),
childs=newNode.childNodes,
header=childs[0].childNodes;
header[0].textContent=b.title/*title from Postdata*/;
header[1].textContent=b.author/*author from Postdata*/;
header[2].textContent=b.date/*date from Postdata*/;
childs[1].textContent=b.content/*content from Postdata*/;
childs[2].textContent=b.footer/*footer from Postdata*/;
frag.appendChild(newNode);
}
document.getElementById('main_content').appendChild(frag);
}
function loadBlogPosts(){
$.getJSON("http://api.tumblr.com/v2/blog/[MY_BLOG]/info?api_key=[MY_KEY]",
appendPosts
)
This function should work now .. but as i don't exactly know the json response you may need to change the various post keys.
note: i put the fragment thing in a function so you have an idea how it works.
you should put the postEl content inside the appendPosts function... (thats also faster)
if you have any questions just ask.
EDIT
no they are not globals
var a,b,c,d; // not globals == var a;var b;var c;var d;
var a,b;c;d; // c d = gobal
// , comma affter a var allows you to not write 1000 times var.
EDIT2
//.......
frag.appendChild(newNode);
}
var topNode=document.createElement('div');
topNode.className='post';
topNode.appendChild(frag);
document.getElementById('main_content').appendChild(topNode);
//.....
when you want to do everything with jquery yoiu could use something like this:
var post = $('<div class="post"></div>');
var postheader = $('<div class="post_header"></div>');
postheader.append('<div class="post_title"></div>');
postheader.append('<div class="post_author"></div>');
post.append(postheader);
post.append('<div class="post_content"></div>');
post.find('.post_title').text('my title');
post.find('.post_content').text('my content');
$('#main_content').append(post);
instead of .text('my title') you can use .text(variable) of course
Write your code in a separate page, then append a whole html page into a div by using:
$('#containerDiv').load('page.htm');
Also, this is a good way to fragment the content.
you could do something like this:
$.each(blogData.posts, function(i,v){
var cnt= '<div class="post">' +
'<div class="post_header">' +
'<div class="post_title">'+ blogData.posts[i].title +'</div>' +
'<div class="post_author">'+ blogData.posts[i].author +'</div>' +
'<div class="post_date">'+ blogData.posts[i].date +'</div>' +
'</div>' +
'<div class="post_content">' +
blogData.posts[i].body +
'</div>' +
'<div class="post_footer">' +
'</div>' +
'</div>';
$('#main_content').append(cnt);
});
Note that you don't need to split up all the lines, i've just done that to make it more readable. (I'm also not sure if all the variables are correct, (i don't think author exists) but it's just as a demo)

Setting the Input Value attribute to a variable with space.

I am trying to set the value of a input button to a string variable.i.e"A Guide to the School Bus"; But when the HTML loads up only the first word comes up in the button. My code is given below. Thanks for the help.
var title="A Guide to the School Bus";
var htmlString= "<div class="+title+ ">"+"<input type="+"button "+"value="+title+" onclick=loadBook()>"+"</div>";
$(htmlString).appendTo(attachPoint);
And the attachpoint is a reference in the HTML that i got using the following.
var attachpoint=document.querySelector('.buttonAttachPoint');
The problem is because you're not putting quotes around the attribute values. Try this:
var htmlString= '<div class="'+title+'"><input type="button" value="'+title+'" onclick="loadBook()"></div>';
You can either escape all the " in your string or, like I have done, just switch between ' and ". " will show up as a normal character and ' is used to mark the start and finish of strings.
As a side point you probably wouldn't want to put the variable title as the class on the div as it would add each separate word as a class, so in your example the div would have 6 classes added to it.

Insert HTML as a String, without JQuery

I'm looking for a method to insert a string, which contains HTML data, into a div element.
The string is loaded via XHR, and there is no way of knowing what elements and such are in it.
I've searched around for a bit, and found some things that might help, but wouldn't completely work for me. What I need is something similar to the update() function from the Prototype framework:
http://prototypejs.org/api/element/update
The platform I'm writing for does not allow frameworks to be used, or JQuery. I'm stuck with Javascript. Anyone have any ideas?
I can't use innerHTML, as it does not apply any updates or functions or basically anything that's supposed to occur on load
I have some onload events that need to occur, and as best I know, using innerHTML does not execute onload events. Am I incorrect?
EDIT 2 years later:
For anyone else reading, I had some serious misconceptions about the onload event. I expected that it was a valid event for any element, while it is only valid for the <body/> element. .innerHTML is the proper method to do what I was looking for, and any extra functionality for the elements added, needs to be done manually some other way.
HTMLElement innerHTML Property
The innerHTML property sets or returns the inner HTML of an element.
HTMLElementObject.innerHTML=text
Example: http://jsfiddle.net/xs4Yq/
You can do it in two ways:
var insertText = document.createTextNode(theText);
document.getElementById("#myid").appendChild(insertText);
or
object.innerHTML=text
I'm looking for a method to insert a string, which contains HTML data, into a div element.
What you want to use is the innerHTML property.
Example of use:
<script type="text/javascript">
function changeText(){
document.getElementById('boldStuff').innerHTML = '<p>Universe</p>';
}
</script>
<p>Hello <b id='boldStuff'>World</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
do you mean like this? : http://jsfiddle.net/FgwWk/1 or do you have things in the div already before adding more?
Plain JS.
Just use: element.insertAdjacentHTML(position, text);
position = "beforebegin" | "afterbegin" | "beforeend" | "afterend"
var text = '<a class="btn btn-blue btn-floating waves-effect">\n' +
'<i class="fas fa-user"><span class="badge badge-danger"></span></i>\n' +
'</a>';
var inputPlace = document.getElementById("input-pace");
inputPlace.insertAdjacentHTML("beforeend", text);

Categories

Resources