What can I do to prevent an anchor link from automatically scrolling to a different section of the page?

I've been attempting to prevent a page from scrolling after selecting an anchor link.

Currently, the page layout includes a larger version of an image appearing in full view on the right panel after clicking on an image in the left panel (with text underneath). This specific look is required for the page. I initially thought using anchors would be the best approach, but I am open to other suggestions.

https://i.sstatic.net/Oeoit.png

I tried using

I have also experimented with various JavaScript methods such as e.preventDefault(), e.stopPropagation(), and return false. However, using return false simply disables the link entirely.

Here is an example of a thumbnail image button with an anchor link placed within a div that has a scrollbar set to overflow: scroll, alongside similar thumbnail images:


              <div class="col-lg-6 col-md-4 col-6">
                  <a href="#alexandru-zdrobau-200768-unsplash" class="d-block mb-4 h-100">
                        <img class="img-fluid img-thumbnail" src="Fashwell/ImagesFashwell/alexandru-zdrobau-200768-unsplash.jpg" alt="">
                  </a>
              </div>

And here is an image containing an anchor, also surrounded by a div with a scrollbar among other images:


<div class="output" id="alexandru-zdrobau-200768-unsplash">
                <h1>
                  Alexandru Zdrobau
                </h1>
                <img class="img_output" src="Fashwell/ImagesFashwell/alexandru-zdrobau-200768-unsplashBOX.jpg">
              </div>

            .....

              <li style="color:green">
                    <span style="color:green">
                      Category: Jumpers &amp; Cardigans.
                      <a href="https://www.zalando.co.uk/aaiko-trilly-jumper-aa321i02m-c11.html" style="color:green" target="_blank">
                        Best match: Aaiko Trilly Jumper
                      </a>
                    </span>
              </li>
         ....

Find below some JavaScript attempts to stop the scrolling:


$("a[href^='#']").click(function(e){
     e.stop();
});


$('.d-block mb-4 h-100').click(function(event) {

    event.preventDefault();

    return false;

});


$(".d-block mb-4 h-100").click(function (event) {
  event.stopPropagation()
})

Any suggestions or ideas? Thank you!

Answer №1

One approach is to surround the gallery position with HTML anchors so that when a user clicks, the browser jumps to that location:

<a id="alexandru-zdrobau-200768-unsplash"></a>

Create all the necessary anchors in this manner. This way, the browser will smoothly navigate to the anchor's position without affecting the gallery JavaScript code.

Another option involves modifying the gallery's code to recognize the URL hash (anchor in the URL) and replacing links with href="javascript:thatfunction('anchor')". Please provide details about the code or gallery you are using for further guidance on this method.

If you prefer an event-controller solution as proposed, ensure that the click events controllers you defined are actually being called. If not, there may be no elements matching the jQuery selectors during setup.

To address this issue, you can:

  • Delay your event controller setup (not ideal but necessary sometimes)...
  • Implement a global body event controller to determine which events should be prevented by analyzing the event.target property, which identifies the DOM element triggering the event. Check if it's the "a" tag or its parent element (to handle cases where children trigger the event). If this doesn't work, consider using mousedown/touch events instead.

Answer №2

Consider Using href="JavaScript:void(0)" Over href="#"

As an illustration :

<a href="JavaScript:void(0);">Click Here!</a>

Answer №3

Just wanted to share that I was able to solve the problem I was experiencing. Originally, I was utilizing the scrollIntoView() function in my JavaScript code to display images in the right-hand box. However, after switching to scrollToTop() instead, the unexpected scrolling of the entire page when clicking on an image in the left panel ceased.

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 send a multi-dimensional array using jQuery ajax?

I am encountering an issue with posting an array as a JavaScript variable {{0,0},{1,1},{2,2}} using JSON.Stringify. Whenever I try to post it, I receive an internal server error 500. Can someone please advise on how I can successfully post and utilize this ...

JavaScript button mouse enter

There seems to be an issue with this code. The button is not functioning properly after hovering over it, even though it was copied from the instructional website where it works fine. <html> <head> <title>Button Magic</t ...

When elements are arranged side by side without using floats, the alignment at the top is not correct

I am having trouble aligning multiple divs next to each other using inline-flex. They are not lining up properly on top (refer to the screenshot). Interestingly, if I remove the svg, the divs align correctly. ...

Counting checkboxes in jQuery version 1.9

