Repeat jquery statement using while loop - javascript

I am new to JavaScript/jQuery. I have a script file linked to a page. I am trying to repeat a simple jQuery statement using while loop in the file. Below are the codes sample. How can I repeat them in while loop?
The codes:
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(1)").addClass("quote_1");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(2)").addClass("quote_2");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(3)").addClass("quote_3");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(4)").addClass("quote_4");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(5)").addClass("quote_5");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(6)").addClass("quote_6");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(7)").addClass("quote_7");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(8)").addClass("quote_8");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(9)").addClass("quote_9");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(10)").addClass("quote_10");
I am trying but not working:
var i = 0;
while( i < 10 ) {
return 'e(".rwpt_testimonials .rwpt_photos ul li:nth-child(' + i + ')").addClass("quote_' + i + '");';
i++;
}

You can use the jQuery method .each() to iterate through each list item.
JS (jQuery):
$('.rwpt_testimonials .rwpt_quotes ul li').each(function(i) {
$(this).addClass('quote_'+(i+1));
});
Here's a fiddle.

return is only used in functions to return a value. Here you can just straight up execute e:
var i = 0;
while( i < 10 ) {
e(".rwpt_testimonials .rwpt_photos ul li:nth-child(" + i + ")").addClass("quote_" + i);
i++;
}
However, a for loop (instead of while) is generally used when you know how many times you're going to be looping:
for(var i = 0; i < 10; ++i) {
e(".rwpt_testimonials .rwpt_photos ul li:nth-child(" + i + ")").addClass("quote_" + i);
}
You may want to rethink about what you're doing though, for the sake of efficiency and maintainability.

Related

Pagination script style current page number after click on next/ previous buttons

