Using JQuery to eliminate the current div in an image slider

I currently have an image slider that allows users to switch between images. There are two buttons - one adds a new item to the slider, while the other is supposed to remove the current image from the slider, but it doesn't seem to be working properly.

Any suggestions on how I can make sure that the "remove item" button accurately removes the current item from the slider?

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
    showSlides(slideIndex += n);
}
...
};
...

Answer №1

I have made some adjustments to your code in order to eliminate the active slide feature. However, please note that this modification may lead to errors when your list is depleted because the sliding method you are using is not suitable. It is important to keep track of the current slide by setting an index as data-attr and retrieving that index upon button click. In other words, create an index for each slide dynamically, which can be automatically incremented.

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
    showSlides(slideIndex += n);
}

function currentSlide(n) {
    showSlides(slideIndex = n);
}

function showSlides(n) {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    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";
    slides[slideIndex - 1].className += " active";
    slides[slideIndex - 1].id=slideIndex;
    dots[slideIndex - 1].className += " active";
}
$('#RemoveItem').click(function () {
 $(".active").remove();
});
$('#NewsItem').click(function () {
    
    var maindiv = $("<div class='mySlides fade'>")
                 .append($("<div class='numbertext'>4 / 4</div>"))
                 .append($("<img src='4.jpg' style='width:100%;height:650px' />"))
                 .append($("<div class='text'>Caption Four</div>"));

    $('.slideshow-container').append(maindiv);
    $('.footer').append($("<span class='dot' onclick='currentSlide(4)'></span>"));
});
* {box-sizing:border-box}
body {font-family: Verdana,sans-serif;margin:0}
.mySlides {display:none}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

/* Next & previous buttons */
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}
.slideshow-container{
 margin-top:20px;
} 
/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.dot {
  cursor:pointer;
  height: 13px;
  width: 13px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active, .dot:hover {
  background-color: #717171;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .4} 
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .4} 
  to {opacity: 1}
}

/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
  .prev, .next,.text {font-size: 11px}
}
 <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

 <button id="NewsItem">Add Item</button> 
    <button id="RemoveItem">remove Item</button> 

 <div class="slideshow-container">

    <div class="mySlides fade">
        <div class="numbertext">1 / 3</div>
        <img src="1.jpg" style="width:100%" />
        <div class="text">Caption Text</div>
    </div>

    <div class="mySlides fade">
        <div class="numbertext">2 / 3</div>
        <img src="2.jpg" style="width:100%" />
        <div class="text">Caption Two</div>
    </div>

    <div class="mySlides fade">
        <div class="numbertext">3 / 3</div>
        <img src="3.jpg" style="width:100%" /> 
        <div class="text">Caption Three</div>
    </div>
     
     <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
     <a class="next" onclick="plusSlides(1)">&#10095;</a>
    </div>
    <br />

    <div style="text-align:center" class="footer">
        <span class="dot" onclick="currentSlide(1)"></span> 
        <span class="dot" onclick="currentSlide(2)"></span> 
        <span class="dot" onclick="currentSlide(3)"></span> 
    </div>

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

Exclude items from AngularJS watch list

Is there a way to manually run a digest loop on specifically selected watches? Take, for example, the scenario where I need a directive that constantly displays the current time (including seconds), but without triggering the digest loop every second. One ...

what can prevent a React component from re-rendering?

Being a novice in the realm of React, I find myself with a perplexing query. Within my application, I have two distinct components - the parent component named Goals and its child, EditGoal. The Goals component functions to display all goals, while the Edi ...

Utilizing JQuery to Modify XML File Content

Looking to retrieve data from an XML file using jQuery and display it in a textbox? If you want changes made in the textbox to reflect back in the original XML file, there are ways to achieve this. Here is some code that can help: <html><head&g ...

Tips for iterating through nested objects with a for loop

Struggling with validations in an Angular 5 application? If you have a form with name, email, gender, and address grouped under city, state, country using FormGroupname, you might find this code snippet helpful: export class RegistrationComponent implemen ...

Angular8: Adjusting Activity Status After Leaving Page

When performing activities like upload, download, delete, and edit, I display statuses such as 'upload started' or 'upload completed'. This works perfectly when staying on the same page. However, there are instances where a user may nav ...

