The background is failing to update properly - Jquery/Javascript/CSS

Novice Alert: JavaScript challenge!

Right now, I'm working on a complex website project, but for the sake of isolating my issue, I've simplified it down.

View Codepen Example

The main goal is to have 3 images (represented by colors) appear as the user navigates using previous and next buttons. I can't use third-party plugins; I must stick to this logic due to the complexity of the final site.

I'm having trouble figuring out why my JavaScript code isn't functioning properly. I acknowledge that my code could be more efficient, and I'm open to suggestions in that regard, but I can't seem to pinpoint the mistake. Upon testing, you'll notice that either the previous or next button stops working after the first slide transition.

Any assistance would be greatly appreciated.

$(document).ready(function() {
  $('.first').on('click', '.next', function() {
    $('body').addClass("second");
    $('body').removeClass("third");
    $('body').removeClass("first");
    event.preventDefault();
  })
});

$(document).ready(function() {
  $('.first').on('click', '.prev', function() {
    $('body').addClass("third");
    $('body').removeClass("second");
    $('body').removeClass("first");
    event.preventDefault();
  })
});

$(document).ready(function() {
  $('.second').on('click', '.prev', function() {
    $('body').removeClass("third");
    $('body').addClass("first");
    $('body').removeClass("second");
    event.preventDefault();
  })
});

$(document).ready(function() {
  $('.second').on('click', '.next', function() {
    $('body').addClass("third");
    $('body').removeClass("first");
    $('body').removeClass("second");
    event.preventDefault();
  })
});

$(document).ready(function() {
  $('.third').on('click', '.prev', function() {
    $('body').removeClass("first");
    $('body').addClass("second");
    event.preventDefault();
  })
});

