Using Javascript to display the next div when a button is clicked

My goal is to create a JavaScript functionality where clicking on a button reveals the next div, followed by subsequent ones. Essentially, it's a 'next' button with the option for a 'previous' button as well.

I've exhausted all my options and can't seem to crack the solution. Any advice or assistance would be greatly appreciated, thank you!

If anyone can offer some help, please?

<div id="wrapper">
    <div class="featured">
      <input id="button-next" type="button" value="next"/>
      <img src="photos/bookcover/Alluredbyyou.jpg" alt="" srcset="">
      <p>ALLURED BY YOU</p>
      <span>Lorem text part 1</span>
    </div>
    <div class="featured2">
      <input id="button-next" type="button" value="next"/>
      <img src="photos/bookcover/Notyourmarrysue.jpg" alt="" srcset="">
      <p>Rebecca Frost</p>
      <span>Lorem text part 2</span>
    </div>  
  </div>

  <script>
$(document).on('click','#button-next', function() {
     $('.featured').removeClass('featured2').next('.featured').addClass('active');
});

</script>
.featured, .featured2 {
  float: left;
  margin-left: 16%;
  margin-top: 4%;
  width: 980px;
  height: 450px;
  background-color: #CFD0CD;

}
.featured img, .featured2 img {
  width: 230px;
  height: 360px;
  margin-top:4%;
  margin-left: 5%;
  float: left;

}
.featured p, .featured2 p{
  float: right;
  margin-top: 5%;
  margin-bottom: 0%;
  margin-right: 51%;
  width: 18%;
  
  font-size: 20px;
  font-family:'poppins';
  text-align: left;

}
.featured span, .featured2 span {
  float: right;
  margin-top: 0%;
  margin-right: 4%;
  width: 65%;

  font-size: 18px;
  font-family: Arial, Helvetica, sans-serif;

    height: 75%;
  text-align: left;
  word-wrap: break-word;
  word-break:normal;
  line-height: 30px;
  white-space: inherit;

}
#button-next{
    color: #000000;
    float: right;
    font-size: 19px;
    border: 3px solid #000000;
    padding: 5px 50px;
    margin-right: 0%;
    margin-top: 0%;
    letter-spacing: 1px;
    cursor: pointer;
    transform: scale(1.0);
    transition: ease-in-out 0.5s;

  }
  #button-next:hover {
    transform: scale(0.9);
    transition: ease-in-out 0.5s;
  }

Answer №1

Here's a Vanilla JavaScript solution that handles scrolling through slide items:

const scrollButtons = document.querySelectorAll('.slide-btn')
const slideItems = Array.apply(
    null,
  document.querySelectorAll('.slide-item')
)

const getActiveIndex = () => slideItems.findIndex(item => {
    return item.classList.contains('active')
})

scrollButtons.forEach(btn => {
    btn.addEventListener('click', ({ target }) => {
    const activeIndex = getActiveIndex()
    slideItems[activeIndex].classList.remove('active')

    let newActiveIndex
    if (target.id === 'previous') {
      newActiveIndex = activeIndex === 0 ? slideItems.length - 1 : activeIndex - 1
    } else {
      newActiveIndex = activeIndex === slideItems.length - 1 ? 0 : activeIndex + 1
    }

    slideItems[newActiveIndex].classList.add('active')
  })
})
.featured, .featured2 {
  float: left;
  margin-left: 16%;
  margin-top: 4%;
  width: 980px;
  height: 450px;
  background-color: #CFD0CD;

}
.featured img, .featured2 img {
  width: 230px;
  height: 360px;
  margin-top:4%;
  margin-left: 5%;
  float: left;

}
.featured p, .featured2 p{
  float: right;
  margin-top: 5%;
  margin-bottom: 0%;
  margin-right: 51%;
  width: 18%;
  
  font-size: 20px;
  font-family:'poppins';
  text-align: left;

}

/* Other CSS rules omitted for brevity */

#wrapper div:not(.active) {
  display: none;
}

