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

Sending data to a PHP page to maintain state in an Angular application

Here is my current setup: In a dynamic Angular environment, I have various states connected to PHP pages. These PHP pages rely on specific data variables, typically provided as GET parameters outside of Angular. Now, I am looking for a way to switch to a ...

Obtain the file path relative to the project directory from a Typescript module that has been compiled to JavaScript

My directory structure is as follows: - project |- build |- src |- index.ts |- file.txt The typescript code is compiled to the build directory and executed from there. I am seeking a dependable method to access file.txt from the compiled module without ...

Comparison of Node.js and Express.js APIs for handling responses

Both Node.js and Express.js have their own unique response APIs. Interestingly, there are some similarities between the two, such as: Node.js: response.write(chunk[, encoding][, callback]) Express.js: res.attachment([filename]) res.download(path [, ...

Why does my JavaScript code fail to retrieve input values?

When the button labeled click here is clicked, it will trigger an alert with empty values. I am curious why the alert does not display the values 400 and 400. This code snippet is from test1.php: <script src="https://ajax.googleapis.com/ajax/libs/jqu ...

Guide to displaying numerous points on mapbox by utilizing a for each loop statement

I have a 2D array containing longitudes and latitudes that I need to map using MapBox. The example I found only demonstrates plotting two points, so I attempted to use a for-each loop to iterate through my 2D array and plot all the points. However, I enco ...

Utilizing AJAX to Dynamically Load Content in Bootstrap 5 Modals

Although Bootstrap lacks AJAX content for Modals, I tried to find a workaround without success: This is the modal that should be triggered with just "Loading..." <div class="modal fade" id="edit-pp" data-bs-backdrop="static&quo ...

Is it possible to use Material-UI Link along with react-router-dom Link?

Incorporating these two elements: import Link from '@material-ui/core/Link'; import { Link } from 'react-router-dom'; Is there a method to combine the Material-UI style with the features of react-router-dom? ...

Using indented, multi-line logging in a NodeJS environment can help to

I'm looking for a way to display objects that have been printed with JSON.stringify() in the console, specifically within the context of a Mocha test suite output. While my tests are running, I want the object log lines to be indented further to the ...

Guidelines for redirecting a page after a jQuery ajax call is made?

I'm working on a login form code and facing an issue where, after the statement is true, it doesn't redirect to the home page. Instead, it just displays the home page on my index page. How can I redirect jQuery Ajax to another page after the sta ...

What is the best method for arranging drop-down menu options in alphabetical order?

Is there a way to organize the options alphabetically in the dropdown menu of Material-UI? I understand that arrays can be sorted easily using arr.sort(). However, when I try const options = [...].sort(), I still see unsorted values in the dropdown menu. ...

What causes the error message 'avoid pushing route with duplicate key' when using NavigationStateUtils in React Native?

Within my React Native + Redux project, I have set up a reducer for navigation utilizing NavigationStateUtils: import { PUSH_ROUTE, POP_ROUTE } from '../Constants/ActionTypes' import { NavigationExperimental } from 'react-native' impo ...

How to stop empty numbers in angular.js

My goal is to ensure that an input with a required attribute always has some value, and if left empty, defaults to zero. <input ng-model='someModel' required> I have created the following directive: App.directive('input', fun ...

Insert a gap between the two columns to create some breathing room

Does anyone know how to create spacing between columns in an HTML table without affecting the rows? In my table, each column has a border around it: <table> <tr> <td style="padding:0 15px 0 15px;">hello</td> <td style=" ...

Running a command line tool from a Node.js application: A step-by-step guide

My question pertains to running a command line tool from a node.js application, specifically one called tilemantle. In the documentation for tilemantle, it is suggested to install it globally and run it from the command line. However, I am interested in i ...

Determining WebElement Clickability in Java and Selenium: Beyond the Basics of isDisplayed, isEnabled, and findElement

There is a common method to test if a WebElement is clickable: It typically involves something like this: public static boolean isElementClickable(WebDriver driver, String accessor){ return driver.findElements(By.xpath(accessor)).size() > 0 & ...

Handling Errors with Async-Await in JavaScript: Struggling to Retrieve Error Specifics from Error Objects

Within my Node Express JS web application, there is a specific function chain present where an API function attempts to call a service function and handle any errors that may be thrown from within the service function. Located in FWBDataExtracService.js c ...

I would like to exclude the item within my ng-repeat loop using ng-if

I'm attempting to utilize ng-if within ng-repeat in order to create Accordions. Depending on the condition value, I want certain items to be skipped in the ng-repeat. For example, if item.condition is true, then only display the accordion. The code b ...

Exploring the JSON structure

Struggling to come up with a solution as I am limited by certain restrictions. I need to create a mobile navigation system using a JSON object provided by the proprietary server. The only allowed framework is jQuery 1.12.4, no other frameworks or updated v ...

Unable to employ the executescript method in Selenium with multiple arguments

I am currently working on automating a website to create a list through input values in a text field and setting them by clicking outside the field. Due to slow performance with Internet Explorer, I am using Selenium webdriver with IE. The sendKeys method ...

"Incorporating date and time information into the database

I am attempting to set up an automatic SMS system that sends a reminder 24 hours before our residents' appointments. My challenge lies in extracting the date and time from the datetime row in my MySQL database. While I could create an input field, my ...