What is causing the page to automatically scroll upwards when a gallery thumbnail is clicked on?

Currently encountering some unusual behavior with my photo gallery. Whenever I click on a thumbnail to view an image, not only does the image display but it also causes the page to scroll up. If the gallery is positioned slightly below the top of the screen, it scrolls upwards. Conversely, if it extends beyond the top of the screen, it scrolls downwards until the top of the Gallery section aligns with the screen's top.

I attempted to recreate this issue on codepen: https://codepen.io/dmontesi/pen/VJZeVq. My code consists of SCSS and HTML only.

<!-- Gallery -->
<section class="wrapper">
    <div class="wrapper__gall">
        <ul class="slides">
            <li id="slide1"><img src="https://cdn.pixabay.com/photo/2016/06/24/11/49/architecture-1477103_960_720.jpg" alt="" /></li>
            <li id="slide2"><img src="https://cdn.pixabay.com/photo/2016/06/24/11/48/architecture-1477101_960_720.jpg" alt="" /></li>
            <li id="slide3"><img src="https://cdn.pixabay.com/photo/2016/06/24/11/46/architecture-1477099_960_720.jpg" alt="" /></li>
        </ul>
        <ul class="thumbnails">
            <li>
                <a href="#slide1"><img src="https://cdn.pixabay.com/photo/2016/06/24/11/49/architecture-1477103_960_720.jpg" /></a>
            </li>
            <li>
                <a href="#slide2"><img src="https://cdn.pixabay.com/photo/2016/06/24/11/48/architecture-1477101_960_720.jpg" /></a>
            </li>
            <li>
                <a href="#slide3"><img src="https://cdn.pixabay.com/photo/2016/06/24/11/46/architecture-1477099_960_720.jpg" /></a>
            </li>
        </ul>
    </div>
</section>

The goal is for the gallery to display the next slide without altering the user's position on the screen.

Answer №1

( To view the complete code, visit: Codepen )

Question:

Why does clicking a navigation link scroll to the top of an image? How can this be prevented?

Answer:

When you click on a navigation link, it by default scrolls to the element with the corresponding ID, known as an anchor link.

To prevent this behavior, you can add onclick="event.preventDefault()", but this will disable the use of the CSS :target rule, resulting in the target image not being displayed prominently over other images.

Alternatively, you can utilize JavaScript to fully control the behavior.

  1. Add an onclick handler to your navigation links:
<a href="#slide1"  onclick='navigate(event)'>
  1. Create a JavaScript function called navigate that switches the 'active' class from the current active element to the clicked one:
function navigate(event){
  // Get the currently active element
  var active = event.target.closest(".wrapper").getElementsByClassName("active")[0];
  // Remove the 'active' class from the active element
  if(active) active.classList.remove("active");
  // Get the target element from the link
  var target = document.getElementById(event.target.closest("a").getAttribute("href").replace("#",""));
  // Add the 'active' class to the target
  target.classList.add("active");
  // Prevent the default link behavior
  event.preventDefault();
}
  1. Define a CSS rule for the active image (replacing the li:target selector):
.slides li.active {
  z-index: 3;
}
.slides li:not(.active) {
  z-index: 0;
}

( For detailed code, please refer to: Codepen )

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

Is there a way to identify when a <td> element in a table is modified using JavaScript?

Currently, I am working on a Table where the values in the <td> elements change dynamically based on user input from a form. To achieve this, I am utilizing Tangle for creating a reactive document. I am facing a challenge where I need to detect any n ...

What is the best way to automatically close a modal box after submitting a form?

Currently, I am utilizing the CSS modal box developed by Paul R. Hayes. More information about this can be found here - Within the modal box, I have integrated a form. This form is aimed at an iframe that remains concealed on the same page. My objective i ...

Confirming information in Bootstrap's pop-up modal dialog

Currently, I'm utilizing Bootstrap 2 in my project. One of the challenges I am facing is that within a form, there is a button triggering a bootstrap modal dialog. Inside this dialog, we have a select2 control that needs validation - specifically, it ...

How to achieve striped columns with Bootstrap 4.0 instead of striped rows

Here is how my table currently looks with the implementation in place: https://i.sstatic.net/b7onC.png Since my data is displayed vertically, I am interested in adding stripes to the columns or implementing some CSS hovering effect when the mouse is over ...