.slide-btn {
    color: #000000;
    float: right;
    font-size: 19px;
    /* Additional styling properties */
  }
  
<div id="wrapper">
    <input class="slide-btn" id="previous" type="button" value="previous"/>
    <input class="slide-btn" id="next" type="button" value="next"/>
    <div class="featured slide-item active">
      <img src="photos/bookcover/Alluredbyyou.jpg" alt="" srcset="">
      <p>ALLURED BY YOU</p>
      <span>Lorem text part 1</span>
    </div>
    <div class="featured2 slide-item">
      <img src="photos/bookcover/Notyourmarrysue.jpg" alt="" srcset="">
      <p>Rebecca Frost</p>
      <span>Lorem text part 2</span>
    </div>  
  </div>

Answer №2

To keep track of your position in the slideshow, it's important to maintain an id variable.

One way to do this is by adding ids to your featured items using data attributes, and then creating a function that sets an initial id value of 1 and returns a new function to act as the listener.

With this setup, you can easily show/hide the relevant featured sections based on the id, and also enable/disable buttons (now located separately) accordingly.

// Initialize id and set up event handler for button clicks
$(document).on('click', 'button', handleClick());

function handleClick() {
  let id = 1;
  const items = $('.featured').length;

  function toggleFeatured(id) {
    $(`.featured[data-id=${id}]`).toggle('show');
  }

  function updateButtons(id) {
    $('button').prop('disabled', false);
    if (id === 1) {
      $('.previous').prop('disabled', true);
    }
    if (id === items) {
      $('.next').prop('disabled', true);
    }
  }

  return function() {
    const cl = $(this).attr('class');

    toggleFeatured(id);

    if (cl === 'previous' && id > 1) --id;
    if (cl === 'next' && id < items) ++id;

    toggleFeatured(id);
    updateButtons(id);
  }
}
.featured { display: none; }
.show { display: block; }
.buttons { margin-bottom: 1em; }
button:hover { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="buttons">
  <button class="previous" type="button" disabled>Previous</button>
  <button class="next" type="button">Next</button>
</div>

<div id="wrapper">
  <div data-id="1" class="featured show">
    <img src="https://dummyimage.com/200x100/000/fff">
    <p>ALLURED BY YOU</p>
    <span>Lorem text part 1</span>
  </div>
  <div data-id="2" class="featured">
    <img src="https://dummyimage.com/200x100/cf5fcf/000000">
    <p>Rebecca Frost</p>
    <span>Lorem text part 2</span>
  </div>
  <div data-id="3" class="featured">
    <img src="https://dummyimage.com/200x100/cf815f/000000">
    <p>Bob Marley</p>
    <span>Lorem text part 3</span>
  </div>
</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

Selecting a Default Option in Dropdown Menu: A Step-by-Step Guide

Hey there! I'm facing an issue with setting a default selection on my dropdown due to what seems to be interference from Angular. Below is the code snippet I've been using: <select class="form-control" data-ng-model="timePeriod" data-ng-chang ...

JavaScript Node.js is the perfect tool for organizing and arranging nested arrays. With its

My challenge involves dealing with an array that outputs multiple nested arrays. If certain codes match, they are placed in the same nested array. How can I separate them? For instance, consider this example of my array: [ [ [ '0011', 6, 96, &apo ...

Dividing an AngularJS module across multiple iFrames on a single webpage

Currently, I am working on a web application that consists of 1 module, 5 pages, and 5 controllers. Each HTML page declares the same ng-app. These pages are loaded within widgets on a web portal, meaning each page is loaded within an iFrame in the portal. ...

Eliminate the keyword in the $http.get request for the JSON data

As a newcomer to Angular and JSON calls, I must admit that I am still learning the ropes. My current task involves making a $http.get call to retrieve data from a JSON object. Here is an example of what the JSON object looks like: [{ path: "site:imag ...

The structure of the figure tag for HTML5 validation

Could you please confirm if the Figure tag is correctly used in the html structure? Regarding html5 validation, can I use this structure? <a href="#"> <figure> <img src="" class="img-responsive" alt=""> <figcaption> ...

Ways to implement a backup plan when making multiple requests using Axios?

Within my application, a comment has the ability to serve as a parent and have various child comments associated with it. When I initiate the deletion of a parent comment, I verify the existence of any child comments. If children are present, I proceed to ...

Issue with Camera inversion not functioning properly in THREE.js with 1 Renderer and 2 Viewports

Check out this JSFiddle example In my project, I have a single scene with two cameras. Each camera is assigned to its viewport, and both viewports are placed side by side on the same renderer object. My goal is to have the second camera display a mirrore ...

Problem with Material UI Checkbox failing to switch states

I'm a bit confused about the functionality of my checkbox in Material UI. The documentation makes it seem simple, but I'm struggling to get my checkbox to toggle on or off after creating the component. const createCheckBox = (row, checkBoxStatus, ...

"All my online spaces are chaotic and cluttered beyond belief, overflowing with content in high-definition

One issue that frequently arises for me when developing websites is related to media queries and resolution. I have utilized the following code using a max-width of 1920px: @media only screen and (max-width : 1920px) {} However, I am facing challenges in ...

Style your Checkbox Button with the Checkbox component from Element Plus

Currently, I am utilizing Vue 3 along with the Element Plus library. My goal is to modify the hover, active, and select colors of the Checkbox Button that I have implemented. Unfortunately, my attempts to do so have not been successful. I essentially copie ...

Automatically determining the optimal quality from various sources tailored to the individual user - jwplayer

Check out the code snippet below: var playerInstance = jwplayer("mySingleVideoWrapper").setup({ image: getCurrentPosterSrc, sources: [ { file: 'file-360.mp4', label: "360p" ...

Achieving a dynamic "Picture Presentation" feature with JavaScript/jQuery

Currently, I am in the process of developing a website that will serve as a presentation. My plan is to create a slideshow effect using JavaScript. While I have implemented some functions, I must admit that it is not very organized at the moment. The main ...

Display Page Separation with JavaScript

I am working on a project where I have created payslips using Bootstrap through PHP. To maintain organization, I am looking to create a new page after every 6 payslips. Below is the code snippet that I am using to generate the payslips: foreach($results a ...

Modify a single parameter of an element in a Map

Imagine I have a map data type exampleMap: Map<string, any> The key in the map is always a string, and the corresponding value is an object. This object might look like this: { name: 'sampleName', age: 30} Now, let's say the user se ...

I am interested in consolidating multiple websites into a single HTML file

Is it possible to combine multiple HTML websites into a single file? ...

Display a dropdown menu when the value of another dropdown is changed using .NET 2.0

I have a dropdown selection that I would like to trigger another dropdown to display based on the selected index change. How can I achieve this using the onchange function in JavaScript? I am working on an older project using .NET 2.0, so I am unable to ...

What is the best way to reset an event back to its original state once it has been clicked on again

As a newcomer to web development, I'm currently working on creating my own portfolio website. One of the features I am trying to implement is triangle bullet points that can change direction when clicked - kind of like an arrow. My idea is for them to ...

What is the process for obtaining a new token in a Linnworks embedded application?

I decided to share my issue on this platform since the support from Linnworks is virtually non-existent. My dilemma involves a private embedded app created within Linnworks that showcases orders in spreadsheet format. The app, constructed using Vue.js and ...

Using a restricted set of special characters in a jQuery regular expression

My requirement is to only allow alphanumeric data along with the following special characters: ' (single quote) - (hyphen) . (dot) single space I attempted this approach: var userinput = $(this).val(); var pattern = [A-Za-z0-9_~\-!@#\$% ...

Exploring the power of Firebase with Vue Js lifecycle methods

I am attempting to retrieve data from a specific user in Firebase and push that data into designated input fields. The path in Firebase is located here: var query = db.ref('Clients/'+ clientName +'/form/'); I retrieve the data in the ...