I am working on a pagination script (code below); and I don't know how to select the current pagination number after clicking on the next previous buttons (I have added a comment to the missing bit below: removeClass('current'); and addClass('current') to active pagination number; ). The style should work the same as directly clicking on the page number $("#pagin li a").click(function()...
here is a picture:
pagination style when current page selected
Thank you in advance for your help!
pageSize = 4;
incremSlide = 5;
startPage = 0;
numberPage = 0;
var pageCount = $(".browsethearchive-items").length / pageSize;
var totalSlidepPage = Math.floor(pageCount / incremSlide);
for(var i = 0 ; i<pageCount;i++){
$("#pagin").append('<li>'+(i+1)+'</li> ');
if(i>pageSize){
$("#pagin li").eq(i).hide();
}
}
var prev = $("<li/>").addClass("prev").html("Prev").click(function(){
startPage-=1;
incremSlide-=1;
numberPage--;
slide();
});
prev.hide();
var next = $("<li/>").addClass("next").html("Next").click(function(){
startPage+=1;
incremSlide+=1;
numberPage++;
slide();
});
$("#pagin").prepend(prev).append(next);
$("#pagin li").first().find("a").addClass("current");
slide = function(sens){
$("#pagin li").hide();
for(t=startPage;t<incremSlide;t++){
$("#pagin li").eq(t+1).show();
}
if(startPage == 0){
next.show();
prev.hide();
}else if(numberPage == totalSlidepPage ){
next.hide();
prev.show();
}else{
next.show();
prev.show();
}
}
showPage = function(page) {
$(".browsethearchive-items").hide();
$(".browsethearchive-items").each(function(n) {
if (n >= pageSize * (page - 1) && n < pageSize * page)
$(this).show();
});
}
showPage(1);
$("#pagin li a").eq(0).addClass("current");
var $listItems = $('#pagin li a');
var activeLink;
$("#pagin li a").click(function() {
$listItems.removeClass('current');
$(this).addClass('current');
var activeLink=$(this);
showPage(parseInt($(this).text()));
});
var i = 1;
$(".prev").click(function() {
// removeClass('current');
// addClass('current') to active pagination number;
if (i != 1) {
showPage(--i);
}
});
$(".next").click(function() {
// removeClass('current');
// addClass('current') to active pagination number;
if (i < ($('.browsethearchive-items').length)/4) {
showPage(++i);
}
});
UPDATE here is a fiddle with the working code — > https://jsfiddle.net/JoChicau/em19ku8v/39/ — > thanks to #biberman!
You can select the list element with the class "current" in this way:
$("#pagin li a.current")
For setting the class "current" to the next or previous list element you can use the jQuery methods next() and prev(). Since you set the class to the anchor inside the list element you first have to select the parent of the anchor with the parent() function to get the list element itself and after using next() or prev() select the anchor inside the new list element with find("a").
Working example:
$(".prev").click(function() {
let prevLi = $("#pagin li a.current").parent().prev().find("a");
if (prevLi[0]) {
$("#pagin li a.current").removeClass("current");
prevLi.addClass("current");
}
});
$(".next").click(function() {
let nextLi = $("#pagin li a.current").parent().next().find("a");
if (nextLi[0]) {
$("#pagin li a.current").removeClass("current");
nextLi.addClass("current");
}
});
ul {
list-style: none;
}
li {
display: inline-block;
width: 20px;
height: 20px;
text-align: center;
}
li:not(.next, .prev) {
background-color: grey;
}
li a.current {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="pagin">
<li class="prev"><</li>
<li><a class="current">1</a></li>
<li><a>2</a></li>
<li><a>3</a></li>
<li><a>4</a></li>
<li><a>5</a></li>
<li class="next">></li>
</ul>
Additionally i would recommend to add and remove the classes directly to/from the li tag because it makes the script a bit easier (for example no need for parent() and find("a")).
Working example:
$(".prev").click(function() {
let prevLi = $("#pagin li.current").prev();
if (prevLi.find('a')[0]) {
$("#pagin li.current").removeClass("current");
prevLi.addClass("current");
}
});
$(".next").click(function() {
let nextLi = $("#pagin li.current").next();
if (nextLi.find('a')[0]) {
$("#pagin li.current").removeClass("current");
nextLi.addClass("current");
}
});
ul {
list-style: none;
}
li {
display: inline-block;
width: 20px;
height: 20px;
text-align: center;
}
li:not(.next, .prev) {
background-color: grey;
}
li.current {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="pagin">
<li class="prev"><</li>
<li class="current"><a>1</a></li>
<li><a>2</a></li>
<li><a>3</a></li>
<li><a>4</a></li>
<li><a>5</a></li>
<li class="next">></li>
</ul>
Warning: below code is untested.
Set an id containing the page number on every <a> representing a page. For instance
$("#pagin").append(`<li>${i+1}</li> `);
Then use this id to target the right <a>
$(".prev").click(function() {
if (i != 1) {
i--;
$listItems.removeClass('current');
$(`#pagin li a#page-${i}`).addClass('current');
showPage(i);
}
});

Dynamically create a html list that update

I'm trying to dynamically create a html list that update when new information arrives.
Here is my code :
setlast();
function setlast() {
last = [
"xyyxx", "yxyxx", "xxxxy", "yyxxy", "yxyxy"]
};
setInterval(function() {
last[0] = Math.random();
last[1] = Math.random();
last[2] = Math.random();
last[3] = Math.random();
last[4] = Math.random();
}, 2000);
createHtml();
function createHtml() {
setTimeout(function(){
ul = document.createElement("ul");
document.body.appendChild(ul);
ul.setAttribute("id", "lyl");
for(w=0; w<5; w++) {
li = document.createElement("li");
ul.appendChild(li);
}
updateT();
},3500);
}
function updateT() {
setInterval(function() {
li.innerHTML = last[w];
},2000);
}
#listwrapper {
margin-top: 2%;
width : 100%;
}
li {
display : inline;
float : left;
padding : 10px;
}
Doing like above, I get undefined.
If I do it like below, the code works but each li do not update every time Math.random generates a new number.:
setlast();
function setlast() {
last = [
"xyyxx", "yxyxx", "xxxxy", "yyxxy", "yxyxy"]
};
setInterval(function() {
last[0] = Math.random();
last[1] = Math.random();
last[2] = Math.random();
last[3] = Math.random();
last[4] = Math.random();
}, 2000)
createHtml();
function createHtml() {
setTimeout(function(){
ul = document.createElement("ul");
document.body.appendChild(ul);
ul.setAttribute("id", "lyl");
for(w=0; w<5; w++) {
li = document.createElement("li");
ul.appendChild(li);
li.innerHTML = last[w];
}
},3500)
}
#listwrapper {
margin-top: 2%;
width : 100%;
}
li {
display : inline;
float : left;
padding : 10px;
}
So my question is: how can I get the list to display and update every time a new number is generated ?
Thanks a lot.
setlast();
function setlast() {
last = [
"xyyxx", "yxyxx", "xxxxy", "yyxxy", "yxyxy"]
};
setInterval(function() {
last[0] = Math.random();
last[1] = Math.random();
last[2] = Math.random();
last[3] = Math.random();
last[4] = Math.random();
}, 2000);
createHtml();
function createHtml() {
setTimeout(function(){
ul = document.createElement("ul");
document.body.appendChild(ul);
ul.setAttribute("id", "lyl");
for(w=0; w<5; w++) {
li = document.createElement("li");
ul.appendChild(li);
}
updateT();
},3500);
}
function updateT() {
setInterval(function() {
list = ul.childNodes;
for (var i = 0; i < list.length; i++) {
list[i].innerHTML = last[i];
}
},2000);
}
#listwrapper {
margin-top: 2%;
width : 100%;
}
li {
display : inline;
float : left;
padding : 10px;
}
This works. Notes:
Create variables without keywords let or var makes them global which is a bad thing. Variables should be accessible only where its supposed to. See this post.
The above code will fail if the number of elements in the last list is less then the number of li elements appended to ul.
Here is a working example using only pur javascript :
/**
* Update The HTML
*
* #param {Array} last - ensure the array exist by passing it as an argument
*/
function updateHtml(last) {
const ul = document.querySelector('#toUpdate');
// Empty existing li node
ul.innerHTML = ''
for (let i = 0; i < last.length; i++) {
// create and append li elements
const li = document.createElement('li')
li.innerHTML = last[i]
ul.appendChild(li);
}
}
setInterval(function() {
// call with random stuff
updateHtml([
Math.random(),
Math.random(),
Math.random(),
Math.random(),
Math.random()
])
}, 2000)
// first call with strings
updateHtml([
"xyyxx", "yxyxx", "xxxxy", "yyxxy", "yxyxy"
]);
#listwrapper {
margin-top: 2%;
width: 100%;
}
li {
display: inline;
float: left;
padding: 10px;
}
<div id="main">
<ul id="toUpdate">
</ul>
</div>
There is many things to say about DOM Update but most of all what I've done is to exctract the update function to specialize it so updateHtml manipulate the DOM according to the 'last' argument.
Please note that this is a one way data binding. You can do more by using more complex structures and patterns like Observable.
Hope that help

