Randomize Image and Color Pair on Webpage - javascript

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>

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 div with onkeypress event

The main problem: I want a inputfield to change its width based on what the user types in. This is solved. The problem comes when appending the same code several times using the onKeyPress-event with javascript append.
The first picture here shows how the code looks like before the user appends it. The inputfield is changing it's width based on the user input successfully:
The second picture here shows how the same code looks like in the "append"-function before executing:
The third picture shows how the append should look like (the code at the top) to work, while the code below shows how the code looks like after being executed by append. It seems like the 'px';'> is missing out every time it gets appended and the input width change does not work:
The fourth picture shows where all the "bubbles" end up when being appended:
So the question is, how can i get the appended code to act like in the first picture? Right now it's just adding the inputfields/boxes while not changing it's width when the user enters text.
Edit: the code:
var inv = 1;
$("#faPlus0").click(function () {
if (inv < 10) {
$(".bubbleBox").append("<span id='input-append' class='badge badge-secondary'><input type='text' name='invo" + inv + "'id='bubble' placeholder='Navn' onkeypress='this.style.width = ((this.value.length + 2) * 9) + 'px';'></span>");
inv++;
};
});
<span id="input-append" class="badge badge-secondary"><input type="text" name="invo0" id="bubble" placeholder="Navn" onkeypress="this.style.width = ((this.value.length + 2) * 9) + 'px';"></span>
The problem is that you're using single quotes for the keyup function and also for the string inside the function. This will cause some trouble because you'll be closing the tag once you put the second quote (+ 'px').
This is the generated HTML:
<span id='input-append' class='badge badge-secondary'><input type='text' name='invox'id='bubble' placeholder='Navn' onkeypress='this.style.width = ((this.value.length + 2) * 9) + 'px';'></span>
See anything wrong there? StackOverflow's code highlight will show you your mistake.
You'll have to escape those quotes to make this work. My recommendation would be to use this:
.append("... onkeypress=\"this.style.width = ((this.value.length + 2) * 9) + 'px';\"> ...
Also, add a space before the id part.

Insert html element into a previously dynamically inserted element?

Here is my first question here, I've been looking for an small clue on many researches but didn't found any piece of answer, hope it's not a silly thing.
I'll try to be straight: I'm working on a website dealing with xml files (data is stored in an array then displayed and fully editable).
Until now and despite some troubles I figured out, everything works fine.
I loop on my array to get all the required string then create jQuery object (such as $("<input id='xxx' value='yyy' />") that I appendTo a specific div).
At first start, I have an empty #insertXml div (written in my html).
One my xml files parsed and my array ready, I dynamcically create a #content div appended to my #insertXml, then for each index I'll have its key written in a #keyInput" div (dynamic insert, only once), then 1st value in a #lang1 div (still dynamic insert), 2nd in #lang2 div, etc.
lang1, lang2, etc are variables, so it's written:
$("<input .../>").appendTo("#"+langN);
where langN changes on each loop.
Everything works FINE!... at 1st display :/
The trouble is, when I'm using my function that creates new data.
I work first on a modal window, to retrieve user values through the listener function, then pass it to another function that pushes it in my array.
I debugged it, that works, my array is correctly updated.
Then I want to simply refresh my page, so I try, the same way I did previously for my whole data, to append a few inputs.
It works then correctly on my #keyInput div, but NOT on my #lang divs !?!?!
No matter how I try (even forgetting jQuery and using html document.xxx functions), no way.
While debugging, all my variables are OK, it just does nothing when doing the "appendTo", except once for the keyInput div.
I tried then to remove the #content div and relaunch the whole displayInit() method (heavy operation but, just to see) and same damn problem: only the #keyInput is correctly refreshed.
The only thing I've read that may be interesting, is that dynamically created elements (through script) are not registered in the DOM, so it can't be found.
BUT in that case, none of my display attempts should work, so?
In advance, THANK YOU very much for taking care about my nightmare.
Attached: my html + JS function.my DOM
function displayInsert() {
var firstLang = stripXmlExtension(paths[0]); // same keys on every language, so we grab the 1st one
var lastKeyIndex = mapXml[firstLang].key.length - 1;
var keyToInsert = mapXml[firstLang].key[lastKeyIndex]; // == last insertion
var inputKey = "<input size=35 type=text id=k" + lastKeyIndex + " value=" + stripHTML(keyToInsert.replace(/ /g, " ")) + " readonly />";
// while appending tag to the HTML content page, we add a dblclick listener that will morph the input into a textarea when double dblclicked
$(inputKey).css("margin-bottom", "15px").dblclick(function (e) {
e.preventDefault();
tempEditId = $(this).attr('id');
$(".modal-body").html("<textarea cols='65' rows='10' id='txt" + $(this).attr('id') + "'>" + $(this).val() + "</textarea>");
$("#modalEdit #btn-correct").css("display", "none");
$("#modalEdit").modal({backdrop: "static"});
}).appendTo("#keyInput");
for (var i = 0; i < paths.length; i++) {
var lang = stripXmlExtension(paths[i]);
var lastValueIndex = mapXml[lang].value.length - 1;
var valueToInsert = mapXml[lang].value[lastValueIndex]; // == last insertion
var inputValue = "<input size=35 type=text id=" + lang + "---" + lastValueIndex + " value=" + stripHTML(valueToInsert.replace(/ /g, " ")) + " readonly />";
// while appending tag to the HTML content page, we add a dblclick listener that will morph the input into a textarea when double clicked
$(inputValue).css("margin-bottom", "15px").dblclick(function (e) {
e.preventDefault();
tempEditId = $(this).attr('id');
$(".modal-body").html("<textarea cols='65' rows='10' id='txt" + $(this).attr('id') + "'>" + $(this).val() + "</textarea>");
$("#modalEdit #btn-correct").css("display", "none");
$("#modalEdit").modal({backdrop: "static"});
}).appendTo("#" + lang);
}
}
OMG, I'm ashamed.
My problem came from an input generated in a modal window that took the same id that was duplicated...
I was hoping it would be a little more complicated ^^
Solved!

Removing spaces between lines in JavaScript

I'm just learning JavaScript, and I've come up with the following page that "draws" a guitar fretboard by creating a 6X16 grid of images (the first column is the set of "open notes" on the very left hand side of the image grid). The page is here.
Each of the six rows represents a string on the guitar so, six strings, six rows. But what I can't figure out is how to make the rows butt up right next to each other, with no whitespace between the top of one row and the bottom of the next. So, what I get is this:
But what I want is this:
The way that the JavaScript works is to run through a loop that is 16 items long - one "open string" image, and 15 "fretted note" images, and at the end of the loop it generates a <br/>tag. These strings are inserted into an InnerHTML value of a <p> element, and the grid of images gets drawn. Here is the line of code that generates, as an example, the fretted note image:
for(frets=0; frets < 17; frets++){
GuitarNeckImg.innerHTML = GuitarNeckImg.innerHTML + "<img title=" + allNotes[frets + 1] + " src=images\\" + allFretImages[frets + 1] + ">";
continue;
}
What I don't understand is:
What CSS attribute/value pairs do I need to enter to get the images
to not have any space between them above and below,and
How do I write the JavaScript code to add those CSS attribute/value pairs to the tag in my code?
Add'l information:
I have tried, as an example, to write the following code in my JS file:
GuitarNeckImg.innerHTML = GuitarNeckImg.innerHTML + "<img title=" + allNotes[frets + 1] + " style=padding:0px; margin:0px;" + " src=images\\" + allFretImages[frets + 1] + ">";
But this produces the following HTML output:
<img title="F.Esharp.Gbb" style="padding: 0px;" src="images\F.jpg" margin:0px;="">
So the first problem is specifically around JS syntax and how I need to craft the code statement to generate multiple attribute/value pairs for the style tag, and the second is which CSS tags I should use to get my desired results.
Thanks in advance, and please feel free to let me know what additional information I can provide.
An appropriate line-height value, such as 0.70, should do exactly what you want.
Try this...
//We define the text variable that needs to be cleansed of line breaks.
Var someText = "Here's some text.\n It has some line breaks that will be removed \r using Javascript.\r\n";
//This javascript code removes all 3 types of line breaks
someText = someText.replace(/(\r\n|\n|\r)/gm,"");
Best of luck...

prevent execution of innerHTML

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>" ;

Categories

Resources