Tips for seamlessly hiding display images with HTML

In my quest to create a basic image slider, I've managed to achieve it using a combination of JavaScript and HTML. Take a look at the code provided below.

I've included all the necessary codes for clarity's sake. However, the issue arises with the showItemAtIndex function. Whenever it alters the display property of the images, the webpage unexpectedly scrolls back to the top of the image – quite bizarre.

JSFiddle

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<script>

/*
@param carousel_id: the tag id containing the carousel components.
The structure of the carousel container should mimic that of Bootstrap.
*/
var ImageSlider = function(carousel_id)
{

 var parent = this;
 this.selected_item_index = 0;//current index of the visible image (defaulted to the first image)
 this.carousel_container = document.getElementById(carousel_id);//container housing the main slider
 this.carousel_items  = this.carousel_container.getElementsByClassName("carousel-inner")[0].getElementsByClassName("item");
     this.carousel_indicators = this.carousel_container.getElementsByClassName("carousel-indicators")[0].getElementsByTagName("li");

 //listen to click events on the right arrow, allowing users to navigate to the previous image
 this.carousel_container.getElementsByClassName("right carousel-control")[0].addEventListener("click", function(){

      var new_item_index = parent.selected_item_index + 1;
      new_item_index = new_item_index % parent.carousel_items.length;
      showItemAtIndex(new_item_index);


 });


 //listen to click events on the left arrow, enabling users to view the next image
 this.carousel_container.getElementsByClassName("left carousel-control")[0].addEventListener("click", function(){

  var new_item_index = parent.selected_item_index - 1;
      if (new_item_index < 0) {
      new_item_index = new_item_index + parent.carousel_items.length;
  }
      showItemAtIndex(new_item_index);


 });

 /*this function will display the item at the specified itemIndex */
 var showItemAtIndex = function(itemIndex){

 /*
   TODO:
       step1 : update carousel images
       step2 : update carousel-indicators
       step3: update this.selected_item_index
  
 */

 /* now we need to display the newly selected item */
 var carousel_height = parent.carousel_container.height;
 var new_selected_item = parent.carousel_items[itemIndex];
 new_selected_item.style.display = "inline-block";
     
     //step1
 /* first thing we need to hide the current selected items */
 var current_carousel_selected_item = parent.carousel_items[parent.selected_item_index];
 current_carousel_selected_item.style.display = "none";
 //Animate(current_carousel_selected_item,0);

    

     //step2
 /* remove 'active' from all elements */
 var carousel_indicators_length = parent.carousel_indicators.length;
 for(var i = 0 ; i < carousel_indicators_length ; i++ ){
 var monoCarouselIndicator = parent.carousel_indicators[i];
 monoCarouselIndicator.className = "";
 }

 /* add 'active' class to the indicator representing the selected element */
 var selectedIndicatorElement = parent.carousel_indicators[itemIndex];
 selectedIndicatorElement.className = "active";

 //step3
 parent.selected_item_index = itemIndex; 
 


     }


     /* hide all items but leave the selected one (selected = indexed at zero) */
     var carousel_item_length = this.carousel_items.length;
     for(var i = 1; i < carousel_item_length ; i++){
         var monoItem = this.carousel_items[i];
        // monoItem.style.height = "0px";
         monoItem.style.display = "none";
     }
    

}


</script>


<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">

<style>
body {
background: #ececee;
}


</style>

</head>
<body>
<!-- header section -->
<div class="container header" style="height:300px;" >

</div>

<!-- carousel section -->


<div class="container carosel_section" id="carosel_section">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>

<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<div class="item active" style="height: 100%;">
<img style="height: 100%;" class="img-responsive"
src="http://i.dailymail.co.uk/i/pix/2016/03/22/13/32738A6E00000578-3504412-image-a-6_1458654517341.jpg">

</div>
<div class="item" style="height: 100%;">
<img style="height: 100%;" class="img-responsive"
src="http://www.gettyimages.ca/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg">
</div>

<div class="item" style="height: 100%;">
<img style="height: 100%;" class="img-responsive"
src="http://eskipaper.com/images/images-4.jpg">
</div>
</div>

<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" role="button"
data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"
aria-hidden="true"></span> <span class="sr-only">Previous</span>
</a> <a class="right carousel-control" href="#myCarousel"
role="button" data-slide="next"> <span
class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>

<!-- load image slider -->
<script>
new ImageSlider("myCarousel");
</script>

<!-- bottom section section -->
<div class="container header" style="height:300px;" >