I recently upgraded my website from jQuery 1.6 to jQuery 1.9.1, and now some of my old code is not working as expected. Specifically, I have a piece of code that handles checkboxes in table rows, allowing only up to 5 checkboxes to be active at once and di ...

The .AppendChild() method does not appear to be working as expected following the completion of

Encountering a peculiar problem here. The scripts run smoothly, but the content doesn't display on screen until I "inspect element" and then close the inspector window or zoom in/out. It's not an issue with the "display" CSS property because even ...

The dropdown feature on my theme seems to be malfunctioning on Wordpress

I'm having trouble figuring out what I'm doing wrong. The dropdown navigation works fine with the default Wordpress twentyeleven theme, but when I switch to my custom theme, the dropdown stops appearing. Here is the code I'm using: <div ...

Utilize JSON data fetched from a URL to dynamically populate an HTML content

There is a JSON file located at a URL that looks like this: [{"tier":"SILVER","leagueName":"Tryndamere's Wizards","queueType":"RANKED_SOLO_5x5","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":18,"wins":411,"losses":430,"rank" ...

Guide on extracting the ID within a for loop and incorporating it into a Vue.js function

In order to make an API request, I need to retrieve the id. However, whenever I try to include <a v-on:click="showRecipe({{inf.Id}})">Recipe</a> in my code, the entire page crashes. Removing this line resolves the issue. How can I pass the id ...

Regularly fetching images from PHP page

Recently, I encountered a challenge with a PHP page that retrieves arguments from the URL to generate an image. The image type (png, gif, etc.) is unknown. Typically, the page is used to embed the image in a standard HTML page like so: <img src="page.p ...

Tips on Handling Multiple Versions of jQuery

I'm seeking your guidance on a particular issue at hand. I am part of the development team for a large web application that heavily relies on jQuery and has been in constant development for the past 7-8 years. Over this time, several versions of jQue ...

Using localized strings in Spring and jQuery validation: Best practices

Consider this form as an illustration: <form id="login_form" method="post" action="/rest/auth/auth"> <div id="login_email" class="row margin-top-50"> <div class="col-md-12" id="input_container"> <input id="log ...

Creating a Form with Dynamic HTML when Button is Clicked

I have been working on enhancing the functionality of my website app located at , but unfortunately, I have not been successful so far. My goal is to introduce a vendor information form with just one click of a button and then enable users to add products ...

Using jQuery to evaluate multiple conditions within an if statement

I'm working on a script that needs to continuously monitor for the presence of an input field with the class name "email" (as this content is loaded via AJAX). If this input exists, I need to show another input field with the class name of "upload". A ...

Navigating URLs with Ajax Requests in CakePHP

How can ajax calls in javascript files located in the webroot be handled without PHP interpretation? In my project using CakePHP and require.js, I avoid placing javascript directly in views. To address this issue, I set a variable in the layout to store t ...

Exploring HTML5 using QXmlQuery

Looking to execute XQueries on a batch of HTML5 documents using QT (currently at 5.8...) HTML/HTML5 documents, unlike XHTML/XHTML5, are not well-formed XML files. HTML introduces elements that XML parsers cannot handle off the bat (such as special characte ...

In Angular, what is the best way to change the format of the timestamp '2019-02-22T12:11:00Z' to 'DD/MM/YYYY HH:MM:SS'?

I am currently working on integrating the Clockify API. I have been able to retrieve all time entries from the API, which include the start and end times of tasks in the format 2019-02-22T12:11:00Z. My goal is to convert the above date format into DD/MM/Y ...

Create a custom navigation bar using PlayFramework for a unique video streaming website

Attempting to create a dynamic navigation bar in Play using the code below in my main.scala.html file: @(title: String)(content: Html) <!DOCTYPE html> <html lang="en"> <head> <title>@title</title> <li ...

Unable to accommodate additional space, InputGroup is not utilizing the

Using react-bootstrap in my project, I have a component with the following code. I want the input and button to display together and fill up the entire space allocated by the Col. Although the input and button are displaying side by side, they are not ta ...

What is the best way to allow someone to chain callback methods on my custom jQuery plugin?

My goal is to enhance the functionality of jQuery.post() by implementing a way to check the response from the server and trigger different callbacks based on that response. For instance: $("#frmFoo").postForm("ajax") .start(function () { showSpinner( ...

Adjust jqGrid dimensions automatically as browser window is resized?

Does anyone know of a method to adjust the size of a jqGrid when the browser window is resized? I attempted the approach mentioned here, but unfortunately, it does not function correctly in IE7. ...