JavaScript disrupting CSS animations

I've just embarked on creating a simple landing-page website. One component of the page is a basic image slider with navigation controls powered by JavaScript. I managed to get everything functioning except for achieving a smooth transition between images - similar to the one demonstrated in this example. Upon analyzing related inquiries on Stackoverflow, I discovered that my issue lies in updating the 'display' element through

slides[i].style.display = "none"; 
and
slides[slideIndex-1].style.display = "block";
, which overrides the necessary CSS code for the desired slide animation. As someone relatively new to Web development, I found it challenging to comprehend potential solutions proposed on Stackoverflow. I would greatly appreciate anyone offering guidance on resolving my specific problem or proposing an alternative approach.

Cheers, Jerome

var slideIndex = 1;
showSlides(slideIndex);

// Next/previous controls
function plusSlides(n) {
  showSlides(slideIndex += n);
}

// Thumbnail image controls
function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("item");
  var dots = document.getElementsByClassName("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";
}

//automatic

var slideIndexAuto = 0;
showSlidesAuto();

function showSlidesAuto() {
  var i;
  var slides = document.getElementsByClassName("item");
  var dots = document.getElementsByClassName("dot");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slideIndexAuto++;
  if (slideIndexAuto > slides.length) {
    slideIndexAuto = 1
  }
  slides[slideIndexAuto - 1].style.display = "block";
  dots[slideIndexAuto - 1].className += " active";
  setTimeout(showSlidesAuto, 5000);
}
.slider {
  width: 65%;
  max-width: 940px;
  height: 500px;
  border-radius: 0.25rem;
  position: relative;
  overflow: hidden;
}

.slider .left-slide,
.slider .right-slide {
  position: absolute;
  height: 40px;
  width: 40px;
  background-color: #444444;
  border-radius: 50%;
  color: #ffffff;
  font-size: 20px;
  top: 50%;
  cursor: pointer;
  margin-top: -20px;
  text-align: center;
  line-height: 40px;
}

.slider .left-slide:hover,
.slider .right-slide:hover {
  box-shadow: 0px 0px 10px black;
  background-color: #29a8e2;
}

.slider .left-slide {
  left: 30px;
}

.slider .right-slide {
  right: 30px;
}

.slider .slider-items .item img {
  width: 100%;
  height: 500px;
  display: block;
}

.slider .slider-items .item {
  position: relative;
  transition: 4s;
}

.slider .slider-items .item .caption {
  position: absolute;
  width: 100%;
  height: 100%;
  bottom: 0px;
  left: 0px;
  background-color: rgba(0, 0, 0, .5);
}
<div class="slider">
  <div class="slider-items">
    <div class="item fade">
      <img src="/images/cs-slider-high.jpg" />
      <div class="caption">
        <p class="caption-text">COMING</p>
        <p class="caption-text">OKTOBER 10th</p>
      </div>
    </div>

    <div class="item fade">
      <img src="/images/building-slider.jpg" />
      <div class="caption">
        <p class="caption-text-2">Blackstoneroad 109</br>
        </p>
      </div>
    </div>
    <div class="item fade">
      <img src="/images/kontact-slider.jpg" />
      <div class="caption">
        <p class="caption-text-3">Coffee<br>Drinks<br>Food<br>& More</p>
      </div>
    </div>
    <div class="item fade">
      <img src="/images/seminar-slider.jpg" />
      <div class="caption">
        <p class="caption-text-3">Seminar Rooms<br>Inspiration<br>Shopping<br>& More</p>
      </div>
    </div>

  </div>

  <!-- Next and previous buttons -->
  <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
  <a class="next" onclick="plusSlides(1)">&#10095;</a>

</div>

<!-- The dots/circles -->
<div class="align-text-center">
  <span class="dot" onclick="currentSlide(1)"></span>
  <span class="dot" onclick="currentSlide(2)"></span>
  <span class="dot" onclick="currentSlide(3)"></span>
  <span class="dot" onclick="currentSlide(3)"></span>
</div>

Answer №1

What about this link: http://jsfiddle.net/lharby/qox05y96/

To simplify things, I've removed the dot animation (although that code is more aligned with the effect you're aiming for).

Here's the simplified JS:

function displaySlides(index) {
  var count;
  var slideItems = document.getElementsByClassName("item");
  var dots = document.getElementsByClassName("dot");
  if (index > slideItems.length) {
    index = 1
  }
  if (index < 1) {
    index = slideItems.length
  }
  for (count = 0; count < slideItems.length; count++) {
    slideItems[count].classList.remove('active');
  }
  slideItems[index - 1].className += " active";
}

//automatic slideshow
var autoIndex = 0;
autoSlideshow();

function autoSlideshow() {
  var count;
  var slidesAuto = document.getElementsByClassName("item");
  var dotsAuto = document.getElementsByClassName("dot");
  
  for (count = 0; count < slidesAuto.length; count++) {
    slidesAuto[count].classList.remove('active'); 
  }
  autoIndex++;
  if (autoIndex > slidesAuto.length) {
    autoIndex = 1
  }
  slidesAuto[autoIndex - 1].classList.add('active'); 
  setTimeout(autoSlideshow, 4000);
}

This also means some adjustments to the CSS. Using display none/block is not ideal for css transitions, so I've opted for opacity: 0/1 and visibility: hidden/visible. Keep in mind this might affect positioning of item elements as they can't be relatively positioned, stacking them on top of one another or side by side. Normally, animated slideshows use absolute positioning for each slide, but I understand your concerns about that.

CSS:

.slider .slider-items .item {
    visibility: hidden;
    opacity: 0;
    transition: 4s;
}

.slider .slider-items .item.active {
    visibility: visible;
    opacity: 1;
    transition: 4s;
}

