Reputation: 4679
I'll explain it via wordings + screenshot
I have three containers which contains the following down below.
Each of them has different id's and same class.
<div id="container" class='list-cont'>
<h2> One Two Three Four</h2>
</div>
<div id="container-1" class='list-cont'>
<h2> Four Five Six </h2>
</div>
<div id="container-2" class='list-cont'>
<h2> Seven Eight Nine Ten Eleven</h2>
</div>
The purpose of what I'm doing is, making each container's first half of words into different color, and the rest are different color too, like this one. But the main problem is, the code is constantly looping that I don't know why it's happening, the page reload non-stop.
Code:
//Count total number of div's which has a class of list-cont
var div_items = $(".list-cont").length;
for (var q = 1; q <= div_items; q++) {
//If 1 the container who doesn't have "-" will get an update
if (q = 1) {
//Get value of h2 of the container who doesn't have "-"
var s = $('div#container h2').html();
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
//Number of words
var str_length = s.split(' ').length;
//Words in an array
var str_array = s.split(' ');
//Get total of first half of words
var len_first = Math.round(str_length / 2);
//Delete Value of h2
$("div#container h2").html('');
for (var ctr = 0; ctr < str_length; ctr++) {
if (ctr >= len_first) {
$("div#container h2").append(" <font color='#fdbd16'>"+ str_array[ctr] +"</font> ");
} else {
$("div#container h2").append(" " + str_array[ctr] + " ");
}
}
} else {
//Container has "-" like container-1 or container-2
//Get value of h2 of the container who doesn't have "-"
var s = $('div#container-'+ q +' h2').html();
s = s.replace(/(^\s*)|(\s*$)/gi,"");
s = s.replace(/[ ]{2,}/gi," ");
s = s.replace(/\n /,"\n");
//Number of words
var str_length = s.split(' ').length;
//Words in an array
var str_array = s.split(' ');
//Get total of first half of words
var len_first = Math.round(str_length / 2);
//Delete Value of h2
$("div#container-"+ q +" h2").html('');
for (var ctr = 0; ctr < str_length; ctr++) {
if (ctr >= len_first) {
$("div#container-"+ q +" h2").append(" <font color='#fdbd16'>"+ str_array[ctr] +"</font> ");
} else {
$("div#container-"+ q +" h2").append(" " + str_array[ctr] + " ");
}
}
}
}
Upvotes: 0
Views: 115
Reputation: 3113
There's a lot wrong with your code, but the thing that's making it loop infinitely is this
for (var q = 1; q <= div_items; q++) {
if (q = 1) {
// q is now 1
// so it stays lower than div_items (3) forever, the loop continues
}
}
You want to check the value of q, not set it
if (q == 1) {
Upvotes: 2