Make JS carousel repeat - javascript

I'm using the following code for a simple carousel. I'd like to make it repeat after you get to the third quote-item.
Can anyone help? Thank you.
Here's the JS:
<script>
show()
$(function() {
var currentCarousel = 0;
function changeCarousel() {
$('.quote-item').hide();
$('.quote-item:eq('+ currentCarousel +')').show();
currentCarousel = currentCarousel + 1;
setTimeout(function(){ changeCarousel(); }, 8000);
}
changeCarousel();
$('.quote-change').click(function(e) {
e.preventDefault();
changeCarousel();
});
});
</script>
And this is the HTML:
<div class="quote" >
<div class="quote-item">
<div class="quote-image">
<img src="" alt="quote 1">
</div>
<div class="quote-text">
quote text one
</div>
</div>
<div class="quote-item">
<div class="quote-image">
<img src="" alt="quote 1">
</div>
<div class="quote-text">
quote text Two...
</div>
</div>
<div class="quote-item">
<div class="quote-image">
<img src="" alt="quote 1">
</div>
<div class="quote-text">
quote text THREE...
</div>
</div>
next
</div>

Try this:
$(function () {
var currentCarousel = 0;
var timeoutID = null;
var timeoutDuration = 2000;
var quoteChange = $('.quote-change');
var quoteItems = $('.quote-item');
var numQuotes = quoteItems.length;
function changeCarousel() {
quoteItems.hide();
quoteItems.eq(currentCarousel).show();
currentCarousel += 1;
if (currentCarousel === numQuotes) { currentCarousel = 0; }
clearTimeout(timeoutID);
timeoutID = setTimeout(function () {
changeCarousel();
}, timeoutDuration);
}
changeCarousel();
quoteChange.click(function (e) {
e.preventDefault();
changeCarousel();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="quote">
<div class="quote-item">
<div class="quote-image">
<img src="" alt="quote 1" />
</div>
<div class="quote-text">quote text one</div>
</div>
<div class="quote-item">
<div class="quote-image">
<img src="" alt="quote 2" />
</div>
<div class="quote-text">quote text Two...</div>
</div>
<div class="quote-item">
<div class="quote-image">
<img src="" alt="quote 3" />
</div>
<div class="quote-text">quote text THREE...</div>
</div>
next
</div>
Also you were missing a clearTimeout(); since you have a click handler calling the same changeCarousel() function as well. There is a conflict.
So imagine that by default, your setTimeout keeps calling changeCarousel() recursively and assuming it was right in the middle of another loop (4 seconds) when you decide to click on next button and jump to next carousel item by yourself. Because of that, your newly displaying carousel item will now only stay visible for the remaining 4 seconds but instead it should have had a full 8 seconds stay. Making sense?
Hope you find it useful.

Update your changeCarousel so if currentCarousel >= slides.length it resets to 0
function changeCarousel() {
$('.quote-item').hide();
$('.quote-item:eq('+ currentCarousel +')').show();
if(currentCarousel >= slides.length ){
currentCarousel = 0;
} else{
currentCarousel++;
}
setTimeout(function(){ changeCarousel(); }, 8000);
}

Related

Trying to use javaScript to make the second image shows instead of the first

I'm trying to show the next image by just adding the style: display(none) but it is not working at all
<script>
function displayBanner() {
var count = 1;
if (count == 1) {
document.getElementById("banner_img3").style.display = "none";
}
}
displayBanner();
</script>
<header>
<div class="banner">
<div id="banner">
<div class="banner_img" id="banner_img1"></div>
<div class="banner_img" id="banner_img2"></div>
<div class="banner_img" id="banner_img3"></div>
</div>
</div>
</header>
Your element does not exist when you execute the script before the element. Move the script to after the elements or move displayBanner into a load event
I assume you want to rotate the images
var count = 0, max;
function displayBanner() {
document.getElementById("banner_img"+count).style.display = "none";
count++
if (count === max ) count = 0
document.getElementById("banner_img"+count).style.display = "block";
}
window.addEventListener("load", function() {
max = document.querySelectorAll(".banner_img").length;
document.getElementById("banner_img0").style.display = "block";
setInterval(displayBanner, 3000);
})
.banner_img { display:none; text-align:center }
<header>
<div class="banner">
<div id="banner">
<div class="banner_img" id="banner_img0"><img src="http://lorempixel.com/output/animals-q-c-640-480-1.jpg" /><br/>Image 1</div>
<div class="banner_img" id="banner_img1"><img src="http://lorempixel.com/output/animals-q-c-640-480-2.jpg" /><br/>Image 2</div>
<div class="banner_img" id="banner_img2"><img src="http://lorempixel.com/output/animals-q-c-640-480-3.jpg" /><br/>Image 3</div>
</div>
</div>
</header>
your div didn't have any source add a source using <img src=""></img> for the div try below code for that
<header>
<div class="banner">
<div id="banner">
<div class="banner_img" id="banner_img1"><img src="http://templatesforcv.com/wp-content/uploads/06.jpg" ></div>
<div class="banner_img" id="banner_img2"><img src="http://templatesforcv.com/wp-content/uploads/06.jpg"></div>
<div class="banner_img" id="banner_img3"><img src="http://templatesforcv.com/wp-content/uploads/06.jpg"></div>
</div>
</div>
</header>
window.onload=displayBanner();
function displayBanner() {
var count = 1;
if (count == 1) {
document.getElementById("banner_img3").style.display = "none";
}
}
working demo:https://jsfiddle.net/athulmathew/yh2esp1c/21/

javascript memory game, need to add congrats message at the end of game

I have created a memory game with javascript, html and css, the game is complete but I am having difficulty adding the last part, which that when all cards are matched a message box need to show to the user e.g. "Well Done! all cards have been matched". I tried SweetAlert and different lines of code, but can't get the message.
I am showing here the whole JS code here and HTML at the bottom of the page
const cards = document.querySelectorAll('.card');
//On first flipped card if match with second flipped card it will lock both cards
let hasFlippedCard = false;
let lockBoard = false;
let firstCard, secondCard;
function flipCard() {
if (lockBoard) return;
if (this === firstCard) return;
this.classList.add('flip');
if (!hasFlippedCard) {
hasFlippedCard = true;
firstCard = this;
return;
}
secondCard = this;
checkForMatch();
}
//If cards match it will freeze those cards and it will prevent them from flipping back - managed with dataset html atribute
function checkForMatch() {
let isMatch = firstCard.dataset.legend === secondCard.dataset.legend;
isMatch ? disableCards() : unflipCards();
}
//Matched card will be disabled for clicks once they are flipped
function disableCards() {
firstCard.removeEventListener('click', flipCard);
secondCard.removeEventListener('click', flipCard);
resetBoard();
}
//If cards don't match it will flip the cards back in 0.5s and you will have a new attempt to make
function unflipCards() {
lockBoard = true;
setTimeout(() => {
firstCard.classList.remove('flip');
secondCard.classList.remove('flip');
resetBoard();
}, 500);
// Add Move
addMove();
}
//Moves
const movesContainer = document.querySelector(".moves");
let moves = 0;
movesContainer.innerHTML = 0;
function addMove() {
moves++;
movesContainer.innerHTML = moves;
rating();
}
//Star Rating
const starsContainer = document.querySelector(".stars");
const star = `<li><i class="fa fa-star"></i></li>`;
starsContainer.innerHTML = star + star + star;
function rating() {
if( moves < 12) {
starsContainer.innerHTML = star + star + star;
} else if( moves < 18) {
starsContainer.innerHTML = star + star;
} else {
starsContainer.innerHTML = star;
}
}
//Timer
const timerContainer = document.querySelector(".timer");
let liveTimer,
totalSeconds = 0;
timerContainer.innerHTML = totalSeconds + ' s';
function startTimer() {
liveTimer = setInterval(function() {
totalSeconds++;
timerContainer.innerHTML = totalSeconds + 's';
}, 1000);
}
startTimer()
function stopTimer() {
clearInterval(liveTimer);
}
//Congrats message
//Game Reset
function myButton() {
location.reload();
}
//If second card match with first card it will return from the function
function resetBoard() {
hasFlippedCard = false;
lockBoard = false;
firstCard = null;
secondCard = null;
}
//Use to shuffle cards - 8 front and 8 back side = 16
(function shuffle() {
cards.forEach(card => {
let randomPos = Math.floor(Math.random() * 16);
card.style.order = randomPos;
});
})();
cards.forEach(card => card.addEventListener('click', flipCard));
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Your Memory</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Jura" rel="stylesheet">
</head>
<body>
<!-- info -->
<div class="container">
<div class="info">
<h1>Test Your Memory</h1>
</div>
<section class="score-panel">Rating:
<ul class="stars"></ul>
<br>
<hr>
<br>
Moves: <span class="moves"></span>
<hr>
<br>
Timer: <span class="timer"></span>
<hr>
<br>
<button onclick="myButton()">Start Over Again</button>
</div>
</section>
<!-- end info -->
<!-- game -->
<section class="game">
<div class="card" data-legend="legend1">
<img class="front" src="images/legend1.png" alt="Github" />
<img class="back"/>
</div>
<div class="card" data-legend="legend1">
<img class="front" src="images/legend1.png" alt="Github" />
<img class="back"/>
</div>
<div class="card" data-legend="legend2">
<img class="front" src="images/legend2.png" alt="Tumblr" />
<img class="back"/>
</div>
<div class="card" data-legend="legend2">
<img class="front" src="images/legend2.png" alt="Tumblr" />
<img class="back"/>
</div>
<div class="card" data-legend="legend3">
<img class="front" src="images/legend3.png" alt="Wikipedia" />
<img class="back"/>
</div>
<div class="card" data-legend="legend3">
<img class="front" src="images/legend3.png" alt="Wikipedia" />
<img class="back"/>
</div>
<div class="card" data-legend="legend4">
<img class="front" src="images/legend4.png" alt="Tumblr" />
<img class="back"/>
</div>
<div class="card" data-legend="legend4">
<img class="front" src="images/legend4.png" alt="Tumblr" />
<img class="back"/>
</div>
<div class="card" data-legend="legend5">
<img class="front" src="images/legend5.png" alt="Wordpress" />
<img class="back"/>
</div>
<div class="card" data-legend="legend5">
<img class="front" src="images/legend5.png" alt="Wordpress" />
<img class="back"/>
</div>
<div class="card" data-legend="legend6">
<img class="front" src="images/legend6.png" alt="Wikipedia" />
<img class="back"/>
</div>
<div class="card" data-legend="legend6">
<img class="front" src="images/legend6.png" alt="Wikipedia" />
<img class="back"/>
</div>
<div class="card" data-legend="legend7">
<img class="front" src="images/legend7.png" alt="The New York Times" />
<img class="back"/>
</div>
<div class="card" data-legend="legend7">
<img class="front" src="images/legend7.png" alt="The New York Times" />
<img class="back"/>
</div>
<div class="card" data-legend="legend8">
<img class="front" src="images/legend8.png" alt="Wordpress" />
<img class="back"/>
</div>
<div class="card" data-legend="legend8">
<img class="front" src="images/legend8.png" alt="Wordpress" />
<img class="back"/>
</div>
</section>
<!-- end game -->
<script src="js/jscript.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</body>
</html>
If i got your code right, then when there is a match of two cards - 'resetBoard' is called.
In that case i would set up a counter, initialized to zero, that incremented every 'resetBoard' call.
So, at the top of your script i would add:
const cards = document.querySelectorAll('.card');
//On first flipped card if match with second flipped card it will lock both cards
let hasFlippedCard = false;
let lockBoard = false;
let firstCard, secondCard;
let matchCounter=0;
.
.
.
Then, when there is a match.. we will increment that variable:
.
.
.
//If second card match with first card it will return from the function
function resetBoard() {
hasFlippedCard = false;
lockBoard = false;
firstCard = null;
secondCard = null;
matchCounter+=1;
}
.
.
.
Now, I am not sure if there is a function that checks if the game is over (tell me if i missed that one), but lets assume there isn't. In that case we can add an if statement that checks if the player matched all cards (which means that the matchCounter should equals the amount of pairs):
.
.
.
//If second card match with first card it will return from the function
function resetBoard() {
hasFlippedCard = false;
lockBoard = false;
firstCard = null;
secondCard = null;
matchCounter+=1;
if(matchCounter==(cards.length/2)){
window.alert("Congratulations! You Won!");
}
}
.
.
.
window.alert simply pops up a message in browser.
EDIT:
Ok, after another look at your code I found that resetBoard() is called even there is not a match, so the increment and the if statement should be somewhere else, where you check if there was a match:
//If cards match it will freeze those cards and it will prevent them
from flipping back - managed with dataset html atribute
function checkForMatch() {
let isMatch = firstCard.dataset.legend === secondCard.dataset.legend;
if(isMatch){
matchCounter+=1;
disableCards();
if(matchCounter==(cards.length/2)){
window.alert("Congratulations! You Won!");
}
}
else{ unflipCards(); }
}

How to get this code to move one class at a time

So I have three DIVs with the same carousel effect. I am pretty sure I can use three different JavaScript codes to move one at a time but would like to make it as minimal code as possible. With the current code, when I click on the arrow once, all three of them moves. How can I get them to move separately?
There's three of the same one as the one below:
(function ($) {
$.fn.thumbGallery = function (settings) {
var $this = $(this);
return this.each(function () {
settings = jQuery.extend({
speed: 1000,
leftArrow: $this.find('.arrow-left'),
rightArrow: $this.find('.arrow-right'),
galleryContainer: $this.find('.gallery-inner'),
visibleImagesSize: 4
}, settings);
var imgElements = settings.galleryContainer.find('img').length;
var size = settings.visibleImagesSize;
//settings.leftArrow.hide();
if (imgElements > settings.visibleImagesSize) {
settings.rightArrow.show();
} else {
//settings.rightArrow.hide();
}
function animateLeft() {
var el = settings.galleryContainer.children(":last");
settings.galleryContainer.animate({
left: '+=' + el.outerWidth(true) + 'px'
},
settings.speed);
}
function animateRight() {
var el = settings.galleryContainer.children(":first");
settings.galleryContainer.animate({
left: '-=' + el.outerWidth(true) + 'px'
},
settings.speed);
}
function checkArrows() {
if (size === settings.visibleImagesSize) {
//settings.leftArrow.hide();
} else {
settings.leftArrow.show();
}
if (size === imgElements) {
//settings.rightArrow.hide();
} else {
settings.rightArrow.show();
}
}
settings.leftArrow.click(function () {
animateLeft();
size--;
checkArrows();
});
settings.rightArrow.click(function () {
animateRight();
size++;
checkArrows();
});
});
};
})(jQuery);
$(document).ready(function () {
$('.gallery').thumbGallery();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="open-space">
<h2>Open Space</h2>
<p class="description">Desk space in an open shared office environment that can be used in various of ways.</p>
<center>
<div class="gallery">
<div class="arrow-left">
<div class="arrow-left-small">
</div>
</div>
<div class="gallery-outer">
<div class="gallery-inner">
<div class="gallery-tmb">
<img src="images/openspace1.png" alt="Open Space1" height="auto" width="250"/>
</div>
<div class="gallery-tmb">
<img src="images/openspace2.png" alt="Open Space2" height="auto" width="250"/>
</div>
<div class="gallery-tmb">
<img src="images/openspace3.png" alt="Open Space3" height="auto" width="250"/>
</div>
<div class="gallery-tmb">
<img src="images/openspace4.png" alt="Open Space4" height="auto" width="250"/>
</div>
<div class="gallery-tmb">
<img src="images/openspace5.png" alt="Open Space5" height="auto" width="250"/>
</div>
<div class="gallery-tmb">
<img src="images/openspace6.png" alt="Open Space6" height="auto" width="250"/>
</div>
</div>
</div>
<div class="arrow-right">
<div class="arrow-right-small">
</div>
</div>
</div>
<span class="btn_margin">
<asp:Button ID="Button3" runat="server" Text="More lists" CssClass="btn btn-primary top" OnClick="Btn_More_Click" />
</span>
</center>
</div>
The reason they move together is because you use the .gallery selector when you call thumbsGallery(), which applies to all elelements that have class="gallery" in the HTML code. What you can do is to simply add a unique id to each of the gallery and call thumbsGallery() with each of the selectors.
HTML:
<div class="gallery" id="executive_gallery">
...
</div>
<div class="gallery" id="conference_gallery">
...
</div>
<div class="gallery" id="open_gallery">
...
</div>
Javascript:
$(document).ready(function () {
$('.gallery#executive_gallery').thumbGallery();
$('.gallery#conference_gallery').thumbGallery();
$('.gallery#open_gallery').thumbGallery();
});
JSFiddle: https://jsfiddle.net/3qeLumkp/1/

jquery - attach/detach multiple divs onclick

I am trying to replace the content of the divs on checkbox's check/un-check events.
HTML:
<div class="checks">
<input type="checkbox" class="section-1" value="section-1">check-1
<input type="checkbox" class="section-2" value="section-2">check-2
<input type="checkbox" class="section-3" value="section-3">check-3
<input type="checkbox" class="section-4" value="section-4">check-4
<input type="checkbox" class="section-5" value="section-5">check-5
<input type="checkbox" class="section-6" value="section-6">check-6
<input type="checkbox" class="section-7" value="section-7">check-7
</div><br><br>
<div class="divs">
<div class="section-1">
<div class="content-1">
div-1
</div>
</div>
<div class="section-2">
<div class="content-2">
div-2
</div>
</div>
<div class="section-3">
<div class="content-3">
div-3
</div>
</div>
<div class="section-4">
<div class="content-4">
div-4
</div>
</div>
<div class="section-5">
<div class="content-5">
div-5
</div>
</div>
<div class="section-6">
<div class="content-6">
div-6
</div>
</div>
<div class="section-7">
<div class="content-7">
div-7
</div>
</div>
</div>
<div class="divs-back" style="display: none">
<div class="section-1">
<div class="content-1">
div-1
</div>
</div>
<div class="section-2">
<div class="content-2">
div-2
</div>
</div>
<div class="section-3">
<div class="content-3">
div-3
</div>
</div>
<div class="section-4">
<div class="content-4">
div-4
</div>
</div>
<div class="section-5">
<div class="content-5">
div-5
</div>
</div>
<div class="section-6">
<div class="content-6">
div-6
</div>
</div>
<div class="section-7">
<div class="content-7">
div-7
</div>
</div>
</div>
jQuery:
$(":checkbox:lt(7)").prop("checked", true);
var array = ["section-1", "section-2", "section-3", "section-4", "section-5", "section-6", "section-7"];
var unArray = [];
var unChecked = 0;
$('input[type="checkbox"]').click(function () {
if ($(this).prop('checked')) {
// Add the new element if checked:
if (array.indexOf($(this).val()) < 0) {
array.push($(this).val());
unChecked = unArray.slice(-1)[0];
unArray.splice(-1, 1);
}
} else {
// Remove the element if unchecked:
if (array.indexOf($(this).val()) >= 0) {
array.splice(array.indexOf($(this).val()), 1);
unArray.push($(this).val());
unChecked = 0;
}
}
showHideDiv($(this).val(), unChecked);
console.log(array);
console.log(unArray);
});
function showHideDiv(value, unCheked) {
console.log(unCheked);
if (unCheked != '0') {
$('.divs').find("." + unCheked).html($('.divs-back').find("." + value).html());
} else {
$('.divs').find("." + value).html('');
}
}
It is replacing the contents successfully on first attempt. But on the second attempt, the positions of the div contents are changed so not getting the desired output.
jsfiddle: https://jsfiddle.net/2th5gmLa/
Edit:
Actually, I don't want to just hide show. I want to replace the div content on last unchecked section. When I uncheck Section-1, Section-2, Section-3, then if we check section-1, then it should place in the DIV of the Section-3.
Why your code is not working?
The issue is you are pushing element. The push() method adds new items to the end of an array, and returns the new length.
//array.push($(this).val());
remove this line
Change you have to make.
$('input[type="checkbox"]').click(function() {
var unchkdArray = [];
var chkdArrray = [];
$('input[type="checkbox"]').map(function(){
if ($(this).is(':checked')) {
chkdArrray.push($(this).val())
} else {
unchkdArray.push($(this).val())
}
});
var selected = $(this).val()
if ($(this).is(':checked')) {
$('div.' + selected).show()
} else {
$('div.' + selected).hide()
}
});
Fiddle Demo
Try this...
Plunker Link
$(":checkbox:lt(7)").prop("checked", true);
var array = ["section-1", "section-2", "section-3", "section-4", "section-5", "section-6", "section-7"];
var unArray = [];
var unChecked = 0;
$('input[type="checkbox"]').click(function () {
console.log($(this)['context']['className']);
$( ".divs ."+$(this)['context']['className'] ).toggleClass( "hide" )
});
Plunker Link

Pure Javascript display div based on Menu Item Clicked?

I just need some advice with my current code. I am trying to display a different div depending on the menu item clicked. I was thinking theoretically using some kind of indexing method. i think the if statement i am using for once does not work but also seems a little horrible in terms of coding.
anyway what do you think?
/**
* Lets get Menu container
*/
var menu = document.getElementById("configurator-menu");
/**
* Set Current Tab and Store which tab is Active
*/
var navitem = menu.querySelector(".configurator-menuitems div");
navitem.className += " " + "activeTab";
/**
* Add click events to Menu Tabs
*/
var tabs = menu.querySelectorAll(".configurator-menuitems div");
for (var i = 0; i < tabs.length; i++) {
tabs[i].onclick=displayPage;
}
/**
* Tabs Logic
*/
function displayPage() {
var items = menu.querySelectorAll(".configurator-menuitems div");
for (var i = 0; i < items.length; i++) {
items[i].classList.remove("activeTab");
}
this.className += " " + "activeTab";
if (this.classList.contains("mainMenu1")) {
var item = document.getElementByClassName("appCanvas1");
item.style.display = "block";
}
else if (this.classList.contains("mainMenu2")) {
var item = document.getElementByClassName("appCanvas2");
item.style.display = "block";
}
else if (this.classList.contains("mainMenu3")) {
var item = document.getElementByClassName("appCanvas3");
item.style.display = "block";
}
}
<div id="configurator-menu" class="appMenu" style="background-color:#001A35;">
<div class="appLogo">
Logo Here
</div>
<hr class="no-margin" />
<div class="configurator-menuitems">
<div class="mainMenu-btn mainMenu1">Shape</div><hr class="no-margin" />
<div class="mainMenu-btn mainMenu2">Size</div><hr class="no-margin" />
<div class="mainMenu-btn mainMenu3">Color</div><hr class="no-margin" />
</div>
<div class="menuspacer"></div><hr class="no-margin" />
<div class="currentSettings">
<p class="settings-title">Your Selection</p>
<p class="variant-config">Shape: </p>
<p class="variant-config">Colors: </p>
<p class="variant-config">Size: </p>
<p class="variant-config">Quantity: </p>
<p class="variant-config">Total Price: </p>
</div>
</div>
<div class="canvas-wrapper">
<div class="appCanvas1" style="background-color:#e7e7e7;">
<div class="shape-selection-bar">
<div class="shape-selector"><img src="'.plugins_url("pentant_conical.png", __FILE__).'" alt="" /></div>
<div class="shape-selector"><img src="'.plugins_url("pendant_cyl.png", __FILE__).'" alt="" /></div>
<div class="shape-selector"><img src="'.plugins_url("standing_lamp_conical.png", __FILE__).'" alt="" /></div>
<div class="shape-selector"><img src="'.plugins_url("standing_lamp_cyl.png", __FILE__).'" alt="" /></div>
</div>
<div class="configurator-progressBtn"> Move On</div>
</div>
<div class="appCanvas2" style="background-color:#e7e7e7;">
<div class="configurator-progressBtn"> Move On</div>
</div>
<div class="appCanvas3" style="background-color:#e7e7e7;">
<div class="configurator-progressBtn"> Move On</div>
</div>
</div>

Categories

Resources