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;
Related
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.
I'm looking to randomize a image and color pair on my webpage upon refresh. For example, when you refresh, it will show "img A" and "#999;", and next it might show "img B" and "#fff;"; basically, one image is paired with exactly one color, and that color never goes with a different image.
The tricky part is that I need the color to randomize under the css/div "a:hover{", and the image to randomize under a different id (i named it #scanner, if it helps)
So far I have this, but it isn't working. I'm not very experienced with javascript so I'm totally stuck (even though i probably just missed something very simple).
<script>
var colors = [["#CCCCCC", "http://static.tumblr.com/ixbct68/1y1niuvxl/wwo.gif"], ["#7b9fb9", "http://static.tumblr.com/ixbct68/2bzniuwcf/nottarget.gif"], ["#3df756", "http://static.tumblr.com/ixbct68/eFxniuwqz/nonlethal.gif"]];
var r = Math.floor(Math.random() * 4);
document.getElementById("scanner").innerHTML = "<font color=\"" + pairs[r][0] + "\"<img src=\"" + pairs[r][1] + "\">"
text.css('color', colors[col][0]);
</script>
<div id="scanner">
<script>
document.getElementById("scanner").innerHTML = "<img src = \"" + colors[col][1] + "\">"
</script>
</div>
You only have three items in the array, but you are creating a random number between 0 and 3 (four different values), so sometimes it will try to get items outside the array. Create a random number between 0 and 2, or better yet just use the length of the array, so that it automatically adjusts to whatever you put in the array:
var r = Math.floor(Math.random() * colors.length);
After that you try to access an element that doesn't exist yet. As the element is further down in the page, the code for it hasn't been parsed yet when the script runs. You should put the code after the element, or in the load event of the page.
The code uses an array named pairs that doesn't exist, and the HTML code that it produces is wrong. There is a font element (which is deprecated by the way) that doesn't have a closing bracket (>) and no closing tag (</font>). Something like this is what you would use:
document.getElementById("scanner").innerHTML = '<span style="color:' + colors[r][0] + '"><img src="' + colors[r][1] + '"></span>';
Then there is some code that uses a variable text that doesn't exist.
Then you have the element that you want to change, and more script inside that element. Changing the element while it is still being parsed (i.e. before the closing tag) might have some unexepected or unpredictable behaviour, for example that the closing tag might produce another element, or work as a closing element for some other element.
The script in the element repeats some of the earlier script, but it doesn't use the color.
Let's put the code in correct order, and clean out what you don't need:
<div id="scanner"></div>
<script>
var colors = [
["#CCCCCC", "http://static.tumblr.com/ixbct68/1y1niuvxl/wwo.gif"],
["#7b9fb9", "http://static.tumblr.com/ixbct68/2bzniuwcf/nottarget.gif"],
["#3df756", "http://static.tumblr.com/ixbct68/eFxniuwqz/nonlethal.gif"]
];
var r = Math.floor(Math.random() * colors.length);
document.getElementById("scanner").innerHTML = '<span style="color:' + colors[r][0] + '"><img src="' + colors[r][1] + '"></span>';
</script>
Please forgive me and let me know if my post is not right since I am brand new to this forum.
I have found most of the answer here (Create a <ul> and fill it based on a passed array), but my problem comes with .createTextNode. My users are using multiple editor boxes to build an outline. Within these boxes they can format the text (underline, color, bold, etc.). So the array items that I am passing to .createTextNode actually have HTML tags in them to format the line items. However .createTextNode makes it just plain text which in turn just spits out the tag instead of applying it when displayed via document.getElementById('foo').appendChild...
I know that I should stay away from HTML concatenation but it is looking very tempting.
Is there any way to retain the formatting of the list items when appended and displayed?
Thank you in advance for your assistance.
Try innerHTML, which will try to parse the content string as HTML structure. For example you have a P tag
<p id="asdf"></p>
<script>
document.getElementById('asdf').innerHTML = 'qwerty';
</script>
Will give you a clickable anchor
<p id="asdf">
qwerty
</p>
But be careful!!! (Notice I use three bang sign here) You must be sure there's no harmful code before you insert it. Check this example:
document.getElementById('asdf').innerHTML = '<img src="image.png" onload="alert(1)">'
You will see an alert dialog. This example is simple though, in practice it can be much more dangerous, e.g. dynamically append a cross site script into you page, aka XSS.
EDIT: here is a demo.
var options = ['Option 1','Option 2'];
function makeUL(){
var LIs = '';
for (i = 0; i < options.length; i += 1){
LIs += '<li>' + options[i] + '</li>';
}
return '<ul>' + LIs + '</ul>';
}
document.getElementById('foo').innerHTML = makeUL();
<div id="foo"></div>
I've been having some troubles with this javascript code and I am looking for a suggestion. I am programtically adding a row to a table with javascript but I need to add an onclick event for each row. Problem is when the row adds to the page the quotations and upper / lower case has been all converted to lower case causing issues on the web page.
here is the current code
var row = $("<tr id=" + id + " onclick=return SelectRow('Racks','" + id + "') >");
if someone could explain how to get it so that the ending result looked like this
<tr id="r1" onclick="return SelectRow('Racks','r1')">
</tr>
I'm guessing it has to do with escape characters and the order they are being placed but I can't seem to figure it out.
Don't try to generate JavaScript inside HTML inside JavaScript. It is a right pain.
Don't write 90s style code. Stop using onclick attributes. Use event handlers bound with JavaScript.
function row_click_handler(event) {
return SelectRow("Racks", this.id);
}
var row = $("<tr />").attr("id", id).on("click", row_click_handler);
I have a Chrome extension in which I'm fetching tab title and url, and putting them into one single line. Same as Chrome History. I want to separate them visually, dark title, lighter url.
and for that I'm using this code
nodeTitle.innerHTML = tabs[j].title + "<span id='url'>" + ' - ' + tabs[j].url + "</span>" ;
CSS for #url is set and everything works fine, unless page title have some actual HTML code/tag in it, and title get messed (ofc. innerHTML works as it supposed to).
example page...look at title
innerText doesn't help in this situation, because I need < span > treated as it is.
Is there any way to cancel HTML execution for that first part (which can be any variable) or I have to separate them into two different elements and style them?
(and I'm really trying to avoid that)
...maybe check for tags and insert space if any exist??!... relized while writing this question, span tag in pointy brackets :)
You can use createTextNode as an easy (though perhaps not very efficient) way to do this:
function textToHtml(str) {
return document.createTextNode(str).innerHTML;
}
nodeTitle.innerHTML = textToHtml(tabs[j].title) + "<span id='url'>" + ' - ' + textToHtml(tabs[j].url) + "</span>" ;