Utilize the capabilities of the Dropbox Core API in Javascript to effortlessly transfer and store files on

I am currently developing a chrome-extension that has the ability to upload files to the user's Dropbox folder. I have implemented AJAX requests in my code to handle file uploads, and it is working fine for text-based file extensions such as .txt, .js ...

Update the headers of the axios.create instance that is exported by Axios

I have a single api.js file that exports an instance of axios.create() by default: import axios from 'axios' import Cookies from 'js-cookie' const api = axios.create({ baseURL: process.env.VUE_APP_API_URL, timeout: 10000, headers ...

Unable to upload any further verification documents to Stripe Connect bank account in order to activate payouts

Query - Which specific parameters should I use to generate the correct token for updating my Stripe bank account in order to activate payouts? I've attempted to activate payouts for my Stripe bank account by using a test routing and account number (t ...

Ruby Thin Server: An Unexpected ActionView Template Error

Encountering an issue when trying to deploy my project on Amazon Web Services and accessing the domain. ActionView::Template::Error (Command 'java -jar /home/ubuntu/.rvm/gems/ruby-2.1.10@silk/gems/yui-compressor-0.12.0/lib/yui/../yuicompressor-2.4.8 ...

What is the process for creating a selector that links to an element that has been dynamically generated?

Can anyone help me figure out how to create a selector that links to a dynamically created element without using an event on the dynamic element? By dynamically created element, I mean an element that is not present in the HTML at the beginning. I know t ...

I'm interested in knowing how to switch between two functions using Angular

I have developed a grocery list application where each row contains the name of a food item. The layout includes a left column for items that are not needed and a right column for items that are needed. Currently, I am able to change the state by clicking ...

using jquery, how can you send multiple parameters in an ajax request

Hello and welcome! I'm having trouble passing parameters through an ajax URL. I am attempting to send multiple data using the jQuery $.ajax method to my PHP script, but I can only pass a single data item when concatenating multiple data entries toget ...

Understanding the functionality of sessions in CodeIgniter when using AJAX

I am experiencing an issue with the Session in my code. It only works when the page is refreshed. I have a controller called ravi and the view named myview. Here is the code snippet: <?php class Ravi extends CI_Controller { public funct ...

What is the best way to have the sidebar of a webpage slide out over the main body content that is being displayed?

Issue Summary I am experiencing an issue with the positioning of my sidebar, which is initially located 66% offscreen using -translate-x-2/3. The sidebar is meant to be pulled into view onmouseover, however, the main body content remains stuck in place. I ...

Transferring String data between Java and JavaScript using Webview in both directions

I'm currently developing an application that allows two users to communicate via a webview. My goal is to transfer a String variable from JavaScript to Java in order to store it in my SQLite database, and also be able to do the reverse operation as we ...

Ways to fix the issue of an unspecified user error in authjs

Having trouble with creating a web token using passport LocalStrategy and passport-jwt. I keep getting a user undefined error in auth.js ****401 Unauthorized**** (if (!user) { return res.json(401, { error: 'message' });}). How can I fix this issu ...

I am looking to obtain a value through a JavaScript function that sums values upon clicking. The result is satisfactory, but I am seeking a way to limit the value

I only need 2 decimal values, not large ones. Can someone please help me achieve this? <script> $(function() { $("#isum, #num1, #num2, #num3, #rec1, #rec2, #rec3, #difnum1, #difnum2, #difnum3").on("keydown ke ...

Is extracting the title of an image from Flickr?

I have a JavaScript code that randomly pulls single images from Flickr every time the page is refreshed. Now, I want to add a feature where the title of the image is displayed when it's hovered over. However, I've been searching for a solution fo ...

Trouble encountered while refreshing a <div> element using AJAX functionality

My web page is being dynamically generated by scriptA.php. Every 5 minutes, the content of the #WatchContainer div element needs to be updated. This content is created by scriptB.php. I have included scriptB.php in scriptA.php using "include" and a variabl ...

Errors caused by Typescript transpilation only manifest on the production server

During the process of updating my node version and dependencies on both machines, I came across an issue where building my app in production on one machine resulted in an error, while building it on my main machine did not. I found that the errors disappe ...