I want to wrap every three < li > elements inside div and I did it. Now I want to count if there are less than 3 < li> inside that wrapped div, and if it is less than 3, then append < li >
This is my code so far, I don't know why it's not working:
var divs = $(".footer-events .event");
for(var i = 0; i < divs.length; i+=3) {
divs.slice(i, i+3).wrapAll("<div class='item-wrapper'></div>");
}
if ( $('.footer-events .item-wrapper li').length < 3 ) {
divs.append('<li class="event"></li>');
}
All I want is to add < li > to fill the remaining space if number of children is less then three.
Looks like you want to append <li> to some <div>, which is invalid.
Anyway: here's a minimal reproducable example (just plain old js) of what you apparently need.
[edit] A recursive and functional method for this
const uls = document.querySelectorAll("ul");
const createLi = () => Object.assign(
document.createElement("li"),
{className: "created"} );
uls.forEach( ul => {
const thisUl = ul.querySelectorAll("li");
if (thisUl.length < 3) {
let i = 3 - thisUl.length;
while(i--) {
ul.append(createLi());
}
}
});
.created::before {
content: 'hi, I am created';
}
<ul>
</ul>
<ul>
<li>item1</li>
</ul>
<ul>
<li>item1</li>
<li>item2</li>
</ul>
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
Or a bit shorter/recursive
const stuffUntil = 4;
const appendLi = (root, reFillIfNecessary) => {
root.append(Object.assign(document.createElement("li"), {className: "created"}));
reFillIfNecessary();
};
const stuffIt = (len, ul) => len >= stuffUntil ? true :
appendLi(ul, () => stuffIt(len + 1, ul));
const stuffUl = ul => stuffIt(ul.querySelectorAll("li").length, ul);
document.querySelectorAll("ul").forEach(stuffUl);
.created::before {
content: "hi, I am just stuffing";
}
<ul></ul>
<ul>
<li>item1</li>
</ul>
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
</ul>
Related
Background color changing works fine, but font color won't change. Here's my code":
`<div class="navbar-container"></div>
<nav class="navbar" id="navbar">
<ul class="menu-links1">
<li>O nama</li>
<li>Servisi</li>
<li>Dogadjaji</li>
</ul>
<img src="blndrlogo.png" alt="">
<ul class="menu-links2">
<li>Galerija</li>
<li>Lokacija</li>
<li>Kontakt</li>
</ul>
</nav>
</div>`
here's JavaScript code, i really don't get the point.:((((((((
const navbar = document.getElementById('navbar');
const navbarText = document.querySelectorAll('.nav-links')
window.onscroll = () => {
if (window.scrollY > 500) {
navbar.classList.add('nav-active');
navbarText.classList.add('nav-text-active')
} else {
navbar.classList.remove('nav-active');
navbarText.classList.remove('nav-text-active');
}
};
use for loop To add a class to a set of elements with a similar class
window.onscroll = () => {
if (window.scrollY > 500) {
navbar.classList.add('nav-active');
for (var i = 0; i < navbarText.length; i++) {
navbarText[i].classList.add('nav-text-active');
}
} else {
navbar.classList.remove('nav-active');
for (var i = 0; i < navbarText.length; i++) {
navbarText[i].classList.remove('nav-text-active');
}
}
};
Javascript isn't my forte, so I'm looking for help : How would you write a function which add a Class to 3 elements with interval ?
<ul>
<li class="panel">Item 1</li>
<li class="panel">Item 2</li>
<li class="panel">Item 3</li>
</ul>
The idea is to add an .--active class on the 1st item when document is ready and remove it after 2sec to add it to the 2nd item and so on.
If you're using jQuery you could loop through the li's using the index, and reset the index to 0 when you reach the last li element :
if( $('li.panel.active').index() == lis_count-1 )
active_li_index = 0;
else
active_li_index++;
Hope this helps.
jQuery solution:
$(function(){
var lis_count = $('li.panel').length;
var active_li_index = 0;
setInterval(function(){
if( $('li.panel.active').index() == lis_count-1 )
active_li_index = 0;
else
active_li_index++;
$('li.panel.active').removeClass('active');
$('li.panel').eq(active_li_index).addClass('active');
}, 1000);
})
.active{
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="panel active">Item 1</li>
<li class="panel">Item 2</li>
<li class="panel">Item 3</li>
</ul>
Pure JS solution:
document.addEventListener('DOMContentLoaded', function(){
var lis = Array.prototype.slice.call( document.querySelectorAll('li.panel'));
var lis_count = lis.length;
var active_li_index = 0;
setInterval(function(){
var active_li = document.querySelector('li.panel.active');
if( lis.indexOf(active_li) == lis_count-1 )
active_li_index = 0;
else
active_li_index++;
active_li.classList.remove('active');
document.querySelectorAll('li.panel')[active_li_index].classList.add('active');
}, 1000);
}, false);
.active{
background-color: yellow;
}
<ul>
<li class="panel active">Item 1</li>
<li class="panel">Item 2</li>
<li class="panel">Item 3</li>
</ul>
Without jQuery:
function showGarland () {
var itemClass = 'panel';
var activeClass = '--active';
var wait = 2000; // 2 seconds
function toggleActive (element, index, maxIndex) {
setTimeout(function(){
element.classList.add(activeClass);
setTimeout(function(){
element.classList.remove(activeClass);
if (index == maxIndex) {
runLoop();
}
}, wait);
}, wait * index);
}
function runLoop () {
var allItems = document.getElementsByClassName(itemClass);
for (var index = 0; index < allItems.length; index++) {
var element = allItems[index];
toggleActive(element, index, allItems.length - 1);
}
}
runLoop();
}
window.addEventListener('load', showGarland);
.--active {
color:red;
}
<ul>
<li class="panel">Item 1</li>
<li class="panel">Item 2</li>
<li class="panel">Item 3</li>
</ul>
since you use jQuery you can do :
jQuery(() => { // callback when DOM is ready
$('.panel1').addClass('active'); // add your class
setTimeout(() => { // function that execute the callback after 2000ms (2s)
$('.panel1).removeClass('active'); // remove your class active
}, 2000);
});
you should use different class for your differents div
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- <div class="hide">
text
</div> -->
<ul id="Items">
<li class="panel">Item 1</li>
<li class="panel hide">Item 2</li>
<li class="panel hide">Item 3</li>
</ul>
<style>
.hide{
visibility: hidden;
}
</style>
<script>
$(document).ready(function() {
var listItems = $("#Items li");
// alert(listItems);
listItems.each(function(idx, li) {
var product = $(li);
setInterval(function(){
product.css( "visibility", "visible" );
$(li).next().css( "visibility", "hidden" );
$(li).prev().css( "visibility", "hidden" );
}, 2000);
});
});
</script>
The above one works fine for two elements, but for the third element its showing quickly without displayinh the second element.
You can use something like this, you need to call toggleClass with the index you want to start, The functions addClass and removeClass supports multiple elements and multiple classes.
// Add class to element
// support multiple classes
function addClass(elements, className){
// split classes
var classArray = className.split(' ');
var els = [];
// If element does not have length property
if(elements.length == undefined)
els[0] = elements
else
els = elements;
for(e=0; e<els.length; e++){
var element = els[e];
for(i=0; i<classArray.length; i++){
if(element.className.indexOf(classArray[i])==-1){
element.className += ' ' + classArray[i];
}
}
}
}
// Remove class to element
// support multiple classes
function removeClass(elements, className){
var classArray = className.split(' ');
var els = [];
// If elements does not have length property
if(elements.length == undefined)
els[0] = elements
else
els = elements;
for(e=0; e<els.length; e++){
var element = els[e];
for(i= 0; i<classArray.length; i++){
element.className = element.className.replace(classArray[i], '').trim();
}
}
}
function toggleClass(index){
// get active elements and remove active class
removeClass(document.getElementsByClassName('active'), 'active');
// add class to element at index
addClass(document.getElementsByClassName('panel')[index], 'active');
// test if index should increment or reset
if(index<document.getElementsByClassName('panel').length - 1){
index++;
}else{
index = 0;
}
// wait 2sec until execute toggleClass again
setTimeout(toggleClass, 2000, index);
}
toggleClass(0);
.active {
color: green;
}
<ul>
<li class="panel">Item 1</li>
<li class="panel active">Item 2</li>
<li class="panel">Item 3</li>
</ul>
Edit: By the way beware with method classList since you'll need to polyfill for browser compatibility
window.addEventListener("load",function change(i=0){
var els=document.getElementsByClassName("panel");
if(els[i-1]) els[i-1].classList.toggle("active");
els[i].classList.toggle("active");
if(i<els.length-1) setTimeout(change,2000,i+1);
});
You could use a recursive approach to iterate over the class elements slowly and toggle their active class...
Without jQuery:
function showGarland () {
var itemClass = 'panel';
var activeClass = '--active';
var wait = 2000; // 2 seconds
function toggleActive (element, index, maxIndex) {
setTimeout(function(){
element.classList.add(activeClass);
setTimeout(function(){
element.classList.remove(activeClass);
if (index == maxIndex) {
runLoop();
}
}, wait);
}, wait * index);
}
function runLoop () {
var allItems = document.getElementsByClassName(itemClass);
for (var index = 0; index < allItems.length; index++) {
var element = allItems[index];
toggleActive(element, index, allItems.length - 1);
}
}
runLoop();
}
window.addEventListener('load', showGarland);
.--active {
color:red;
}
<ul>
<li class="panel">Item 1</li>
<li class="panel">Item 2</li>
<li class="panel">Item 3</li>
</ul>
Trying not set the background color every time the count is 7 or less, if its already red it shouldnt set it again.
<div class="parent">
<ul class="list">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
<li class="item">Item 4</li>
<li class="item">Item 5</li>
<li class="item">Item 6</li>
<li class="item">Item 7</li>
</ul>
</div>
How can I stop setting the color over and over once the count is less than 7?
var parent = document.querySelector('.parent');
parent.addEventListener('click', changeColor, false);
function changeColor( e ) {
var element = e.target;
var item = document.querySelectorAll('.item');
element.parentNode.removeChild(element);
if( item.length <= 7 ) {
parent.style.background = "red";
console.log(
item.length + " set backgroud color"
)
}
}
DEMO http://jsfiddle.net/Grundizer/awc6rymn/
If I understand your question correctly, this should do the trick:
var parent = document.querySelector('.parent');
var background = 'false';
parent.addEventListener('click', changeColor, false);
function changeColor( e ) {
var element = e.target;
var item = document.querySelectorAll('.item');
element.parentNode.removeChild(element);
if( item.length <= 7 && parent.style.background != 'red') {
parent.style.background = "red";
console.log(
item.length + " set backgroud color"
)
}
You could remove event listener if count is under 7. That way, not only you're not changing color again, you're not running anything on click anymore.
if( item.length <= 7 ) {
parent.style.background = "red";
parent.removeEventListener('click', changeColor, false);
}
And if somewhere you have a function adding element, simply start listening again.
I cannot solve this problem, are you able to solve it? I would need your expert advice on how to do it in JS vanilla or jQuery (optional).
A sample of code on jsfiddle would be high appreciated.
I have to display an array of 5 elements in a list with a limit of 3 at one time
var range = [0,1,2,3,4];
<ul>
<li>0</li>
<li>1</li>
<li>2</li>
</ul>
<div id="prev">prev</div>
<div id="next">next</div>
When user click on "next", I need to add a class "focus" on the first "li".
<ul>
<li class="focus">0</li>
<li>1</li>
<li>2</li>
</ul>
Second click on "next"
<ul>
<li>0</li>
<li class="focus">1</li>
<li>2</li>
</ul>
click on "next" ...
<ul>
<li>0</li>
<li>1</li>
<li class="focus">2</li>
</ul>
click on "next" ... note array shift
<ul>
<li>1</li>
<li>2</li>
<li class="focus">3</li>
</ul>
click on "next" ... array shift
<ul>
<li>2</li>
<li>3</li>
<li class="focus">4</li>
</ul>
click on "next" ... but I cannot go any further as there is not element in the array to be displayed, so if I clicking "prev" I would like have the reverse
click on "prev" …
<ul>
<li>2</li>
<li class="focus">3</li>
<li>4</li>
</ul>
click on "prev" …
<ul>
<li class="focus">2</li>
<li>3</li>
<li>4</li>
</ul>
click on "prev" … note array shift
<ul>
<li class="focus">1</li>
<li>2</li>
<li>3</li>
</ul>
click on "prev" … note array shift
<ul>
<li class="focus">0</li>
<li>1</li>
<li>2</li>
</ul>
click on "prev" … nothing happen it has we reach the beginning go the array
<ul>
<li class="focus">0</li>
<li>1</li>
<li>2</li>
</ul>
Any idea? Thanks in advance
Revised solutions as suggested in answers
http://jsfiddle.net/QwATR/
// Initalize everything
var curPos = 0;
var minIndex = 0;
var maxIndex = 2;
var clicks = 0;
var range = ['0','1','2','3','4','5','6','7','8','9','10'];
if($('li.focus').length === 0)
{
$('ul > li:eq(0)').addClass('focus');
$('ul > li').each(function(index){
$(this).text(range[index+curPos]);
});
}
// Next click handler
$('#next').click(function(){
if($('ul li').index($('li.focus')) < 2)
{
$('li.focus').removeClass('focus');
if(curPos < 2)
curPos++;
else
{
clicks++;
}
$('ul > li:eq('+curPos+')').addClass('focus');
} else {
if(clicks < range.length -3)
clicks++;
}
$('ul > li').each(function(index){
$(this).text(range[index+clicks]);
});
});
// Previous click handler
$('#prev').click(function(){
if($('ul li').index($('li.focus')) > 0)
{
$('li.focus').removeClass('focus');
if(curPos > 0)
curPos--;
else
{
clicks--;
}
$('ul > li:eq('+curPos+')').addClass('focus');
} else {
if(clicks > 0)
clicks--;
}
$('ul > li').each(function(index){
$(this).text(range[index+clicks]);
});
console.log('clicks after prev:' + clicks);
});
http://jsfiddle.net/QAsQj/2/
$(function(){
$("#next").click(function(){
if($(".focus").length == 0){
$("ul li:first-child").addClass("focus");
}
else{
if($(".focus").is(":last-child")){
$("ul li").each(function(){
var content = $(this).next("li").html();
$(this).empty().html(content);
}
$(".focus").html(/**WHATEVER YOUR NEXT CONTENT IS**/);
}
else{
var active = $(".focus");
$("ul li").removeClass("focus");
active.next("li").addClass("focus");
}
}
}
);
$("#prev").click(function(){
if($(".focus").length == 0){
break;
}
else{
if($(".focus").is(":first-child")){
$("ul li").each(function(){
var content = $(this).prev("li").html();
$(this).empty().html(content);
}
$(".focus").html(/**WHATEVER YOUR PREV CONTENT IS**/);
}
else{
var active = $(".focus");
$("ul li").removeClass("focus");
active.prev("li").addClass("focus");
}
}
}
);
}
);
This is quite straightforward in vanilla javascript (jsfiddle)
var range = [0, 1, 2, 3, 4],
lis = document.getElementsByTagName('li'),
foc, offset = 0;
function next() {
if (foc === undefined) {
foc = 0;
} else if (foc < lis.length - 1) {
foc++;
} else if (offset + foc < range.length - 1) {
offset++;
}
rewriteList();
}
function previous() {
if (foc === undefined) {
foc = 0;
} else if (foc > 0) {
foc--;
} else if (offset > 0) {
offset--;
}
rewriteList();
}
function rewriteList() {
for (var i = 0; i < lis.length; i++) {
lis[i].innerHTML = range[i + offset];
lis[i].className = i == foc ? 'focus' : '';
}
}
document.getElementById('prev').onclick = previous;
document.getElementById('next').onclick = next;
Alternatively you could set up the carousels with a constructor function (jsfiddle)
I have an array of numbers. 0,136,1084,3521,3961,5631,6510,7901,8204 (which are the current scrollTops of all of the sections on one page.) I'm trying to find a way to take the current window scrollTop and find out which of these values it's currently between so that when the page is being scrolled, the active navigation item switches.
Currently, while scrolling, 'current page' skips 0 and goes straight to 1 in the array, and as a result, is unable to catch the last page.
currentPage = 0;
divOffset = new Array();
function setCurrentPage() {
divOffset = []; //this ends up as 0,136,1084,3521,3961,5631,6510,7901,8204
//get offset and ID of each section and add to array.
$(".section").each(function() {
sectionOffset = $(this).offset();
divOffset.push(Math.round(sectionOffset.top));
});
bodyOffset = $(window).scrollTop();
for(i=0; i < divOffset.length; i++) {
if( divOffset[i] >= bodyOffset ) {
currentPage = i;
$('#mainNav li').removeClass("active");
$("#mainNav li #a-" + currentPage).parent().addClass("active");
return false;
}
}
}
My navigation looks something like this:
<ul id="mainNav">
<li class="active">home</li>
<li class="menuLI"><a>works</a>
<ul>
<li><a href='#a-1' class='navA' id='a-1'>Websites</a></li>
<li><a href='#a-2' class='navA' id='a-2'>Illustrations</a></li>
<li><a href='#a-3' class='navA' id='a-3'>Photomanipulations</a></li>
<li><a href='#a-4' class='navA' id='a-4'>Glam Guitars</a></li>
<li><a href='#a-5' class='navA' id='a-5'>Logos</a></li>
<li><a href='#a-6' class='navA' id='a-6'>Photography</a></li>
</ul>
</li>
<li>about</li>
<li>contact</li>
</ul>
You can look at it here: http://glowtagdesign.com/index2.php#a-0
Assuming the array is sorted, try this:
var i;
for (i = 0; i < arr.length && pos < arr[i]; i++)
{
}
// i is now the number of items in the array less than pos
// pos is less than the first item -> 0
// pos is greater than the last item -> arr.length