for loop failing to loop continuously - javascript

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/']");

Related

How to run a function on click and url change JQuery

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);
}
}
}
});
});

jQuery load function inside jQuery load function

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.

Javascript doesn't work when have another one

I searched but I didn't find the answer.
I have a code that change the color of my wordpress template blocks and posts randomly. Actually it changes the classes of these blocks and so the colors. You can see the code here:
function inArray(array , exist) {
var rslt = false;
for (var j = 0; j < array.length; j++)
{
if (array[j] == exist)
{
rslt = true;
}
}
return rslt;
}
var colored = Array();
function changeColor(target) {
var blocks = document.getElementsByClassName(target);
var blockLength = blocks.length;
for (var i = 0; i < blockLength; i++)
{
if (colored.length >= 9)
{
colored = [];
}
var rand = 0;
while (rand == 0 || inArray(colored , rand))
{
rand = Math.floor(Math.random()*10)%10;
}
colored.push(rand);
blocks[i].className = target+' color'+rand ;
}
}
window.onload = function() {
changeColor('block');
changeColor('post');
}
the code you seen placed in an external file named 'colors.js' and included by:
<script src="<?php bloginfo('template_url'); ?>/scripts/colors.js"></script>
in my wordpress template.
the code works correctly til I add another code like this:
<script>var _mxvtmw_position = 'left', _mxvtmw_domain = 'icomp.ir'</script>
<script src="http://iwfcdn.iranwebfestival.com/js/mx.vtmw.min.js?12688" async="async"></script>
Why? And how can i fix this problem?
Thank you.
EDIT:
DEMO: http://tuts.icomp.ir/
IN CASE blocks.length IS 1 YOU HAVE TO ADD ONE MORE IF CONDITION
if (blocks.length==undefined){
//code
}

Javascript, looping through gridview checking hidden values

I need some help :). Im trying to build a Javascript that goes through a gridview on my page and for each row checks the hiddenvalue that is stored in a certain cell of that row. It should then check this against a filtervalue and if it doesnt match hide the row in question.
How can I do this?
While not the most elegant, this should get you started in the right direction:
<script type="text/javascript">
function HideEvenValueRows() {
var tGrid = document.getElementById('<%= GridView1.ClientID%>');
for (var i = 0; i < tGrid.rows.length; ++i) {
var inputs = tGrid.rows[i].getElementsByTagName("input");
for (var j = 0; j < inputs.length; ++j) {
if (inputs[j].type == "hidden") {
var k = inputs[j].value * 1;
if (k % 2 == 0) {
tGrid.rows[i].style.visibility = "collapse";
}
}
}
}
}
</script>

Javascript function returning fixed value from array

I'm newbie with JavaScript, so I decided to develop a little application which is supposed to show the schedule of the streetcar of the place I live, because of the lack of the information on the official webpage.
I have several arrays with the starting time of the line, and as the time to reach each station it's the same, I only have to add the total minutes to the first hour.
There's a form for the user to set a range of hours. So, my main problem is that the "adder();" function is supposed to iterate and print all the values from an array. Instead of doing that, it takes always the same index, 24, so if the array returned has less than 24 indexes, it does not work.
Here's the HTML:
< input type="button" class="submit" value="Enviar" onclick="caller()"/>
JavaScript:
function cropHours(i){
if (i.substr(0,2) >= hora1user_recortada && i.substr(0,2) <= hora2user_recortada) {
horas.push(i);
}
return horas;
}
function adder() {
minInicio1 = horas[i].substr(0,2);
minInicio2 = horas[i].substr(3,2);
document.getElementById("test4").innerHTML = "---" + minInicio1+"_"+minInicio2;
y = parseInt(total) + parseInt(minInicio2);
document.getElementById("test5").innerHTML = "total vale "+total+"minInicio1 vale "+minInicio1+"... minInicio2 vale "+minInicio2+"...Y vale "+y;
html += "<td>"+y+"</td>";
document.getElementById("horario").innerHTML = html;
}
This is a part of another function:
if (platform == 1) {
for (var j = 0; j <= indexorigen; j++) {
total += mins1[j];
}
for (var j = 0; j <= indexdestino; j++) {
total2 += mins1[j];
}
if (today !== "Sábado" || today !== "Domingo") {
for each (var i in horainiciolaboral1) {
cropHours(i);
//adder(horainiciolaboral1);
}
} else {
for each (var i in horainiciofinde1) {
cropHours(i);
}
}
} else {
for (var x = 0; x <= indexorigen; x++) {
total += mins2[x];
}
for (var x = 0; x <= indexdestino; x++) {
total2 += mins2[x];
}
if (today !== "Sábado" || today !== "Domingo") {
for each (var i in horainiciolaboral2) {
cropHours(i);
}
} else {
for each (var i in horainiciofinde2) {
cropHours(i);
}
}
}
/*for (var i = 0; i <= horainiciolaboral1.length; i++) {
adder(horainiciolaboral1);
}*/
//horario = horas.slice(11);
for each (var i in horas) {
adder();
}
document.getElementById("test6").innerHTML = horas;
document.getElementById("test3").innerHTML = total + "----" + total2;
// ******************************************
// ** FUNCTION WHICH CALLS EVERY FUNCTION **
// ******************************************
// STARTS
function caller() {
cleaner();
retrieve_origen();
retrieve_destino();
getIndex();
sumMinutes();
getHours();
}
This is the problem:
for each (var i in horas) {
adder();
}
Thank you in advance.
Pass i to adder() as an argument:
adder(i);
...and define it as a parameter in the function:
function adder( i ) {
//...

Categories

Resources