JavaScript function to toggle visibility and scroll back to top of the page

I have been an avid reader on this platform, and I am hoping that my question has not already been addressed. I am struggling to find a solution to a problem I am facing.

There are two DIVs in my code that I toggle between showing and hiding using Javascript.

However, whenever the action is triggered, the page scrolls back to the top. Is there a way to keep the position intact? I have tried switching from visibility to display = 'block' / 'none', but it did not make any difference.

This is the structure of my code:

The two divs that are affected by the script are popup1 and popup2. They both have a position: fixed;. The element class has viewport height.

I believe this information should be sufficient to troubleshoot the issue. If not, please feel free to ask for more details.

Thank you for your assistance!

UPDATE: You can view the JSFiddle here: https://jsfiddle.net/vx6vju3c/2/

Answer №1

To eliminate the href="#" or modify the <a> tag to <button>

Answer №2

If you apply a min-height property to the element with id #content, it can be beneficial.

#content {
 min-height:100px;
}

Answer №3

Modify <a> elements to <buttons>:

<div id="content">
    <div id="popup1">
        <div id="hoverbarnavi">
        <button type="button" onclick="hide('popup1'); show('popup2')">Close</button>
        </div>
        <div id="hoverbarcontent">
            This is Popup 1
        </div>
    </div>
    <div id="popup2">
        <div id="hoverbarnavi">
            <button type="button" onclick="hide('popup2')">Close </button>
        </div>
        <div id="hoverbarcontent">
            This is Popup 2
        </div>
    </div>

  <div class="element">Content 1 goes here</div>
  <div class="element">Content 2 goes here</div>
</div>

The issue arises from having href="#" within the <a> tag, which causes the page to scroll back to the top when clicked.

Answer №4

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Smooth Scroll To Top Demo</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>


    <style>
        .display-container
        {
            position: absolute;
            top: 3rem;
            left: 1rem;
            width: 300px;
        }
        body
{
    background: #eee;
}

.container{
    width:900px;
    margin:30px auto;
    padding:25px;
    min-height:400px;
    height:auto;
}
.container h2 { margin-top:30px;}

.scrollToTop{
    width: 50px;
    height: 50px;
    padding: 10px;
    text-align:center;
    background: whiteSmoke;
    font-weight: bold;
    color: #fff;
    text-decoration: none;
    position:fixed;
    bottom: 75px;
    right: 40px;
    display: none;
    background: #000;
}
.scrollToTop:hover{
    text-decoration: none;
}
    </style>
    <script>
    var $ = jQuery.noConflict();
jQuery(document).ready(function( $ ){
    scrollToTop.init( );
});

var scrollToTop =
{
    /**
     * When the user has scrolled more than 100 pixels then we display the scroll to top button using the fadeIn function
     * If the scroll position is less than 100 then hide the scroll up button
     *
     * On the click event of the scroll to top button scroll the window to the top
     */
    init: function(  ){

        //Check to see if the window is top if not then display button
        $(window).scroll(function(){
            if ($(this).scrollTop() > 100) {
                $('.scrollToTop').fadeIn();
            } else {
                $('.scrollToTop').fadeOut();
            }
        });

        // Click event to scroll to top
        $('.scrollToTop').click(function(){
            $('html, body').animate({scrollTop : 0},800);
            return false;
        });
    }
};
    </script>
</head>
<body>




<section class="container">

<h2>Smooth Scroll To Top Demo</h2>

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut in metus nec mauris egestas laoreet. Integer vehicula velit non massa suscipit at porta sem commodo....</p>

<a href="#" class="scrollToTop">Scroll To Top</a>


</section>


</body>
</html>

Here are the complete solution and very smooth scroll for check copy code make test html file run on browser, scroll down and click on back to top button on right bottom

Answer №5

If you include href="#" in the Anchor tag, it will direct you to the top of the webpage when clicked.

To avoid this behavior, simply remove the href="#" attribute and observe if you prefer not changing the tag to a button.

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

How can you easily reuse an Ajax method in Vue.js by passing a Vue data array name as an argument?

