set class active to next slide element - javascript

I have a question about Javascript.
You can find my HTML markup below
<div class="slides">
<div class="slide active" id="one"></div>
<div class="slide" id="two"></div>
<div class="slide" id="third"></div>
<div class="slide" id="fourth"></div>
</div>
<button onclick="slide-down()">
Next slide
</button>
<button onclick="slide-up()">
Previous slide
</button>
What can i do if the user click on the button slide-down to remove with pure javascript the class 'active' en set this to the next slide element?

You can use a single function, set class at <button> elements to "prev" and "next", pass clicked button .className to function; .getElementsByClassName(), .nextElementSibling, .previousElementSibling
.active {
color: green;
}
<div class="slides">
<div class="slide active" id="one">one</div>
<div class="slide" id="two">two</div>
<div class="slide" id="third">third</div>
<div class="slide" id="fourth">fourth</div>
</div>
<button class="next" onclick="slide(this.className)">
Next slide
</button>
<button class="prev" onclick="slide(this.className)">
Previous slide
</button>
<script>
var active = document.getElementsByClassName("active");
function slide(prevNext) {
if (prevNext === "next") {
if (active[0].nextElementSibling) {
active[0].nextElementSibling.className = "active";
active[0].className = "";
}
} else {
if (active[0].previousElementSibling) {
active[0].previousElementSibling.className = "active";
active[active.length - 1].className = "";
}
}
}
</script>

Something like the below will work. Makes use of many javascript DOM properties and methods. You will need to change the names of your functions slightly as a hyphen is not valid in a name of a function. Ive replaced with underscores.
function slide_down(){
var elems = document.querySelectorAll(".slide");
var curr = document.querySelector(".active");
curr.classList.remove("active");
if(curr.nextElementSibling)
curr.nextElementSibling.classList.add("active");
else
elems[0].classList.add("active");
}
function slide_up(){
var elems = document.querySelectorAll(".slide");
var curr = document.querySelector(".active");
curr.classList.remove("active");
if(curr.previousElementSibling)
curr.previousElementSibling.classList.add("active");
else
elems[elems.length-1].classList.add("active");
}
.active{background-color:red}
<div class="slides">
<div class="slide active" id="one">1</div>
<div class="slide" id="two">2</div>
<div class="slide" id="third">3</div>
<div class="slide" id="fourth">4</div>
</div>
<button onclick="slide_down()">
Next slide
</button>
<button onclick="slide_up()">
Previous slide
</button>

Here is an example I wrote. Jasmiec answered before I finished, and I honestly like some of the different methods used in that example. As already mentioned, you will need to change the names of your functions because a hyphen makes the name invalid.
<div class="slides">
<div class="slide active" id="one"></div>
<div class="slide" id="two"></div>
<div class="slide" id="three"></div>
<div class="slide" id="four"></div>
</div>
<button onclick="slideDown()">
Next slide
</button>
<button onclick="slideUp()">
Previous slide
</button>
<script>
var slides = ["one", "two", "three", "four"]
function slideDown() {
var element = document.getElementsByClassName('active')[0];
var index = slides.indexOf(element.id) + 1;
if (index < slides.length) {
element.className = "slide";
document.getElementById(slides[index]).className = "slide active";
}
}
function slideUp() {
var element = document.getElementsByClassName('active')[0];
var index = slides.indexOf(element.id) - 1;
if (index >= 0) {
element.className = "slide";
document.getElementById(slides[index]).className = "slide active";
}
}
</script>

Related

Changing simultaneously text and image on slider

I made a slider with a series of images. I created two buttons (prev and next) that allow browsing the images.
I created also two divs where I put the slide's number and title.
My goal is to change the image, number, and title of the slide simultaneously each time a click event on prev or next buttons occurs.
I have started programming some months ago and I am having difficulties associating images with corresponding titles and numbers.
Could someone help me complete my code?
Actually, the following code works for me to show the image on click but is not complete.
I would like to change all the elements (image, title and number) at the same time after click.
More details on the picture:Screen of the homepage
// Carousel
let sliderImage = document.querySelector(".sliderImage");
let images = [
"carousel1.jpg",
"carousel2.jpg",
"carousel3.jpg",
"carousel4.jpg",
"carousel5.jpg",
"carousel6.jpg",
"carousel7.jpg",
];
let i = 0; // Current image index
// I have already created in html file 2 btns with "onclick" event
// that trigger the following functions:
function prev() {
if (i <= 0) i = images.length;
i--;
return getSlideImg();
}
function next() {
if (i >= images.length - 1) i = -1;
i++;
return getSlideImg();
}
function getSlideImg() {
return sliderImage.setAttribute("src", "img/" + images[i]);
}
<!-- Carousel -->
<div class="carousel-container">
<div class="carousel-slide">
<img src="./img/carousel1.jpg" alt="" class="sliderImage"/>
<!-- Carousel card -->
<div class="carousel__card-container">
<div class="carousel__card-title">Soggiorno</div>
<div class="carousel__slide-data">
<div class="slide__number">01</div>
<div class="slide__loader">
<div class="loader__line-grey">
<div class="loader__line-white"></div>
</div>
</div>
</div>
</div>
<!-- Carousel buttons -->
<div class="carousel-btn">
<a href="#" class="button left-arrow bottone" id="prevBtn" onclick="prev()">
<i class="ri-arrow-left-s-line btn-icon-small"></i>
</a>
<a href="#" class="button right-arrow bottone" id="nextBtn" onclick="next()">
<i class="ri-arrow-right-s-line btn-icon-small"></i>
</a>
</div>
</div>
</div>
set all values inside getSlideImg function so everything will update with corresponding image
// Carousel
let sliderImage = document.querySelector(".sliderImage"),
container = document.querySelector(".carousel-container")
let images = [
"carousel1.jpg",
"carousel2.jpg",
"carousel3.jpg",
"carousel4.jpg",
"carousel5.jpg",
"carousel6.jpg",
"carousel7.jpg",
];
let i = 0; // Current image index
// I have already created in html file 2 btns with "onclick" event
// that trigger the following functions:
function prev() {
if (i <= 0) i = images.length;
i--;
return getSlideImg();
}
function next() {
if (i >= images.length - 1) i = -1;
i++;
return getSlideImg();
}
function getSlideImg() {
container.querySelector(".slide__number").innerText = i + 1
container.querySelector(".carousel__card-title").innerText = images[i]
return sliderImage.setAttribute("src", "img/" + images[i]);
}
// for onload
getSlideImg()
<!-- Carousel -->
<div class="carousel-container">
<div class="carousel-slide">
<img src="./img/carousel1.jpg" alt="" class="sliderImage"/>
<!-- Carousel card -->
<div class="carousel__card-container">
<div class="carousel__card-title">Soggiorno</div>
<div class="carousel__slide-data">
<div class="slide__number">01</div>
<div class="slide__loader">
<div class="loader__line-grey">
<div class="loader__line-white"></div>
</div>
</div>
</div>
</div>
<!-- Carousel buttons -->
<div class="carousel-btn">
<a href="#" class="button left-arrow bottone" id="prevBtn" onclick="prev()">
<i class="ri-arrow-left-s-line btn-icon-small">prev</i>
</a>
<a href="#" class="button right-arrow bottone" id="nextBtn" onclick="next()">
<i class="ri-arrow-right-s-line btn-icon-small">next</i>
</a>
</div>
</div>
</div>

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/

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>

