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

Anchor checkboxes

I am dealing with a large number of checkboxes that are linked to anchors. Whenever a checkbox is clicked, it navigates to the corresponding anchor on the same page. Is there a more efficient way to implement this? With around 50 checkboxes, my current cod ...

Turn off Chrome 69's autofill functionality

I've recently encountered an issue with Chrome's password autofill feature that has been troubling me for a few days now. This problem began when I was using Chrome version 69. After much trial and error, I found a solution by removing the id an ...

Converting an HTML form with empty values into JSON using JavaScript and formatting it

While searching for an answer to my question, I noticed that similar questions have been asked before but none provided the solution I need. My situation involves a basic form with a submit button. <form id="myForm" class="vertically-centered"> ...

Adding a button to the right of a text-field input in Vuetify app

I need advice on the best way to use Vuetify in order to display a button to the right of a text-field (attached). I've checked the main site for information but couldn't find anything related to this specific scenario. <v-row clas ...

How to eliminate ampersands from a string using jQuery or JavaScript

I'm having trouble with a seemingly simple task that I can't seem to find any help for online. My CSS class names include ampersands in them (due to the system I'm using), and I need to remove these using jQuery. For example, I want to chan ...

Display picture on webpage in 10 seconds

Hi, I'm working on a website project and I've run into an issue where I need to use JavaScript, but I haven't mastered it yet. I have a background image slideshow set up where a new image appears every 6 seconds. My idea is to have the sec ...

I have implemented an email validation form in Angular, however, if the validation is not properly handled, the data will still be stored. How

When I enter an email address, for example: if I enter "abc" it shows an alert saying "please enter a valid email". If I leave it blank and try to submit, it shows an alert saying "email required". But when I click register, the data is saved regardless of ...

Issue encountered when concealing page elements followed by revealing them again

My goal is to conceal an id within a page and then reveal it once all the JavaScript has finished loading on the page. The JavaScript I am using to display the content again is: $(document).ready(function() { $("#HomePage")[0].style.visibility = "visib ...

Center the p tag vertically

To ensure the text inside the p tag aligns vertically in the middle, I've set a specific height for the tag. While this works perfectly for single-line text, it shifts to the top of the p tag when there are two lines of text. It's important to k ...

Can you identify the selected item on the menu?

My goal is to highlight the menu item for the current page by adding a "current" class. I've tried several code snippets from this website, but most of them didn't work as expected. The code I'm currently using almost works, but it has a sma ...

Using the `position: sticky` property does not function properly if the HTML element has a height set to

Here is the CSS code I have for the two important items... html, body { background-image: url("../images/background.png"); background-attachment: fixed; height: 100%; } --and-- #navBar { font-family: Cinzel; position: sticky; t ...

guide for interpreting a complex json structure

I'm attempting to extract data from a JSON file that has multiple layers, like the example below. - "petOwner": { "name":"John", "age":31, "pets":[ { "animal":"dog", "name":"Fido" }, ...

Adjust the width to ensure the height is within the bounds of the window screen?

I am currently in the process of developing a responsive website, and my goal is to have the homepage display without any need for scrolling. The layout consists of a 239px tall header, a footer that is 94px tall, and an Owl Carousel that slides through im ...

Begin an unnumbered hierarchical list commencing at 1.2.1

I am trying to create a nested unordered list with specific numbering. My goal is for the list to start at "1.2.1, 1.2.2, etc." Please refer to the attached fiddle for reference. The desired outcome is shown in the following image: https://i.stack.imgur ...

How can we prevent the restoration of size effects in jQuery UI versions 1.9 and above?

After implementing jQuery UI 1.9 or newer, I noticed that the size effect returns to its original state. Below is a snippet of my code: http://jsfiddle.net/mQCxY/ $(function () { $('.circle').click(function () { $(this).effect("size ...

What is the best way to remove headers and footers programmatically in print pages on Safari using JavaScript?

Struggling with eliminating the header and footer on print pages in Safari using JavaScript? While disabling the header and footer manually can be done through print settings in most browsers, my aim is to automate this process with code to ensure that use ...

jQuery will envelop the HTML elements in an inconsequential div

Imagine a website that is visually complex, with various styles and images positioned in different ways. What if we wanted to add a small overlay icon above each image? At first, the solution might seem simple - just use absolute positioning for a span el ...

Switch to display only when selected

When I click on the details link, it will show all information. However, what I actually want is for it to toggle only the specific detail that I clicked on. Check out this example fiddle Here is the JavaScript code: $('.listt ul').hide(); $( ...

Which HTML tags can be activated with JavaScript to be interactive?

I'm currently diving into the world of JavaScript and one of the initial code snippets I've encountered is onclick. So far, I've seen it utilized in form buttons like this: <input type="button" onclick="checkName()" value="Check name" / ...

Empty Firebase currentUser Redirected After Successful Sign In

I have a webpage named index.html which serves as the sign-in page. After a user successfully signs in, I want to redirect them to a new page called home.html, where their email will be displayed. However, I am encountering an issue with getting a null va ...