What is preventing window.scrollTo() from being executed?

I have implemented Bootstrap's Buttons plugin to toggle the state of a custom checkbox. When the button is toggled on, a hidden element should appear at the top of the page and then the page should scroll to the top. Similarly, when the button is toggled off, the element should disappear and the page should scroll to the top.

Although the hidden element toggles correctly with the button, the scrolling feature does not work as intended.

I attempted changing the data-toggle attribute from 'buttons' to 'button', which made the scroll function properly but caused the button to not visually toggle, rendering this solution ineffective.

Setting an onchange event for the checkbox itself also did not result in successful scrolling.

It seems that Bootstrap's onclick event function may be interfering with the execution of my own event handling function. I need to investigate this further to understand the issue.

Utilizing a timeout for the window.scrollTo() function allows the scrolling to happen. However, I am curious about why this workaround is necessary and if there is a way to achieve the desired functionality without relying on a timeout.

<body>
    <div class="container">
        <div>
            <h3>Toggle Header and Scroll To Top</h3><hr />
            <h1 id="displayMe" class="d-none">Display Me</h1>
            <div style="height: 100vh;"></div>
            <div class="btn-group-toggle btn btn-success custom-control custom-switch" data-toggle="buttons" id="myButton">
                <input type="checkbox" class="custom-control-input" id="myCheckbox">
                <label class="custom-control-label" for="myCheckbox">Toggle and Scroll</label>
            </div>
        </div>
    </div>
    <script src="assets/jquery/jquery.min.js"></script>
    <script src="assets/twitter-bootstrap/js/bootstrap.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#myButton").on("click", toggleAndScroll);
        });

        function toggleAndScroll() {
            $('#displayMe').toggleClass('d-none');
            window.scrollTo(0, 0);
        }
    </script>
</body>

https://jsfiddle.net/ews9q50v/

(Uncomment the setTimeout lines to see it working)

Answer №1

I'm stumped as to why it's not working. Bootstrap seems to be causing the issue. However, a workaround is to resolve this by postponing the scrollTo function until the end of the event loop using setTimeout(func, 0).

$("#myButton").on("click", toggleAndScroll);

function toggleAndScroll() {
    $('#displayMe').toggleClass('d-none');

    setTimeout(function () {
        window.scrollTo(0, 0);
    }, 0);
}

Check out the demo here!

Answer №2

Chrome seems to handle this code well, but Firefox is encountering some issues:

function toggleAndScroll() {
  $('#displayMe').toggleClass('d-none');

  window.scrollTo({
    top: 0,
    left: 0,
    behavior: 'smooth'
  });
}

However, if you are using jQuery, you can try this alternative that works on both Firefox and Chrome:

function toggleAndScroll() {
  $('#displayMe').toggleClass('d-none');
  $("html, body").animate({ scrollTop: 0 }, "slow");
}

The problem may be related to the scroll height changing simultaneously with the scrollTo function being called.

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

Guide to connecting the response data from my MVC post controller