Make JS carousel repeat

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);
}

Accordion with javascript

I've been trying to get an accordion movement going with javascript.
The problem that I'm having is having one close if it's already open and stay closed.
Right now the according closing one and opening another when I click a different div.
I see that the argument is always resolving to true because I'm removing the classes.. but I can't seem to find a away to get around that so I could have a nice accordion.
<div class="speaker-container">
<div class="span3 offset1 speaker" id="sp-info-0">
<div class="speaker-img">
<div class="hover"></div>
<img src="" alt="">
</div>
<h4>Title</h4>
</div>
<div class="speaker-info" id="sp-info-0">
<button class="close-speaker">Close</button>
<h2>Title</h2>
</div>
<div class="span3 offset1 speaker" id="sp-info-1">
<div class="speaker-img">
<div class="hover"></div>
<img src="" alt="">
</div>
<h4>Sub Title</h4>
</div>
<div class="speaker-info" id="sp-info-1">
<button class="close-speaker">Close</button>
<h2>Title</h2>
</div>
<div class="span3 offset1 speaker" id="sp-info-2">
<div class="speaker-img">
<div class="hover"></div>
<img src="" alt="">
</div>
<h4>Title</h4>
</div>
<div class="speaker-info" id="sp-info-2">
<button class="close-speaker">Close</button>
<h2>Title</h2>
</div>
</div>
var timer;
$('.speaker-container .speaker').on('click', function(){
var speakerContainer = document.getElementsByClassName('speaker-container');
var self = this;
var children = $('.speaker-container').children();
var selfHeight = this.clientHeight;
var parentOffset = this.parentElement.offsetHeight;
var selfOffset = this.nextElementSibling.offsetHeight;
console.dir(children);
console.log(parentOffset);
$('.speaker-container').removeClass('open').css({'height' : selfHeight + 'px'});
for (var i = 0; i < children.length; i++) {
if (children[i].className == 'speaker-info fade') {
console.dir(children[i]);
$(children[i]).removeClass('fade');
}
}
if (self.parentElement.className !== 'speaker-container open' && self.nextElementSibling.className !== 'speaker-info fade') {
timer = setTimeout(function(){
self.parentElement.setAttribute('class' , 'speaker-container open');
self.parentElement.style.height = selfOffset + selfHeight + 'px';
self.nextElementSibling.style.top = selfHeight + 'px';
self.nextElementSibling.setAttribute('class' , 'speaker-info fade');
// return false;
}, 500);
} else {
$('.speaker-container').removeClass('open').css({'height' : selfHeight + 'px'});
self.nextElementSibling.setAttribute('class' , 'speaker-info');
window.clearTimeout(timer);
}
});
Make a class that has the item open. (let's say the class is "open")
Make a class that has the item closed. (let's say the class is closed")
let's say all the accordion items are in the accordion class.
function that opens an item:
cycle through and remove any existing open item classes, add closed class.
add open class to the selected item.
by default, give closed class to all items (except the one you want open by default, if any)
with javascript it would look something like:
function openOnClick()
{
var openaccordion=document.getElementsByClassName('open');
openaccordion.className.replace( /(?:^|\s)open(?!\S)/g , 'close' );
this.className.replace( /(?:^|\s)close(?!\S)/g , 'open' );
}
with jQuery it would look like this:
$('div.accordion').click(function(){
$('.open').removeClass('open').addClass('close');
$(this).removeClass('close').addClass('open');
}
you can use jqueryui to get some sliding effects in there pretty simply too:
$(this).switchClass('close','open',1000);

Categories

Resources