After dedicating 9 hours to learning Vue.js, I have ventured into using it with JQuery Ajax. My challenge lies in making the last argument work as intended. Passing an array name expected to exist in vue data: {... seems to yield no results. Update: I hav ...

What is the best method for me to filter the values in my array?

I need to add a value to an array based on certain conditions. My code looks something like this: var newEmployee = []; $scope.employees = [{'id':1, 'new':true},{'id':2, 'new':false}{'id':3, 'new&apo ...

Assigning multiple identifiers to a single element

Multiple posts have emphasized the importance of using an ID only once. But, I'm facing a situation where I need to pass 2 PHP variables to my JavaScript. I initially thought of using document.getElementById, but since IDs must be unique, this approa ...

First render does not define useEffect

Why am I experiencing an issue here? Whenever I attempt to retrieve data from my API, it initially returns undefined during the first render, but subsequent renders work correctly. const [data, setData] = useState([]) useEffect(() => { const fe ...

Having trouble retrieving the $scope value in HTML, even though it was assigned within the success function of $http.post

Having trouble accessing the values of $scope properties after a successful $http post in index.html file. Here is the code snippet for reference, any help in resolving this issue would be greatly appreciated as I am new to AngularJs var app = angular.m ...

When the page first loads, there will be isotope gutter and spacing. However, as you resize the window,

When my isotope items load on the page, there is a noticeable gap between them. Interestingly, this issue disappears when I resize the window by even just 1px. I've been trying to figure out why this extra spacing occurs only on one particular page. ...

Strategies for Updating Backgrounds on Individual WordPress Pages

I am looking to revamp a WordPress blog with 5 different pages, each requiring a unique background image. Is there a method to achieve this without altering the background element, but instead changing the background image of the #main element in my CSS? ...

What is the best method for gracefully opening external links in a reusable new tab?

Here is the progress I have made so far: <script> var win; function OpenInNewTab(url ) { // var win; if (win) { win.close(); } win =window.open(url, 'myWin'); win.focus(); } </script> My links are structured like ...

Is there a way to enable popovers globally and also utilize the container: 'body' option simultaneously?

My Bootstrap 5 popovers seem to be missing the arrow and I suspect it's because of interference from the parent element. The documentation provides a solution by using the container: 'body' option on a single item. How can I apply this to al ...

AngularJS ngAnimate triggering prematurely

In the current setup, p2 animates in while p1 is still animating out. After that, p1 disappears and p2 glitches up the page. The desired effect is for 1 to fade out and then have 2 fade in. html: <nav> <a ng-click="changeView('p1' ...

Enhancing Next.js with custom CSS for React-Bootstrap components: A step-by-step guide

After installing the react-bootstrap module using the pm command and importing it into my _app.js file, I encountered an issue when trying to modify the Bootstrap code for my navbar component. The code snippet provided below showcases the navbar component: ...

Extract information from a webpage using JavaScript through the R programming language

Having just started learning about web scraping in R, I've encountered an issue with websites that utilize javascript. My attempt to scrape data from a specific webpage has been unsuccessful due to the presence of javascript links blocking access to t ...

Creating a visual selection menu with icon options using jQuery or a similar framework

Currently, I am working on designing an HTML form that includes a field where users must select from a set of options such as sunny, cloudy, rainy, and more. I am seeking a creative alternative to using the <select> or <radio> input elements. ...

Using jQuery, add a class for a specified amount of time in milliseconds

Can a class be temporarily added to an element and then removed after a certain number of milliseconds? For instance; If I were to click on an element with the class .trigger, would it be possible to add the class .loading to another element with the cla ...

Once the save operation is finished, I retrieve the collection from the server. However, since the fetch is asynchronous, the view is rendered before the fetch is fully complete

When making a fetch call on a collection, I then perform another fetch inside the success methods to retrieve a separate collection. Once both collections have been obtained, I combine them and render them to the view. However, after saving a new item in ...

How can I customize button colors in react-bootstrap components?

Changing colors in react-bootstrap may be a challenge, but I'm looking to customize the color of my button beyond the primary options. Any suggestions on how I can achieve this using JS and SCSS? ...

How can you handle all HTML tags with Regex in a single line of code?

I've developed a PHP script that converts all inline CSS in HTML tags to classes. Visit the following link for more information: https://gist.github.com/iBars/aa52c6119e53908c91ac553aeba229e0 However, it currently only processes tags that are the onl ...

Making <div> elements responsive by rearranging their display order using CSS in media queries, troubleshooting issues with floats, and adjusting font sizes

I'm currently working on a webpage located at: On this page, there is a containing division with 5 elements inside. They are floated left in order to align vertically, but I am facing some challenges when it comes to adjusting my CSS for media querie ...

How does Code Sandbox, an online in-browser code editor, manage file storage within the browser?

What are the ways in which Code Sandbox and StackBlitz, as online in-browser code editors, store files within the browser? ...

Obtain the range of values for a match from an array using Vue.js

I have an array in my Vue.js code with values 25, 100, 250, and 500. I am looking to find the key value that matches a specific range. For example, if the input is 5, then the output should be 25. However, the code I tried returns all values within the ran ...