</div>

</body>
</html>

Answer №1

The issue lies in the HTML code of the left and right controls. It is necessary to remove href="#myCarousel" for it to function correctly. Once removed, the code should appear like this:

<!-- Left and right controls -->
<a class="left carousel-control" role="button" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" role="button" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
</a>

Below is a functional demonstration:

var ImageSlider = function(carousel_id) {
    var parent = this;
    
    // image index which currently visible. default selection is the first image
    var selected_item_index = 0;
    
    // container containing the main slider
    var carousel_container = document.getElementById(carousel_id);
    var carousel_items = carousel_container
    .getElementsByClassName("carousel-inner")[0]
    .getElementsByClassName("item");
    var carousel_indicators = carousel_container
    .getElementsByClassName("carousel-indicators")[0]
    .getElementsByTagName("li");

    // listen to click events for next, to display previous image
    carousel_container
    .getElementsByClassName("right carousel-control")[0]
    .addEventListener("click", function() {
        var new_item_index = selected_item_index + 1;
        new_item_index = new_item_index % carousel_items.length;
        showItemAtIndex(new_item_index);
    });

    // listen to click events for prev, to display next image
    carousel_container
    .getElementsByClassName("left carousel-control")[0]
    .addEventListener("click", function() {
        var new_item_index = selected_item_index - 1;
        if (new_item_index < 0) {
            new_item_index = new_item_index + carousel_items.length;
        }
        showItemAtIndex(new_item_index);
    });

    // function to display item at given itemIndex
    var showItemAtIndex = function(itemIndex) {

        // now show new selected item
        var carousel_height = carousel_container.height;
        var new_selected_item = carousel_items[itemIndex];
        new_selected_item.style.display = "block";

        // hide current selected items
        var current_carousel_selected_item = carousel_items[selected_item_index];
        current_carousel_selected_item.style.display = "none";

        // update indicators
        var carousel_indicators_length = carousel_indicators.length;
        for (var i = 0; i < carousel_indicators_length; i++) {
            var monoCarouselIndicator = carousel_indicators[i];
            monoCarouselIndicator.className = "";
        }

        var selectedIndicatorElement = carousel_indicators[itemIndex];
        selectedIndicatorElement.className = "active";

        // update selected item index
        selected_item_index = itemIndex;
    }


    // hide all items except the selected one
    var carousel_item_length = carousel_items.length;
    for (var i = 1; i < carousel_item_length; i++) {
        var monoItem = carousel_items[i];
        monoItem.style.display = "none";
    }
}

