What is the best way to toggle the visibility of a background image within a carousel?

As a beginner in j-query, I am struggling with creating a slider image carousel using a full background image. Most of the solutions I found online require a fixed width for all pictures to slide smoothly. However, I believe there might be a way to use an array or index function in a loop to toggle visibility. Transitioning from basic JavaScript to jQuery has been challenging for me. Any tips or advice would be greatly appreciated. Below is the code snippet I'm currently working on. Thank you!

http://codepen.io/kevk87/pen/PPNPmg

    <main>

<div class="container">
<ul>  
  <li class="one"> 
  </li>
  <li class="two"> </li>
  <li class="three"></li>
  <li class="four"></li>
</ul>

  <div class="nav">
      <ul >
       <li class="first active"> </li>
      <li class="second"> </li>
       <li class="third"> </li>
      <li class="fourth"> </li>
      </ul>
  </div>
</div>
</ul>
</main>

CSS

*{
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}



ul {
  list-style:none;
  height:100%;
}
main, html, body{
  height:100%;
}

.container {
  height:100%;
  postion:relative;

}

.one {  
   height:100%;   background:url(http://hamderser.dk/blog/images/clairvoyant/clairvoyant-nature-nature2.jpg) center center no-repeat fixed; 
   background-size:cover;

}  

.two {
  background: url(http://www.atilaminates.com/wp-content/uploads/2015/05/nature-wlk.jpeg) center center no-repeat fixed;
  height:100%; 
}
.three {
  background: url(http://php.drishinfo.com/photostudioone/wp-content/uploads/2014/11/nature-wallpaper-hd-1920x1080.jpg) center center no-repeat fixed;
  height:100%; 
}
.four {
  background: url(http://www.projecthappyhearts.com/wp-content/uploads/2015/04/green-nature-dual-monitor-other.jpg) center center no-repeat fixed;
  height:100%; 
}


.nav ul li {
  width:20px;
  background-color:white;
  height:20px;
  display:inline-block;
  margin-right:20px; 
}
.nav ul li:last-child {
  margin-right:0px;
}

.nav {
  position: absolute;
  bottom:100px;
  left:50%;
  transform:translate(-50%,-50%);
}

.nav ul .active{
  background-color:black;
}

.two, .three, .four {
  display:none;
}

Javascript

//change active class

    $('.nav ul').click(function(){
  $(this).removeClass('active');  
    $(this).addClass('active');
});

//Click handlers to change image and active class


$('.first').click(function(){
    $('.one').show();
  $('.two').hide();
  $('.three').hide();
  $('.four').hide();
});


$('.second').click(function(){
    $('.two').show();
  $('.one').hide();
  $('.three').hide();
  $('.four').hide();
});

$('.third').click(function(){
    $('.three').show();
  $('.one').hide();
  $('.two').hide();
  $('.four').hide();
});

$('.fourth').click(function(){
    $('.four').show();
  $('.one').hide();
  $('.three').hide();
  $('.two').hide();
});

Answer №1

Check out this simplified version using jQuery functions:

http://jsfiddle.net/7erakxad/

<main>
<div class="container">
<ul>  
  <li class="one"></li>
  <li class="two"></li>
  <li class="three"></li>
  <li class="four"></li>
</ul>

  <div class="nav">
      <ul>
       <li class="first active"></li>
      <li class="second"></li>
       <li class="third"></li>
      <li class="fourth"></li>
      </ul>
  </div>
</div>
</ul>
</main>

<script>
$(".nav > ul li").click(function () {
        $('.nav > ul li').each(function () {
            $(this).removeClass('active');       
        });
        var index = $(this).index();
        $(".container > ul").find("li").each(function (i2) {
            if (index == $(this).index())
                $(this).show();
            else
                $(this).hide();
        });
        $(this).addClass('active');
    });
</script>

<style>
*{
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

ul {
  list-style:none;
  height:100%;
}
main, html, body{
  height:100%;
}

.container {
  height:100%;
  position:relative;
}

.one {  
   height:100%;   
   background:url(http://hamderser.dk/blog/images/clairvoyant/clairvoyant-nature-nature2.jpg) center center no-repeat fixed; 
   background-size:cover;
}  

.two {
  background: url(http://www.atilaminates.com/wp-content/uploads/2015/05/nature-wlk.jpeg) center center no-repeat fixed;
  height:100%; 
}
.three {
  background: url(http://php.drishinfo.com/photostudioone/wp-content/uploads/2014/11/nature-wallpaper-hd-1920x1080.jpg) center center no-repeat fixed;
  height:100%; 
}
.four {
  background: url(http://www.projecthappyhearts.com/wp-content/uploads/2015/04/green-nature-dual-monitor-other.jpg) center center no-repeat fixed;
  height:100%; 
}

.nav ul li {
  width:20px;
  background-color:white;
  height:20px;
  display:inline-block;
  margin-right:20px; 
}
.nav ul li:last-child {
  margin-right:0px;
}

.nav {
  position: absolute;
  bottom:100px;
  left:50%;
  transform:translate(-50%,-50%);
}

.nav ul .active{
  background-color:black;
}

.two, .three, .four {
  display:none;
}
  </style>

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

Search for a specific folder and retrieve its file path

Is there a way for me to include an export button on my webpage that will allow users to save a file directly to their computer? How can I prompt the user to choose where they want to save the file? The button should open an explore/browse window so the ...

Unable to extract data from my xml reply

I've been trying to extract a value from an XML response, but I keep getting null. What am I missing? $.ajax({ method: "GET", url: "fphub01-prd.tc.workstreaminc.com/hub/custLookup/", data: { emailAddress: email } }).done(function(msg) { ...

Issue with jQuery click event not firing on multiple buttons with identical names

These are the two buttons that appear multiple times but do not function: <button name='btnEditar' class='btn btn-outline-success me-4' data-bs-toggle='modal' data-bs-target='#staticBackdrop'><i class=&a ...

Disregard the Field File when utilizing jQuery validation

I have created a form with jQuery validation, but I am facing an issue where the file upload field is showing a message "enter no more than 3 characters." I believe this problem is due to the maxlength="3" property in the file field. How can I remove the ...

The issue with element.style.backgroundColor not functioning properly within WordPress

Struggling to make the background of a button change upon hover? I've got the code, but it seems to be working everywhere except in WordPress. Check out the code that should be working here: https://jsfiddle.net/TopoX84/3oqgmjb0/ Want to see it not ...

Press the button to duplicate the cell column separated by commas

In my HTML table, there is a specific column filled with container numbers that I want to copy to the clipboard when a button is clicked. The column has the class ".container" Here is the code I have been working on. HTML: <button onclick="copyToC ...

updating the datepicker input maxDate property to the current date

I am facing a challenge with setting the input date using datepicker. I want to require the user to choose a date less than the current date. Below is the code snippet: <div class="tab-pane fade active in" id="evenement"> < ...

AngularJS - Enhance table row visibility with ngRepeat for targeted highlighting

Example Data <table class="table table-condensed table-striped table-responsive"> <thead> <tr> <th>Sender</th> <th>Subject</th> <th>Received</th> <th>Actions&l ...

Effortlessly move and place items across different browser windows or tabs

Created a code snippet for enabling drag and drop functionality of elements within the same window, which is working smoothly. var currentDragElement = null; var draggableElements = document.querySelectorAll('[draggable="true"]'); [].forEach ...

What is the best way to add padding to both the TextField input and label components within Material UI?

Recently, I've integrated Material UI into my project and set up a TextField for a form field. However, I'm facing an issue where applying padding to the input field doesn't affect the label as well. <TextField sx={{ display: &q ...

"Ajax has the ability to alter the vertical scroll position

I have a quick query for you. Can anyone assist me in understanding why the page scroll resets to the top after an Ajax request? I suspect it has something to do with JQuery. There isn't much information available online, so I'm reaching out for ...

Adjusting the dimensions of the image carousel

Here is my code for an Image carousel: <div class="container"> <div class="row"> <div class="col-md-12 col-md-offset-0"> <div id="imageCarousel" class="carousel slide" data-interval="4000" data ...

What is the best method for securing my API key within the script.js file while utilizing dotenv?

My goal is to conceal my API key using dotenv. Interestingly, when I replace require('dotenv').config(); with my actual API key in the code as apiKey: process.env.API_KEY, it works fine despite not using process.env.API_KEY. I made sure to inst ...

Sending an ajax request to submit the results of jQuery.each loop

$(".submitinfo").each(function() { // Using ID as POST name and value as POST value }); // Sending the data using ajax request $.ajax({ url: 'submit.php', traditional: true, data: { 'submit':'true', 'age&a ...

iOS creates dynamic images with artifacts that appear on a generated and animated canvas

I am currently developing an HTML5 web application for WeChat, compatible with both iOS and Android devices, using only pure JavaScript without any third-party libraries like jQuery. The main feature of my app involves creating visually appealing animation ...

The jQuery DataTable is repeatedly triggering when attempting to conceal columns

Update Here is an additional example, consisting of just a few lines of code... triggering the alert twice! $(document).ready( function () { var x = $('#example').dataTable( { fnRowCallback: function( nRow, aData ...

Having trouble interpreting the response using jQuery

Upon running my PHP script, I am receiving the following response. PHP: <?php $con = mysqli_connect("localhost","root","pass","products"); if(mysqli_connect_errno()) { echo "Failed to connect database, please check with your administrator. Error ...

"What is the best way to send back multiple responses to an AJAX request in a Struts action class

Looking for some guidance on handling responses in an Ajax call from a Struts (1.3.10) action class. I've been using the PrintWriter class to send responses back to the client's browser, and while it works sometimes, there are instances where the ...

Modify flex direction to column in response to changes in height of another div or when its content wraps

I am currently utilizing React MUI V5 and I am looking to modify the flex direction of a div from row to column when a preceding div changes in height or wraps. Below is a basic example of what I have implemented using plain HTML/CSS, but I am uncertain i ...

Both radio buttons are being chosen simultaneously

<div class="container"> <div class="row"> <form> <div class="form-group"> <label>username</label> <br /> <input type="text" class=" ...