$(document).ready(function() {
  $('.third').on('click', '.next', function() {
    $('body').removeClass("second");
    $('body').addClass("first");
    $('body').removeClass("third");
    event.preventDefault();
  })
});
.first {
  background-color: #0ff;
}
.second {
  background-color: #000;
}
.third {
  background-color: #ff0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body class="first">
  <nav class="slides-navigation">
    <a href="#" class="prev">Prev</a>
    <a href="#" class="next">Next</a>
  </nav>
</body>

Answer №1

Take a look at this, it may be useful for you.


$(document).ready(function() {
  $(document).on('click', 'body.first .next', function() {
    event.preventDefault();
    $('body').addClass("second");
    $('body').removeClass("third");
    $('body').removeClass("first");

  })

  $(document).on('click', 'body.first .prev', function() {
    event.preventDefault();
    $('body').addClass("third");
    $('body').removeClass("second");
    $('body').removeClass("first");

  })

  $(document).on('click', 'body.second .prev', function() {

    event.preventDefault();
    $('body').removeClass("third");
    $('body').addClass("first");
    $('body').removeClass("second");

  })


  $(document).on('click', 'body.second .next', function() {
    event.preventDefault();
    $('body').addClass("third");
    $('body').removeClass("first");
    $('body').removeClass("second");

  })

  $(document).on('click', 'body.third .prev', function() {
    event.preventDefault();
    $('body').removeClass("first");
    $('body').addClass("second");

  })

  $(document).on('click', 'body.third  .next', function() {
    event.preventDefault();

    $('body').removeClass("second");
    $('body').addClass("first");
    $('body').removeClass("third");

  })
});

.first {
  background-color: #0ff;
}
.second {
  background-color: #000;
}
.third {
  background-color: #ff0;
}

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body class="first">
  <nav class="slides-navigation">
    <a href="#" class="prev">Prev</a>
    <a href="#" class="next">Next</a>
  </nav>
</body>

Answer №2

Don't overcomplicate things with excessive code for simple tasks.

var numbers = ['first', 'second', 'third'];
var current = 0;

$('.next, .prev').on('click', function(e) {
  // determine which button was clicked and update the current value accordingly
  var offset = $(this).hasClass('prev') ? numbers.length - 1 : 1;
  current = (current + offset) % numbers.length;          // avoid going out of bounds
  $('body').removeClass();
  $('body').addClass(numbers[current]);
})
.first {background-color: #0ff;}
.second {background-color: #000;}
.third {background-color: #ff0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body class="first">
  <nav class="slides-navigation">
    <a href="#" class="prev">Prev</a>
    <a href="#" class="next">Next</a>
  </nav>
</body>


Your code didn't work as expected because you attached event listeners to 6 elements, but only 3 of them existed when the code executed. You were trying to use delegated listeners, but not correctly. To fix this issue, you should target a static parent element first, like the html or document since you're changing body classes. So, something along the lines of:

$(document)...

instead of:

$('body')...

Answer №3

   

 $(function() {
      
    
    $('#slide').on('click','.next',function(){
          if($('body').hasClass("first")){
          $('body').removeClass("first");
              $('body').addClass("second");
              event.preventDefault();
          } else  if($('body').hasClass("second")){
              $('body').removeClass("second");
              $('body').addClass("third");
              event.preventDefault();
          }  else  if($('body').hasClass("third")){
                $('body').removeClass("third");
                $('body').addClass("first");
                event.preventDefault();
           }                                       
       });
    
      
     
      
    
    $('#slide').on('click','.prev',function(){
                if($('body').hasClass("first")){
            $('body').removeClass("first");
                    $('body').addClass("third");
                    event.preventDefault();
                } else  if($('body').hasClass("second")){
                    $('body').removeClass("second");
                    $('body').addClass("first");
                    event.preventDefault();
                }  else  if($('body').hasClass("third")){
            $('body').removeClass("third");
                    $('body').addClass("second");
                    event.preventDefault();
                }                                       
             });
          });
.first {
  background-color: #0ff;
}
.second {
  background-color: #000;
}
.third {
  background-color: #ff0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
     <body id='slide' class="first">
           <nav class="slides-navigation">   
              <a href="#" class="prev">Prev</a>
              <a href="#" class="next">Next</a>
           </nav>
       </body>

Answer №4

Here is a JavaScript code that allows you to dynamically add and remove classes from an array based on button clicks.

JavaScript Code:

$(document).ready(function() {
    var counter = 0;
    var classArr = ["first", "second", "third"];

    $('body').on('click', '.next, .prev', function(event) {
        $(this).hasClass("next") ? counter++ : counter--;
        changeClass();
        event.preventDefault();
    });

    function changeClass(){
        var indexClass = counter % classArr.length;
        indexClass = Math.abs(indexClass);
        $.each(classArr, function(index, value) {
            if (index == indexClass) {
                $('body').addClass(classArr[index]);
            } else {
                $('body').removeClass(classArr[index]);
            }
        });
     }

});

You can view the implementation in this JSFiddle link.

CSS Styles:

.first{
background-color:#0ff;
background-position: center -47px
}
.second{
background-color:#000;
    background-position: center -47px
}
.third{
background-color:#ff0;
background-position: center -47px
}

HTML Structure:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body class="first">
  <nav class="slides-navigation">    
          <a href="#" class="prev">Prev</a>
          <a href="#" class="next">Next</a>
  </nav>
</body>

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

Unable to modify translation values in an existing ngx-translate object

I am facing an issue where I am unable to change the value of an object property within a translation JSON file using ngx translate. Despite attempting to update the value dynamically when receiving data from an API, it seems to remain unchanged. I have t ...

Webpack and Keycloak Integration: Content blocked because of MIME type ("text/html")

I am currently using VueJS for my frontend with Keycloak handling authentication, along with Webpack to bundle my code. Upon the initial application load, if the user is not authenticated, they are redirected to the Keycloak page. During this process, an ...

Angular's eval directive's parameters

Looking for a solution to manage parallax on mobile devices in my HTML template: <div width-watcher> <div parallax-bg parallax-active="!(tablet || mobile)"> ... </div> </div> The width-watcher includes boolean valu ...

Issue with lodash set function: Unable to generate a sub-object with an integer key

Having trouble with setting an object using Lodash's set function, specifically in this format: { '288452': { '57': 'value1', '69': 'value2', '01': 'value3 ...

Send form information using AJAX response

I have successfully implemented a feature where I load an iframe into a div with the id of #output using AJAX. This allows me to play videos on my website. jQuery( document ).ready( function( $ ) { $( '.play_next' ).on('click', fun ...

What is the method to trigger the alt + f4 combination in AngularJS when a button is clicked?

Is there a way to manually close the current tab in AngularJS by simulating Alt+F4 key press? $scope.cancel = function (event) { var keycode = event.keycode; }; <button class="btn btn-outline-primary" ng-click="cancel($event);">OK</button&g ...

The functionality of event.preventDefault is not working as expected

Using AJAX, I successfully loaded data into a div. <div id="container"> <a class="hello" href="abc.php">hello</a> // content loaded via AJAX <div> Currently, I am trying to implement jQuery: <script type="text/javascript" ch ...

Implementing a global configuration for smart-table in AngularJS

In order to display buttons, I have implemented the following code snippet with a template: <ul class="pagination"> <li><div class="pageNumberClass" st-pagination="" st-template="/AppScripts/vendor/template/pagination.custom.html" st- ...

Discovering the method to extract a specific section from a lengthy string

Looking to extract phone numbers from an HTML source code using PHP? Each phone number in the code starts with 'phone=' and ends with %. For example, consider the following sample HTML code: b2e1d163b0b4dc6ebfa5&amp;t=s&amp;phone=9535503 ...

The div element on my website spans the entire width, yet it appears slightly narrower than the body

My website features a scrolling div element that spans 100% of the screen, but I am encountering an issue with slight horizontal scrolling and the background image extending beyond the visible area. I am striving to adjust the width of the div so that it ...

What is the best approach for retrieving Google API responses - accessing them directly from the frontend or routing through the backend first?

Currently, I am in search of the optimal location to make Google API requests. Given that Google Maps is utilized in the front end, we have the option to directly call the distance API service from there. However, we also have the choice to access these se ...

What is the benefit of writing in this manner?

Additional Module Insights available on redirectmodulenotes.com. Here is an example of how a module can be written: define(["require", "./another/name"], function(require) { var mod = require("./another/name"); }); Alternatively: define(function(req ...

How can I turn off the animation for a q-select (quasar select input)?

I'm just starting out with Quasar and I'm looking to keep the animation/class change of a q-select (Quasar input select) disabled. Essentially, I want the text to remain static like in this image: https://i.stack.imgur.com/d5O5s.png, instead of c ...

Tips for creating gaps between list items in a collapsible navbar

I am attempting to add spacing between the li items in my collapsible navbar However, the issue arises when I slightly minimize the browser window, causing the navbar to collapse incorrectly. See image below: https://i.sstatic.net/TdKb4.png Below is t ...

Form in HTML with Automatic Multiplication Functionality in pure JavaScript

I'm struggling with integrating a simplified HTML form with JavaScript to dynamically adjust and multiply the entered amount by 100 before sending it via the GET method to a specific endpoint. Below is the HTML form: <body> <form method= ...

View content from an external file within an iframe

My goal is to showcase a text file within an iframe that updates automatically every second. To achieve this, I have created a simple function: function refresh() { $("#derek").attr('src', $("#derek").attr('src')); }; The automati ...

What is the simplest way to display an HTTP response in an alert window?

Struggling to display the JSON response using JavaScript's window.alert or alert. As a non-native JS coder, I apologize for my lack of experience. Here are a few attempts I've made based on online examples. My objective is to showcase the JSON r ...

Guide on how to use Vue's watch feature to monitor a particular property within an array

I am interested in observing the "clientFilter" within an array TableProduit: [ { nr_commande: 0, date_creation: "", id_delegue: "1", clientFilter: "" } ], ...

How can I make a div take up the entire height of its parent column using Bootstrap?

I need the div with the red border to match the height of the green div on the right. I'm using Bootstrap 4 for this layout! I've experimented with display: flex and flex-grow, and also tried placing the border on the column (which achieves the ...

Organize your list with a single click using jQuery plunge

I am trying to organize a group of list items based on a specific date. Below is the code I have written for this task: Please review the code snippet provided below. $(document).on('change','#exampleSelect',function(){ var filt ...