new ImageSlider("myCarousel");
body {
    background: #ececee;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container header" style="height:300px;"></div>

<div class="container carosel_section" id="carosel_section">
    <div id="myCarousel" class="carousel slide" data-ride="carousel">

        <ol class="carousel-indicators">
            <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
            <li data-target="#myCarousel" data-slide-to="1"></li>
            <li data-target="#myCarousel" data-slide-to="2"></li>
        </ol>

        <div class="carousel-inner" role="listbox">
            <div class="item active" style="height: 100%;">
                <img style="height: 100%;" class="img-responsive" src="http://i.dailymail.co.uk/i/pix/2016/03/22/13/32738A6E00000578-3504412-image-a-6_1458654517341.jpg">
            </div>
            
            <div class="item" style="height: 100%;">
                <img style="height: 100%;" class="img-responsive" src="http://www.gettyimages.ca/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg">
            </div>

            <div class="item" style="height: 100%;">
                <img style="height: 100%;" class="img-responsive"
                    src="http://eskipaper.com/images/images-4.jpg">
            </div>
        </div>

        <a class="left carousel-control" role="button" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
        </a>
        <a class="right carousel-control" role="button" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
        </a>
    </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

"Interactive bootstrap tabs nested within a dropdown menu that automatically close upon being clicked

Hey, I've got a dropdown with tabs inside. When I click on certain tabs within it, they close but the content inside the tabs that I click on changes, so it's functioning properly. However, the issue is that it closes when I want it to stay open ...

Using a CSS nth-child selector to eliminate the bottom margin of the final row

As I work on creating lists that are displayed in columns of two, each .customer-review-container includes a margin-bottom CSS property like this: <div class="col-md-6"> <div class="customer-review-container"> </div> <!-- en ...

Enhancing the appearance of the MUI DatePicker

I'm currently using a DatePicker component from Mui Lab and I'm attempting to customize the appearance of the Calendar component by incorporating some border or background color. Although I've tried utilizing the PaperProps prop for DatePick ...

Adjust the flexslider to transition to a new slide when hovering over the thumbnails

I have a flexslider with thumbnails like this ; https://i.stack.imgur.com/9bfC2.jpg I am looking to change the slide when the user hovers over the thumbnails. How can I achieve this functionality? Here is the jQuery code I am currently using to set up th ...

Other elements are unable to conceal Material UI InputBase

Displayed below is a navigation bar that sticks to the top, followed by rows of InputBase components from material-ui. Despite setting the background color of the nav bar to white, the input always appears above the nav. This strange behavior stopped when ...

Add at the beginning of each row in the text area

I have a small text area on my webpage where I want to add ">>" to the beginning of each line. My initial attempt was to use this code: $("#mytextarea").prepend("EvilHacker001>>"); Unfortunately, this did not produce the desired result. I se ...

Searching for a table row that corresponds to the content of a cell using Python and Selenium

If you need to retrieve the row element from an HTML table where the text in a specific cell matches the string 'Mathematik & Informatik'. Here is the structure of the HTML: <table class="views-table cols-4"> <thead> ...

Bootstrap is unable to function properly without jQuery, throwing an error message that states: "Bootstrap's JavaScript

Attempting to create a Bootstrap interface for a program. Added jQuery 1.11.0 to the <head> tag, however upon launching the web page in a browser, jQuery throws an error: Uncaught Error: Bootstrap's JavaScript requires jQuery Various attempts ...

Exploring the world of XML parsing with iText

I am curious to learn whether it is feasible to modify the font, color, and size while converting HTML to PDF using xmlWorker.parser. Thus far, I have successfully parsed the input as is, but now I am seeking ways to customize the font, size, color, and ...

Bootstrap navigation bar collapsing horizontally instead of vertically

My Navbar is collapsing correctly, but when I click the toggle icon after it's collapsed, the items appear in a horizontal row instead of the intended vertical block. I have checked the code on the Bootstrap 5 example page and tried to replicate it, b ...

Adjust the button's color even after it has been clicked

My goal is to update the button's color when it's clicked. I found some examples that helped me achieve this, but there's an issue - once I click anywhere outside of the button, the CSS class is removed. These buttons are part of a form, and ...

Warning displayed on form input still allows submission

How can I prevent users from inserting certain words in a form on my website? Even though my code detects these words and displays a popup message, the form still submits the data once the user acknowledges the message. The strange behavior has me puzzled. ...

Adding ids dynamically to href elements in Vue.js

As a newcomer, I am facing an issue with dynamically adding an id to my href tag. Below is the code snippet: <div class="col-md-6" v-for="Product in data"> <div class="panel panel-default" > <div class="panel-heading"> ...

Retrieve unique elements from an array obtained from a web API using angular brackets

I've developed a web application using .NET Core 3.1 that interacts with a JSON API, returning data in the format shown below: [ { "partner": "Santander", "tradeDate": "2020-05-23T10:03:12", "isin": "DOL110", "type ...

Modifying the verbiage in the menu based on location

Could anyone provide some assistance or guidance on how to solve a small issue I'm facing? I would like the text in my navigation to change depending on my position on the site (position1, position2 etc.) Here is a fiddle link for reference: http:// ...

Array of radio buttons submitted via form

I am currently working on a PHP exam form where each option has a corresponding radio button to mark if it is correct. I need to store this information in a database. For each option, if the radio button is checked, it sends a post value of 'Yes&apos ...

struggling to rectify an undefined index error on my PHP page

My challenge revolves around accessing the token from an HTML page, where I have an input element containing the token. Whenever I try running this page on a server (WAMP) on Windows 7, I encounter an error stating "undefined index" on the "api_key". How ...

Initiate an "execute.document" command directly from the address bar

While reviewing my old website, I stumbled upon this snippet: <input type="image" id="QuickPass" name="QuickPass" src="/images/QuickPass.gif" alt="Quick Pass" onclick="document.pressed=this.value" value="QuickPass" /> nestled within this form: & ...

Is it possible to shift the "ul" block of the navigation bar to the right without compromising the responsiveness toggle button functionality?

I'm currently using bootstrap NavBar and encountering an issue where moving the ul block to the right is disabling the toggle button responsiveness. <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" c ...

Contact on the go with our handy mobile contact form

Having some difficulties with the contact form on my website. The link to the form is: here. I am currently working on making the form mobile-friendly (the rest of the site scales down using @mobile screen tags in the CSS). The form is stacked, so there ...