Why is :lt() not working as expected?

Could you please tell me why :lt() is not working. Here is my code:
https://jsbin.com/refunuyahe/edit?html,js,output
I try to show only 100 items at first, and when the user scrolls it should show a further 100 items.
(function() {
'use strict';
$(function() {
var str = '<ul id="myList">';
var x = 100;
var initialData = '';
for (var i = 0; i < 1000; i++) {
str += '<li>' + i + '</li>';
}
str += '</ul>'
// complete data in str;
// load only first 100 element
$('#container').append(str);
$('#myList li:lt(' + x + ')').show();
})
$('#container').on('scroll', function() {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
x += 100;
$('#myList li:lt(' + x + ')').show();
}
})
})();
Why is this line not working?
$('#myList li:lt(' + x + ')').show();
There are main two problems with your code. Firstly the x variable is out of scope of the scroll event handler. Secondly the li elements are already visible on load, so calling show() on them would have no effect.
To fix this, place the x definition in a higher scope, and use CSS to only show the relevant elements when the page loads. Try this:
$(function() {
'use strict';
var x = 100;
var str = '<ul id="myList">';
for (var i = 0; i < 1000; i++) {
str += '<li>' + i + '</li>';
}
str += '</ul>'
$('#container').append(str);
$('#container').on('scroll', function() {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
x += 100;
$('#myList li:lt(' + x + ')').show();
}
})
});
#container {
height: 300px;
border: 1px solid;
overflow: auto;
}
.hide {
display: none;
}
.showItem {
display: block;
}
/* This is the required part */
#container li:nth-child(-n+100) {
display: list-item;
}
#container li {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='container'></div>
Also note that I tidied your use of an IIFE and document.ready handlers.
I really doubt if it is correct way to achieve what you are actually trying to do. Anyway you'r missing hiding elements.
(function(){
'use strict';
$(function(){
var str ='<ul id="myList">';
var x=100;
var initialData ='';
for(var i=0;i<1000;i++){
str+='<li>'+i+'</li>';
}
str +='</ul>'
// complete data in str;
// load only first 100 element
$('#container').append(str);
$('#myList li:gt('+x+')').hide(); // <-- first hide rest of li's
$('#myList li:lt('+x+')').show();
})
$('#container').on('scroll', function() {
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
x+=100;
// HERE you need to hide elements as well
$('#myList li:lt('+x+')').show();
}
})
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='container'>
</div>

jquery .top is not working

I'm getting error from using top property in my jquery code. The code is about navigation dots on my slider. This is the link to my page: http://54.169.61.153/teavana
Below is my code. I'm getting error in the console saying that:
Uncaught TypeError: Cannot read property 'top' of undefined
$(document).ready(function () {
var one = $("#slider").offset();
var two = $("#tabsDiv").offset();
var three = $("#teaWare").offset();
var four = $("#videoo").offset();
$(window).scroll(function () {
var screenPosition = $(document).scrollTop();
if (screenPosition < one.top) {
$(".teavanamenu li a").removeClass("active");
$(".teavanamenu li a.menu1").addClass("active");
}
if (screenPosition >= two.top) {
$(".teavanamenu li a").removeClass("active");
$(".teavanamenu li a.menu2").addClass("active");
}
if (screenPosition >= three.top) {
$(".teavanamenu li a").removeClass("active");
$(".teavanamenu li a.menu3").addClass("active");
}
if (screenPosition >= four.top) {
$(".teavanamenu li a").removeClass("active");
$(".teavanamenu li a.menu4").addClass("active");
}
});
$(window).scroll();
$(".one, .two").click(function () { $(window).scroll(); });
});
I'm not sure why it can't read the property top. Any help?

jquery string concatenation in selector

i want to concat some string(id) with parent id...
so i'v tried this-------------->
$(' #cate_id2 > ul > li:has(ul) ').hover(function () {
$('#cate_id2 > ul' + this + ' > ul').stop().slideDown('fast');
},
want to concat #cate_id2 > ul with this and than append > ul ....
string should becomes after execute '#cate_id2 > ul' + li:has(ul) + ' > ul'
i mean li:has(ul) will replaced by with its value.......
Try it like this
$(' #cate_id2 > ul > li:has(ul) ').hover(function () {
$(this).children('ul').stop().slideDown('fast');
}

Categories

Resources