Utilizing React JS Styled-Components to Import Images from the Public Directory

I've been attempting to set the image as a background-image from the public folder using styled-components. I've tried the following: import styled from "styled-components"; import Background from 'process.env.PUBLIC_URL + /images/ ...

What steps should be taken to ensure that the onmouseover and onmouseout settings function correctly?

The Problem Currently, I have a setup for an online store where the shopping cart can be viewed by hovering over a div in the navigation menu. In my previous prototype, the relationship between the shoppingTab div and the trolley div allowed the shopping ...

What is the best way to extract the name from JSON data?

I have a list of items in my HTML with data attributes. When a user clicks on one of the items, I want to display or append a list of related suburbs for that selected item in another list. This is being achieved using ajax. <ul id="cities"> <l ...

Chrome does not support top.frames functionality

I have three HTML pages: main.html, page1.html, and page2.html. I am displaying page1.html and page2.html within main.html using the code below. <!DOCTYPE html> <html> <frameset frameborder="1" rows="50%, *"> <frame name="f ...

Troubles with showcasing icons on a website

I need some help with a minor issue that I'm stuck on. I'm trying to display an information icon that, when clicked, opens a pdf. The strange thing is that the icon doesn't show up on the page even though it exists on the server. However, wh ...

How to dynamically modify a list box with JavaScript

I have an index.html file with a select tag containing multiple options for a drop-down: <label for="edu">Education</label> <select id="edu" name="edu"> <option value="0">10th</option&g ...

Challenge with Making Backgrounds Responsive on Android Chrome

I’m facing an issue with the responsive background on Android Chrome. It displays correctly on PC browsers like Safari, Firefox, and Opera, as well as in Firefox on Android. However, I am encountering a problem with Chrome on Android where it doesn’t a ...

Navigate to a different page using a sliding transition

Currently, I am working on a project using jquery-mobile where I need to redirect to another page after clicking on an image with a delay. This is what I have done so far: setTimeout(function(){ window.location.href = "myPage.html"; }, 1000); While t ...

Adjusting Navigation bar size according to the Media Screens/Device Width

Greetings! I am curious to know if it is feasible for my navigation bar to adjust its size according to different screen sizes. For instance, I would like the nav bar to be visible at a specific height on desktops and appear smaller at a different height o ...

Guide to populating a select-option dropdown using CSS

I'm working on creating a dropdown menu in HTML that pulls the options from a CSS file. To accomplish this, I have assigned custom classes to each option and specified the option label in the CSS using the CUSTOM_CLASS::after{content: "";} r ...

Can anyone help me troubleshoot this issue with uploading external JS scripts into my HTML code?

I'm currently facing an issue with my HTML document where the external js file is not loading. Here's a snippet of the HTML: <!DOCTYPE html> <html> <head> <title>...</title> <meta name="viewport" conten ...

Show all information from MySQL tables in an HTML format

I need help with displaying an entire mysql table within an HTML table. I've come across some code that is able to show the fields: <?php $con=mysqli_connect("example.com","peter","abc123","my_db"); // Check connection if(mysqli_connect_e ...

Task: Choose MySQL option and Retrieve JSON data

I have a question regarding implementing a function in a separate module file and calling it within a route to retrieve query data: function getSobre() { return new Promise((resolve, reject) => { db.query(`SELECT * FROM sobre ORDER BY cod ...

Facing challenges when attempting to store data with find() on Internet Explorer

I'm currently immersed in a project that involves fetching data through ajax jQuery. The code I am utilizing is as follows: $.ajax({ dataType : 'html', type: 'POST', url : url, //cache: false, ...

Swap out a term in a sentence with an interactive span element in real-time

I'm struggling with a seemingly simple task, and I feel quite embarrassed that I can't seem to solve it. My goal is to identify words in a string that begin with '@' or '#' and change their color to blue. The string itself com ...

How can I dynamically populate a multiple select box with data from a PHP query and store it in a multidimensional array using jQuery?

I apologize for any language barriers as English is not my first language. My query is as follows, I am looking to implement three multiple select boxes on a single page. How can I retrieve query data before it is executed in PHP? Each loop result will be ...