Loop fadeIn and fadeout every 2 items in javascript, jquery - javascript

i would like to ask how to make loop fadeIn and fadeout every 2 items from unorder list. I trying to do this with jQuery but my loop only take 1 by 1 item.
<div>
<ul>
<li>item1</li> // will be first display
<li>item2</li> // will be first display
<li>item3</li> // will be second display
<li>item4</li> // will be second display
<li>item5</li> // will be third display
</ul>
</div>
My javaScript code. I try to split array for 2 elements each array then im trying to fade out it.
function slide(elements) {
var perChunk = 2
var inputArray = Array.from(elements[0].children);
var result = inputArray.reduce((resultArray, item, index) => {
const chunkIndex = Math.floor(index/perChunk)
if(!resultArray[chunkIndex]) {
resultArray[chunkIndex] = []
}
resultArray[chunkIndex].push(item)
return resultArray
}, [])
console.log('res',result);
$(inputArray).hide();
setInterval(function() {
result.map(el => {
$(el).show().fadeIn();
});
}, 2000);
}

Using .slice() you can select a range of elements, then each time increase the start of that range.
With the help of this question to call a function when all elements have finished .fadeOut() (otherwise you get a callback per element), gives:
var items = $("ul>li");
var pos = 0;
var count = 2;
items.hide().slice(pos, pos+count).show();
setInterval(() => {
$.when(items.slice(pos, pos+count).fadeOut())
.then(function() {
pos += count;
if (pos>items.length)
pos = 0;
items.slice(pos, pos+count).fadeIn();
});
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<ul>
<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
</ul>
</div>
There are, of course, many different ways to do this, for example using $("ul>li").each((idx) => and comparing the idx (index) value or using a setTimeout instead of the $.when to fadeIn when fadeOut has completed.

If you are just doing two list items together each time:
In your for loop increment i by 2 each time and set i and i+1 to visible, fadein and the rest to hidden, fadeout. With your example have 5 items, I would put a check to make sure the i+1 is not greater than your set list length.
for(i=0;i<list_length;i+=2){
//Add fade out ability here if you want it to happen before the fadein
$(list[i]).fadin();
$(list[i+1]).fadein();
//Add fade out ability here if you want it to happen after the fadein
}
If you are no just make every other item in your list fade in and out. Set an id for the ones you want to pair together, then loop over your list and fadein and fadeout which ones want active at a time. If this is the option you are looking for I can add some example code but I think you are looking for the first option.

Related

Make div appear or disappear with javascript

I am attempting to make a few divs behave the way I want them to. Here is my relevant HTML:
<ul class="services">
<li class="business-formation" id="services-li-1">Business Formation</li>
<li class="domestic-relations" id="services-li-2">Domestic Relations</li>
<li class="estate-probate" id="services-li-3">Estate & Probate</li>
</ul>
<div class="business-formation-list" id="business-formation-list">
<ul>
<li>Items go here</li>
</ul>
</div>
<div class="domestic-relations-list" id="domestic-relations-list">
<ul>
<li>Items go here</li>
</ul>
</div>
<div class="estate-probate-list" id="estate-probate-list">
<ul>
<li>Items go here</i>
</ul>
</div>
I want the divs to appear and disappear when the corresponding li is clicked (they are links). Here is my Javascript:
document.getElementById('services-li-1').style.cursor = "pointer";
document.getElementById('services-li-2').style.cursor = "pointer";
document.getElementById('services-li-3').style.cursor = "pointer";
const div1 = document.querySelector('business-formation-list');
const div2 = document.querySelector('domestic-relations-list');
const div3 = document.querySelector('estate-probate-list');
const click2 = document.getElementById('services-li-2');
document.addEventListener('click', (event) => {
if (event.click2.className = 'domestic-relations') {
div1.style.display = 'none';
div2.style.display = 'block';
div3.style.display = 'none';
}
});
This doesn't make anything happen, but what I wanted it to do is to make the second div appear when the li with the class name "domestic-relations" is clicked. What am I doing wrong? Thanks!
If you're using querySelector, you need to tell it that it's a class. You do that by adding . before the class in question.
So document.querySelector('business-formation-list') should be document.querySelector('.business-formation-list').
However, if you're only using it once, it should be an ID, not a class.
Im also fairly new to this and had a similar problem to yours. I came up with a solution, so it might help you as well. The solution is quite long so I hope you can bear with me.
first thing is to change your your div class "domestic/estate/business" to just "list". When you're doing the css for it, you'll want to apply the same style to them. If you need more styling, you can always target the IDs or add another css class.
Once you've done that, apply to that list "display: none;". This will hide all your ul's at once.
The javascript looks something like this. i've added some description as to why I chose to do what I did.
var serviceType = document.querySelectorAll(".serviceType");
var serviceTypeArray = Array.prototype.slice.call(serviceType); // this will
//change your serviceType from a nodelist to an Array.
var serviceDescription = document.querySelectorAll(".list"); // to grab the
//list of descriptions and make it into an "array"
for ( i = 0 ; i < serviceTypeArray.length ; i++) {
var services = serviceTypeArray[i]; // I created this variable to store the
// variable "i"
services.addEventListener( "click" , displayServices); }
// created this "for loop" to loop through every element inside the array
//and give it the "click" function
function displayServices() {
var servicePosition = serviceTypeArray.indexOf(this); // when we click the
// event, "this" will grab the position of the clicked item in the array
if (serviceTypeArray[servicePosition].hasAttribute("id") == false) { //
// the hasAttribute returns values of true/false, since initially the
// serviceTypeArray didn't have the "id" , it returns as false
serviceTypeArray[servicePosition].setAttribute( "id" , "hide"); // I've
// added the "setAttribute" function as a unique indicator to allow
// javascript to easily hide and show based on what we are clicking
serviceDescription[servicePosition].style.display = "block"; // When you
//click one of the serviceType, it returns an the index number (aka the
// position it is inside the arrayList)
//this gets stored inside servicePosition(aka the actual number gets
// stored).
// Since i've made an array to store the the description of each service,
// their position in the array correspond with the service's position
//inside the serviceType array made earlier; therefore, when I press one
// particular serviceType (ie i clicked on "business formation"), the
// appropriate text will pop up because the position of both the name and
// its description are in the same position in both arrays made
} else if (serviceTypeArray[servicePosition].hasAttribute("id") == true ) {
//since the serviceType now has an attribute, when we check it, it'll come
// back as true
serviceTypeArray[servicePosition].removeAttribute("id"); //we want to
// remove the id so next time we click the name again, the first "if"
// condition is checked
serviceDescription[servicePosition].style.display = "none"; //this is
// so that the display goes back to "none"
}
}
This will allow to click any of the names and display/hide them at will. you can even show 2/3 or all three of them, it's up to you. I hope this helps and I hope the explanation is clear enough!
Let me know if you have any questions for this!

how to get divs to display one at a time, set to a time

I have been playing with setInterval and setTimeout to get one div to display before moving on to get the second div to display and then the third (final). After the final div displays I want to loop back to the first div to begin the process of toggling the divs again.
setInterval(function(){
$(".one").toggle();
$(".two").toggle();
}, 5000);
So I find that this loop works really well but when I introduce the ".third" div it skips the second and I am super confused!!
Give them all the same class, and use a counter variable that you increment each time to know which one to show. Use modulus to wrap around when you reach the last div.
var counter = 0;
setInterval(function() {
$(".class").hide();
$(".class").eq(counter).show();
counter = (counter + 1) % $(".class").length;
}, 2000);
.class {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class">
Div 1
</div>
<div class="class">
Div 2
</div>
<div class="class">
Div 3
</div>
<div class="class">
Div 4
</div>
you need to iterate over your divs otherwise you are just toggling all of them every 5000ms, which might seem to work for only two divs, but not gonna work for more
pseudocode:
var divs = [$(".one"),$(".two"),$(".three")]
var index = 0
function focusNextDiv(){
//hide all divs
//select divs[index] and toggle it
//increment index by 1
//check if index is bigger than divs.length if so reset index to 0
}
setInterval(function(){
focusNextDiv()
}, 5000);

Custom slider with automatic timed animation and also controls

I am trying to create a news slider that consists of a big slide area (picture and heading) and a second area to the left which contains a simple list of all the slides.
I've managed to get the slider to work so that you can click on one of the list items and this then changes the slide.
However, I'd also like the slider to animate by default through all the slides. I'd like clicking on a list item to override the animation and make the animation loop go to the point in the loop at which the current slide is at. So if the user clicks slide 2, the next slide to be animated to will be slide 3. I'd also like hovering over a slide to pause the animation.
Any ideas how I can achieve the animation/hover part? I am new to jQuery so pretty confused.
This is what I've come up with so far:
var $newsitem = jQuery('.featured-news');
var $newsitem1 = jQuery('.featured-news.item-1');
var $newsitem2 = jQuery('.featured-news.item-2');
var $newsitem3 = jQuery('.featured-news.item-3');
var $newslistitem1 = jQuery( '.newslist.item-1' );
var $newslistitem2 = jQuery( '.newslist.item-2' );
var $newslistitem3 = jQuery( '.newslist.item-3' );
// click actions
$newslistitem1.click(function () {
$newsitem.hide();
$newsitem1.fadeIn();
});
$newslistitem2.click(function () {
$newsitem.hide();
$newsitem2.fadeIn();
});
$newslistitem3.click(function () {
$newsitem.hide();
$newsitem3.fadeIn();
});
// timed actions
animate();
function animate() {
$newsitem1.delay(4000).hide();
$newsitem2.delay(4000).fadeIn();
$newsitem2.delay(4000).hide();
$newsitem3.delay(4000).fadeIn();
}
HTML:
<ul>
<li class="newslist item-1">
News item 1
</li>
<li class="newslist item-2">
News item 2
</li>
<li class="newslist item-3">
News item 3
</li>
</ul>
<ul>
<li class="featured-news item-1">
<img src="http://placehold.it/350x150">
<br>News Story 1
</li>
<li class="featured-news item-2" style="display: none">
<img src="http://placehold.it/350x150">
<br>News Story 2
</li>
<li class="featured-news item-3" style="display: none">
<img src="http://placehold.it/350x150">
<br>News Story 3
</li>
</ul>
And here's a fiddle:
http://jsfiddle.net/HdDG6/
here is how I modified your code :
First, setup global variables :
var $newsitem = $('.featured-news');
// global variable of the current slide
var current = 0;
// global variable interval, which will call "nextSlide" func every 3s
var interval = setInterval(nextSlide, 3000);
I updated your slide list click function so it become general. You won't need to setup every slide click event now :
// attach event to every list item
$('.newslist').click(function () {
// clear the interval
clearInterval(interval);
// set it back to reset the timer
interval = setInterval(nextSlide,3000);
// set current slide var to .newslist item index (0, 1, 2,...)
current = $(this).index();
// hide every shown item
$newsitem.hide();
// show item which index = current slide index
$newsitem.eq(current).fadeIn();
});
Then I created the nextSlide function which will increment current before hiding every slides and showing the current one as $('.newslist').click function
function nextSlide () {
// if current slide is the last one, go back to the first, else increment
if (current == $newsitem.length - 1) {
current = 0;
} else {
current++;
}
// hide every slides and show the good one
$newsitem.hide();
$newsitem.eq(current).fadeIn();
}
Then I finally set the hover event, which simply clear the timer when mouse enter .featured-news and set it back on mouse leave :
$('.featured-news').hover(function(ev){
clearInterval(interval);
}, function(ev){
interval = setInterval(nextSlide,3000);
});
Here is a working fiddle : DEMO
This way you can add as many slides as you want without changing the code. You can also bind nextSlide function to any button or control (like arrow keys or a "next slide" button).
Hope I helped you :)

loop a list using a jquery - carousel effect

I'm trying to loop a list making a carousel effect. I think it should know first the counts of all the list so it can do math. then it can do something like this. If it add on the other side it will remove something on the other side. So if I remove the first list item it will add the the last item.
$(function() {
$('#up').mouseenter(goUp);
$('#down').mouseenter(goDown);
function goUp() {
$('#list').last('li').remove;
$('#list').first('li').append('put the first item here')
}
function goDown() {
$('#list').first('li').remove;
$('#list').last('li').append('put the first item here')
}
}
<a id="up">+</a>
<ul id="list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<a id="down">-</a>
You have a bunch of errors there and I think your logic is wrong. You want to use a .current class and hide() or show() the items. Something like this should work.
$items.hide().first().addClass('cur').show();
var actions = {
getCurIdx: function(){
return $items.filter('.cur').index();
},
goTo: function(idx){
// Something like...
$items
.removeClass('cur').hide()
.eq(idx).addClass('cur').show();
},
next: function(){
var _idx = actions.getCurIdx();
if(_idx < $items.length) {
actions.goTo(_idx+1);
} else {
actions.goTo(0); // Go first
}
},
prev: function(){
var _idx = actions.getCurIdx();
if(_idx >= 0) {
actions.goTo(_idx-1);
} else {
actions.goTo($items.length-1); // Go last
}
}
};
$next.click(function(){ actions.next(); });
$prev.click(function(){ actions.prev(); });
There's a few problems, first the last and first methods don't work the way you're thinking, you don't pass a selector to them (doc) so what you're actually doing is finding the last element in the matched selector of #list. What you want to be using is the :last selector (doc) (and :first), changing your selectors to.
Next remove is a method not a property, so you are missing some brackets. Also remove will return the jQuery object that you were working against so you can reposition it in the DOM.
Here is a jsfiddle that implements what you want. It uses the before and after methods to insert the new item correctly in the DOM.

Simple Ticker (jQuery)

<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
I'd like to show only one li at a time using slide effect, thats it. I'd like to avoid using plugins for something as simple as this.
Thanks in advance for your help.
i have made something simple up for you (based on your description), just to point you in the right direction:
check it out here:
http://jsfiddle.net/meo/ACenH/234/
function slider(container, delay){
$container = $(container) // select the container elements and store them in a variable
if ( !$container.length ){ return fasle; } // checks if the slider exists in your dom. if not the function ends here...
var slides = $container.length, // gives back the total LI's you have
slide = 0 // set the actual li to show
setInterval(function(){ // set a Interval for your main function
if (slide == slides - 1) { // if the actual slide is equal the total slides (-1 because eq is 0 based and length gives back the number of elements in the jQuery object) the slide counter is set to 0
$container.slideDown(); // and all slides a shown again
slide = 0;
} else {
$container.eq(slide).slideUp(); //slides the selected slide up i think you could think of a solution with .next() instead of eq()
slide++; // slide counter +1
}
}, delay)
}
slider('ul > li', 2000); // call your slider function
Your question already mentions jquery as the javascript framework of choice. The best place you can start is the jquery docs on hiding:
http://api.jquery.com/hide/
and sliding:
http://api.jquery.com/slideUp/
http://api.jquery.com/slideDown/
http://api.jquery.com/slideToggle/

Categories

Resources