Reputation:
I am trying to make the slides fade in and out instead of display none/block using JS. Is this going to need to be done using css or can i do it just in JS. Thanks
code:
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentDot(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
console.log('SHOWSLIDES');
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("nav-dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
or would it be better converting this to jquery and using .fadeOut() / .fadeIn()
Upvotes: 0
Views: 1137
Reputation: 626
Before: Just look a little bit into it source of jQuery:
http://james.padolsey.com/jquery/#v=1.11.2&fn=fadeIn
http://james.padolsey.com/jquery/#v=1.11.2&fn=animate
Here is an approach how you could possibly do it:
var fadeInBtn = document.getElementById('fadeIn');
fadeInBtn.addEventListener('click', function() {
var testString = document.getElementById('test');
fadeIn(testString, 30);
});
var fadeOutBtn = document.getElementById('fadeOut');
fadeOutBtn.addEventListener('click', function() {
var testString = document.getElementById('test');
fadeOut(testString, 60);
});
function fadeIn(element, speed) {
var interval = setInterval(function () {
var opacity = parseFloat(element.style.opacity);
if(opacity >= 1.0) {
clearInterval(interval);
}
element.style.opacity = opacity + 0.1;
}, speed);
};
function fadeOut(element, speed) {
var interval = setInterval(function () {
var opacity = parseFloat(element.style.opacity);
if(opacity <= 0) {
clearInterval(interval);
}
element.style.opacity = opacity - 0.1;
}, speed);
}
div {
font-size: 300%;
}
<button id="fadeIn">Test .fadeIn()</button>
<button id="fadeOut">Test .fadeOut()</button>
<div id="test" style="opacity: 0">Example String</div>
Another solution is to use CSS(3) for this. I reference this already asked question here: Using CSS for fade-in effect on page load
Upvotes: 1