Now all the css modifications are done within the css file while js simply adds or removes a class name, making updates easier.

Answer №2

When it comes to CSS, there are certain priorities that need to be taken into consideration. Please review this information and let me know if it has any impact on your current situation. If not, I can step in and troubleshoot the code for you. Just so you know, I primarily focus on JavaScript development. However, when necessary, I do utilize CSS and HTML within my JS projects. I encourage you to give it a try first as it will help enhance your skills as a developer.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to attach an event listener to a div so that clicking on it increases the width and height of the div by 20%?

I've started working on it and decided to use the same dimensions (100px by 100px) as a previous question. Right now, I'm sticking with just Javascript, but I might incorporate jQuery down the line. One big issue is that in the line (this.style.w ...

Is there a way to use jQuery to toggle a child element when the parent is clicked?

There are three images displayed on a webpage, each accompanied by a list of three events. The desired functionality is that when a user clicks on an event, the corresponding information should be displayed below that event. Below is the HTML structure: & ...

Sending information to a single component among several

I'm developing a custom DownloadButton component in VueJS that features an animation when clicked and stops animating once the download is complete. The DownloadButton will be utilized within a table where it's replicated multiple times. I intend ...

Is the JSON returned by the API server not being properly processed by the RequireJS module, resulting

After extensive research on promises and module creation, I am still unable to understand why my current setup is not functioning properly. My goal is to write a script that takes a username and then fetches user data from a 3rd party API using a separate ...

Guide on updating a table with query parameters in Html Agility Pack using C#

Struggling with parsing this URL using the Html Agility Pack: " The default table that shows up is always based on the closest contract date and the current date. I can parse the entire page without any issues, but when I try to request a different date ...

Creating a CSS grid layout with dual columns to dynamically adjust and accommodate two items in each row

I am attempting to create this layout using CSS grid: https://i.sstatic.net/Ktbnm.png The goal is to have an input and a textarea. The textarea should be of the size of 2 inputs. If there is already a textarea in the previous column, the next column shou ...

Using $app->render() in Slim PHP allows you to specify the relative path to external dependencies

When rendering an actual HTML site that includes external dependencies like JavaScript and CSS using PHP, there may be issues with resolving the dependency paths when using methods such as $app->render("./somewhere/index.html") or simply echoing out the ...

Troubleshooting issues with rowspan in a Datatable

I am currently utilizing jQuery DataTables to display my grid data and implementing the rowspan concept with the rowsGroup option. Initially, it works well by spanning some rows and looking visually pleasing, but eventually, it starts failing. Here are so ...

Adding LocalStorage functionality to buttons in order to switch colors can be done by storing the

I've run into an issue trying to incorporate LocalStorage with the buttons that change colors as themes in JavaScript. I'm new to coding and eager to add this feature to my personal blog. $(document).ready(function () { $(".header--theme-button ...

Improve code efficiency by streamlining a function and using more effective syntax techniques

I've been learning how to condense code with jQuery. Can this script be written in a more concise manner without everything being on one long line? items.push('<li id="' + key + '">' + ' (key: ' + key + ')&apo ...

Issues with Opera Mini Jquery AJAX not loading

I recently created a website optimized for mobile devices, but I'm encountering an issue with AJAX calls specifically on Opera Mini. One particular request involves loading additional content when the user scrolls to the end of the page (70%). $(docu ...

Code remaining stable post-execution of promise

I'm facing a problem with my Node.js application where I'm using promise-mysql and bluebird packages to make calls to a MySQL database. Despite following tutorials and successfully querying the database, I keep encountering a timeout error. The p ...

Is it possible to create an If Statement within a foreach loop on an ASP.Net view page?

I am attempting to showcase 4 columns in a single row, with an opening <div class="row"> tag following every group of 4 data elements and a closing tag </div> at the end. @{ int i = 1; } @{ foreach (var item in ViewBag.Prod) { ...

The horizontal center alignment of text is not working properly in Bootstrap v5.0

I'm currently learning Bootstrap v5.0 and working on creating a practice webpage with it. However, I've encountered an issue where the text is not aligning center horizontally. Despite using align-items-center, the centering is not working as int ...

How to Alphabetize an Array of Strings Containing Numbers using TypeScript and Angular

I'm working with an array that looks like this: arr = ["100 abc", "ad", "5 star", "orange"]; The goal is to first sort the strings without numbers at the beginning, then sort the strings with numbers added at t ...

Struggling to implement CSS for second div onto selected item in the first div

As a beginner in Angular, I am seeking some guidance and examples. In my code, there are two divs. One is created using ng-repeat with an ng-click function to detect the clicked item. The other div below has CSS properties like style="width:100px; float ...

Utilizing CSS for creating dynamic columns within a Bootstrap row

Is there a way to dynamically change the background color of each section in a bootstrap row based on percentages passed through? For example, if I pass in percentages of 30, 40, 20, and 10, the divs should appear in green, red, yellow, and purple respecti ...

What is the process of turning a picture from a menu file into a clickable link?

I have created a menu with some images included, and I want them to be clickable links. However, currently only the text on top of the images acts as a link when hovered over. I would like the entire image to be clickable, not just the text. I believe I ...

What is the process for deactivating a range of dates?

I am trying to prevent users from selecting dates within the range specified by l1 and l2. However, my current method only disables the date 13. var l1 = new Date("2019-07-13"); var l2 = new Date("2019-07-30"); this.flag = 0; this.filter2 = function( ...

What is the method for ensuring that a GreaseMonkey script impacts elements on a page prior to their appearance?

I'm currently working on a project that requires hiding images on a specific website while still displaying the alt text. Initially, I tried to achieve this using Stylish on Firefox and posted the following question: How to force an image's alt ...