Is it possible to bind JSON data returned from a post action controller using the Controller View and JS? How can this be achieved? Controller [HttpPost] public ActionResult PBHEP(string PC,string FC) { /perform some data calculations ...

What could be causing the error I'm encountering while attempting to utilize Array.includes as the function for Array.filter in my JavaScript code?

During a recent javascript project, I attempted something like the following code snippet. To my surprise, it did not work and instead produced an error message. const test = [1, 2, 3, 4]; const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(test.includes) ...

Using the $lookup aggregation stage to $group a nested array in MongoDB

I'm working with a Product Schema that is partially built using mongoose. Here's a snippet: attributes: [ { set: { ref: 'AttributeSet', type: Schema.Types.ObjectId }, items: [ ...

What could be causing my JavaScript pricing calculator to malfunction?

I've been struggling to make the script below work, but I can't seem to figure out why. It should be functioning properly. Even though all variables are in place, no price is appearing? You can view the HTML on this page: var cake_prices = n ...

Making sure the axios API call is completed before rendering the child component with props

Check out the snippet of code I've provided: function StoryCarousel(props) { const [ivrDests, setIVRDests] = useState([]); useEffect(() => { async function getIVRDests() { var data = { "customer-id": ...

How to Revalidate a Next.js Dynamic Route Manually Using an API Route?

In my application built with Next.js, I have a dynamic page that displays resources at the route /resource/[id]. When a user edits a resource, such as #5, I want to refresh the cached page at /resource/5. I've created an API route in my /pages direct ...

Exploring the Power of Destructuring Results in React.js with Apollo

I have been exploring the Apollo client for my project, and I encountered an issue with two of my query functions. The first query, which retrieves a list of users, is working perfectly fine. However, I am struggling to understand why my second simple quer ...

Can the data retrieved from a jsonp call that may be considered "bad" be utilized effectively?

When making a JSONP call to another domain, I am receiving data that is in JSON format but not wrapped in a function. This causes a parse error to occur. However, the data is still retrievable and visible. Despite the error, is it possible to utilize the ...

Is there a way to generate PDF files from rrdcgi output?

I have developed an rrdcgi script to showcase system performance data through graphs. I am now seeking a way to allow users to generate PDFs on the spot, containing the current page's images and information along with header and footer details. Additi ...

Tips for preserving changes made to a jQuery script when the page is reloaded

Is there a way to retain jQuery script changes when the page is reloaded? I have a page where clicking on certain elements triggers events, and I want these changes to persist even after reloading the page, resetting only when the cache is cleared. I appre ...

Is JavaScript not having an impact on your HTML code?

I am attempting to create a dynamic number change when the user interacts with the "range-slider" element, but the number is not updating as expected. Below is the code I have written: var rangeSlider = function() { var slider = $(".range-slider"), ...

Simultaneous opening of several bootstrap collapse panels with a single button press

I have been developing a blog-style web application with Django. My goal is to display all the posts on the home page, with each post containing a collapse panel. Initially, I had hardcoded the IDs to trigger the collapse panels, causing all the panels to ...

How to determine if a radio button has been selected using Javascript?

I have come across scripts that address this issue, however they are only effective for a single radio button name. My case involves 5 different sets of radio buttons. I attempted to check if it is selected upon form submit. if(document.getElementById(&ap ...

Issues with Displaying Components Generated from an Array in JSX

I have a task variable which has the structure as follows: [ team_id_1: { task_id_1: { description: ... }, task_id_2: { description: ... } }, team_id_2: { ... } ] When trying ...

JavaScript: How to Build a Digital Grocery List with Browser Storage

Struggling with a tough exercise question, I could use some help deciphering it. https://i.stack.imgur.com/V5he2.png Here is how I've started the code: <!DOCTYPE html> <html> <head> <title></title> <script> fun ...

Incorporate an image into your webpage with the Fetch API by specifying the image link - JavaScript

I've been attempting to retrieve an image using the imageLink provided by the backend server. fetchImage(imageLink) { let result; const url = `https://company.com/internal/document/download?ID=${imageLink}`; const proxyurl = 'https:/ ...

Jquery and AJAX are struggling to load dynamic content when accessed locally

I have a keen interest in utilizing Ajax to dynamically load content into a div. While I have been using jQuery for a few months, my experience with Ajax is still limited. Recently, I came across a downloadable tutorial online that seemed promising here. H ...

Unusual issue in IE causing rendering problems in reporting services

Currently, I am creating a report using Reporting Services 2008, MVC 2, and Ajax as my development technologies. When I generate the report, everything displays perfectly if there is data present. However, if there is no data, the report body gets cut off ...

Seeking assistance with formatting output for OpenCPU and igraph

Here is my adjacency array data: var g = [[10, 2], [15, 0], [18, 3], [19, 6], [20, 8.5], [25, 10], [30, 9], [35, 8], [40, 5], [45, 6], [50, 2.5]] The code I am using in OpenCPU is as follows: ocpu.call("centralization.closeness", {graph: g} ...

Tips for wrapping a div element around another div at the top left corner

I am working with a particular layout. <div class="comment"> <div class="leftpart"> </div> <div class="rightpart"> </div> </div> When viewing on a desktop, I maintain the original styling where each div is in its own s ...