I have this code that has to be a tree with random signs. I put setInterval to change the signs every second, but nothing happens and I don't get even any error.
Someone please tell me where I made a mistake, or more :).
window.onload = intervalSetup;
function intervalSetup() {
'use strict';
setInterval(function() {
theTree();
}, 1000);
}
function theTree() {
'use strict';
var x = 8;
for (var i=0; i<x; i++) {
for (var j=x-1; j>i; j--) {
document.write(" ");
}
for (var k=0; k<=(i*2); k++) {
document.write(arraySigns[Math.floor(Math.random() * arraySigns.length)]);
}
document.write("<br>")
}
for (var i=0; i<2; i++) {
for (var j=0; j<(x*2)-3; j++) {
document.write(" ");
}
document.write("**<br>");
}
}
I tested the code on Google Chrome and it worked correctly.
Only had an undefined error in arraySigns.
The script has removed itself by writing to the document. That was the reason, the function was never called twice.
Funny bug, I think. :-)
The first problem was an undefined array, which was fixed in an edit.
The remaining problem was that the trees were being written to the page endlessly and it was hard to see the symbols changing.
By generating the tree in a container div which is cleared before each new tree, you can easily see that the symbols were properly random each time.
The snippet has a working example that functions by adding to the innerHTML of the treeDiv. (I took out the document fragment for readability)
'use strict';
window.onload = intervalSetup;
var arraySigns;
var treeDiv;
function intervalSetup() {
arraySigns = ["*", "^", "&", "#"];
treeDiv = document.getElementById("theTreeDiv");
setInterval(theTree, 1000);
}
function theTree() {
treeDiv.innerHTML = '';
var x = 8;
for (var i=0; i<x; i++) {
for (var j=x-1; j>i; j--) {
treeDiv.innerHTML += " ";
}
for (var k=0; k<=(i*2); k++) {
treeDiv.innerHTML += arraySigns[Math.floor(Math.random() * arraySigns.length)];
}
treeDiv.innerHTML += "<br>";
}
for (var i=0; i<2; i++) {
for (var j=0; j<(x*2)-3; j++) {
treeDiv.innerHTML += " ";
}
treeDiv.innerHTML += "**<br>";
}
}
<div id="theTreeDiv">
</div>
Related
Right now I'm trying to use JQuery to set text at the end of a products name for a website. But the issue is right now it's set up to run when the document is ready.
So for some reason when switching pages it's not refreshing the page just adding to the url and changing products which is fine, but my code doesn't work for the other pages.
Example:
https://www.example.com/category
to
https://www.example.com/category/?sort=featured&page=2
I know that my code isn't as efficient as it could be, and there's reused code. But right now I'm just trying to get it to work before cleaning it up further. I couldn't really find anything online that really worked other than doing a location.reload() when the page nav was pressed. Unfortunately that ended up creating an infinite loop on the page.
I'm not sure if I'm just not thinking of the correct way to go about this or if my code isn't working as intended. I don't get any errors in the console either.
What I've tried:
Creating a selector for the page navigation so when clicked it will run the same code again.
Tried using a listener to listen for the clicks.
Tried checking if the url has changed.
Tried to refresh the page after clicking on page navigation along with using a timeout to wait for the page to change then refresh.
Code:
script1 - Handles adding text to product titles
$(document).ready(function() {
var multiTitle = $(".card-title");
var prodTitle = $(".productView-title");
var array = [list of titles];
if (multiTitle.length > 0) {
for (var i = 0; i < multiTitle.length; i++) {
for (var j = 0; j < array.length; j++) {
if (multiTitle[i].innerText == array[j]) {
var text = document.createElement('span');
text.innerHTML = "<span>text</span></br>";
multiTitle[i].prepend(text);
}
}
}
}
if (prodTitle.length > 0) {
for (var j = 0; j < array.length; j++) {
if (prodTitle[0].innerText == array[j]) {
var text = document.createElement('span');
text.innerHTML = "<span>text</span></br>";
prodTitle[0].append(text);
}
}
}
});
script2 - should re-add text after titles when pages change
$(".pagination-list").click(function() {
$(window).bind('hashchange', function() {
var multiTitle = $(".card-title");\
var prodTitle = $(".productView-title");
var array = [list of titles];
if (multiTitle.length > 0) {
for (var i = 0; i < multiTitle.length; i++) {
for (var j = 0; j < array.length; j++) {
if (multiTitle[i].innerText == array[j]) {
var text = document.createElement('span');
text.innerHTML = "<span>text</span></br>";
multiTitle[i].prepend(text);
}
}
}
}
if (prodTitle.length > 0) {
for (var j = 0; j < array.length; j++) {
if (prodTitle[0].innerText == array[j]) {
var text = document.createElement('span');
text.innerHTML = "<span>text</span></br>";
prodTitle[0].append(text);
}
}
}
});
});
So I'm trying to parse a large amount of data from another website trough JavaScript and jQuery and (I'm new to both) so the problem here is the function inside the 2nd jQuery load() is not working.
function load() {
var r = 0;
var cols = [4,5,8,9,10];
$('#Parser').load('url #tableID', function () {
var r = $('#Parser').find('label').length;
for (var i = 0; i < r; i++) {
$('#table').append('<tr id="'+i+'"></tr>')
for (var j = 0; j < cols.length; j++) {
$('#'+i).append('<td id="c'+i+j+'"></td>')
$('#c'+i+j).load('url #tableId\\:Row'+i+'\\:Col'+cols[j], function() {
$('#c'+i+j).html($('#c'+i+j).children().text());
});
}
}
$('#Parser').html('');
});
}
So if tested this on its own with static id's and it works
$('#test').load('url #tableId\\:Row1\\:Col1', function() {
$('#test').html($('#test').children().text());
});
I need to parse the code by column and row like this because the webpage where I'm getting the data from has the data I want scattered over the columns on the cols variable and I find how many rows the table has on the r variable
I don't know if it's a logic problem or just a misuse of the functions but I have been struggling the whole day and I needed help.
The main load() function is called when the page starts, and this outputs the whole element instead of only the text
var time =new Date().getTime();
var rc = 0;
load();
refresh();
function load() {
var r = 0;
var cols = [4,5,8,9,10];
$('#Parser').load('url #tableID', function () {
var r = $('#Parser').find('label').length;
if (r != 0) {
//Simulating going back to this page
$('body').css({'background-color':'red','color':'white'});
for (var i = 0; i < r; i++) {
if (rc < r) {
$('#table').append('<tr id="'+i+'"></tr>')
}
for (var j = 0; j < cols.length; j++) {
if (rc < r) {
$('#'+i).append('<td id="c'+i+j+'"></td>')
}
col = $('#c'+i+j).load('url #tableId\\:Row'+i+'\\:Col'+cols[j],function() {
if ($('#c'+i+j).html != col){
$('#c'+i+j).html('');
}
});
}
}
}else {
if (rc != 0 ) {
for (var i = 0; i < rc; i++) {
for (var j = 0; j < cols.length ; j++) {
$('#c'+i+j).html('');
}
}
}
if ($('body').css('background-color') != 'white') {
//Simulating another page
$('body').css({'background-color':'white','color':'black'});
}
}
$('#Parser').html('');
if (rc < r) {
rc = r ;
}
});
}
function refresh() {
if(new Date().getTime() - time >= 10000){
load();
setTimeout(refresh, 10000);
}else{
setTimeout(refresh, 10000);
}
}
This is my full javascript on the page
the previous code is my atempt on processing it to text on a simpler way
Try this:
function load()
{
...your code...
}
$(document).ready(load);
Maybe the function is not being called on time, make sure you call it AFTER the DOM has been rendered.
Okay so it was a pretty easy fix, inside the second load function I have replaced
the
$('#c'+i+j).html($('#c'+i+j).children().text());
to
$(this).html($(this).text());
And it works fine now.
I wrote this script to add elements to the DOM according to content stored in an array, then I added a listener on a click event to those elements.
It works, but I am pretty sure it can be improved, any idea?
function writeSuggestions() {
for (var k = 0; k < suggestions.length; k++) {
citySample.innerHTML += "<li>" + suggestions[k][0] + "</li>";
}
for (var i = 0; i < citySample.children.length; i++) {
(function(index){
citySample.children[i].onclick = function(){
lat = suggestions[index][1];
lng = suggestions[index][2];
};
})(i);
}
}
Thank you in advance
I coded a simple program which take 2 textareas and combine every single line of one textarea with all the lines in the second textarea and my browser crushes after 6000 lines.
The resul of my check needs to get to 100,000 lines.
This is the javascript code:
function go() {
var lines1 = $('#text1').val().split(/\n/);
var lines2 = $('#text2').val().split(/\n/);
var textarea1 = [];
var textarea2 = [];
var textarea3 = [];
for (var i = 0; i < lines1.length; i++) {
if (/\S/.test(lines1[i])) {
textarea1.push($.trim(lines1[i]));
}
}
for (var j = 0; j < lines2.length; j++) {
if (/\S/.test(lines2[j])) {
textarea2.push($.trim(lines2[j]));
}
}
for (var k = 0; k < lines1.length; k++) {
for (var q = 0; q < lines2.length; q++) {
textarea3.push($.trim(lines1[k] + ' ' + lines2[q]));
var msg = textarea3.join("\n");
document.getElementById('text3').value = msg;
}
}
}
This is the HTML:
<textarea name="textarea" id="text1"></textarea>
<textarea name="textarea" id="text2"></textarea>
<input type="button" value="GO!" onclick="go()">
<br />
<textarea name="textarea" id="text3"></textarea>
The problem is with this code
for (var k=0; k < lines1.length ; k++) {
for (var q=0; q < lines2.length ; q++) {
textarea3.push($.trim(lines1[k] + ' ' + lines2[q]));
var msg = textarea3.join("\n");
document.getElementById('text3').value = msg;
}
}
If there are 1K lines in textarea1 and 1K in testarea2 then you will modify the DOM (by changing the value of textarea3) 1M times which is insane. So instead of updating the DOM every time try to do it outside the loop.
Try to provide maxlength attribute in textarea and then check I think it will work.
and in your for loops first store all the content in a variable and then outside for loop write it into textarea rather than each time assigning the DOM value inside for loop.
var _target=document.querySelectorAll('.post .content');
var isYT = /youtube|youtu.be/gi;
for (i = 0; i < _target.length; i++) {
var _tar = _target[i].children;
for (var j = 0; j < _tar.length; j++) {
var vidID;
if (_tar[j].tagName == "A") {
if (isYt.test(_tar[j].href) == true) {
_eles.push(_tar[j]);
}
}
if (_tar[j].tagName == "EMBED") {
if (isYt.test(_tar[j].src) == true) {
_eles.push(_tar[j]);
}
}
} //end for loop j
} //end for loop i
console.log(_eles);
The HTML looks sort of like this:
<div>
Video 1
Video 2
<embed src="www.youtube.com/v/239324"></embed>
</div>
<div>
Video 1
Video 2
<embed src="www.youtube.com/v/239324"></embed>
</div>
Though the returning array Object with my console logging is only showing one a element and one embed element. I have to continuously invoke this myself to get all the links and embeds to be placed into the array Object. Any one see any errors I've written, just been working on this issue for about 3 hours now and it is tiring me. Any help is greatly appreciated.
thank you
I have changed your code this way:
var _target = document.querySelectorAll("div");
var _eles = [];
var isYt=new RegExp("\youtube.com");
for (var i = 0; i < _target.length; i++) {
var _tar = _target[i].childNodes;
for (var j = 0; j < _tar.length; j++) {
var vidID;
if(_tar[j].nodeType != 1) continue;
if (_tar[j].tagName.toLowerCase() == "a") {
if (isYt.test(_tar[j].href)) {
_eles.push(_tar[j]);
}
}
if (_tar[j].tagName.toLowerCase() == "embed") {
if (isYt.test(_tar[j].src)) {
_eles.push(_tar[j]);
}
}
} //end for loop j
} //end for loop i
console.log(_eles);
and it works, check this DEMO
but my favorite way to do this is like this:
var _target = document.querySelectorAll("div>a, div>embed");
var _eles = [];
var isYt=new RegExp("\youtube.com");
for (var j = 0; j < _target.length; j++) {
var vidID;
if (_target[j].tagName.toLowerCase() == "a") {
if (isYt.test(_target[j].href)) {
_eles.push(_target[j]);
}
}
if (_target[j].tagName.toLowerCase() == "embed") {
if (isYt.test(_target[j].src)) {
_eles.push(_target[j]);
}
}
} //end for loop j
console.log(_eles);
for this check this one DEMO
and if your isYT regexp is just as simple as I have used in my answer instead of all these lines of code you can simply do:
var _eles = document.querySelectorAll("div>a[href*='youtube.com/'],"+
"div>embed[src*='youtube.com/']");