Difficulty with Vue Router horizontal scrolling to hash functionality

My goal is to achieve horizontal scrolling of the viewport by using a button wrapped in a router-link that navigates to a vue component. I was successful in achieving this functionality using anchor tags:

<a href="#about">
    <button class="btn">About</button>
</a>

However, when I tried to replace the anchor tags with router-link, the horizontal scroll stopped working (vertical scroll still works):

<router-link :to="{ hash: 'about' }">
    <button class="btn">About</button>
</router-link>

The issue seems to stem from the function defined in router.js responsible for the scroll behavior:

import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

export default new VueRouter({
    mode: "history",
    routes: [...],
    scrollBehavior(to, from, savedPosition) {
        if (to.hash) {
            return window.scrollTo({top: document.querySelector(to.hash).offsetTop, behavior: 'smooth'});
        }
        return window.scrollTo({top: 0, behavior: 'smooth'});
    }
});

The target component, where the viewport is supposed to scroll, is positioned on the right side outside the viewport as follows:

.about {
  position: absolute;
  transform: translateX(100%);
  height: 100vh;
  width: 100%;
}

Edit:

Upon changing the button code to:

<button @click="$router.push({ hash: 'about' })">About</button>

The viewport scrolls down approximately 20% but only vertically, not horizontally. The reason behind this behavior remains unclear. Running

scrollBehavior(to, from, savedPosition) {console.log(to)}
outputs the following information:

{name: 'home', meta: {…}, path: '/', hash: '#about', query: {…}, …}
fullPath: "/#about"
hash: "#about"
matched: [{…}]
meta: {}
name: "home"
params: {}
path: "/"
query: {}
[[Prototype]]: Object

Answer №1

Give this a shot:

<button @click="$router.push({ hash: 'about' })">About</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

Classic ASP offers a feature that allows users to select all checkboxes at once

I'm looking to create a functionality where there is a 'Select all' checkbox along with individual checkboxes for each database record. Is it possible to use JavaScript to ensure that when the 'Select all' checkbox is checked, all ...

How to send cross-domain AJAX requests to RESTful web services using jQuery?

I have been utilizing Jquery Ajax calls to access RESTful webservices in the following manner. The web service is being hosted on a different domain. $.ajax({ type: "GET", url: "url for the different domain hosting", crossDomain: true, ...

Evolving the appearance of every vacant element

Currently, I am working on a project that allows users to add items. To facilitate this process, I have included an "add another" button which enables them to include additional items all at once. In order to validate the form and save values to the datab ...

Problems with installing ambient typings

I'm having trouble installing some ambient typings on my machine. After upgrading node, it seems like the typings are no longer being found in the dt location. Here is the error message I am encountering: ~/w/r/c/src (master ⚡☡) typings search mo ...

Utilizing custom variables in Vuetify 3.0: A guide

Here is the configuration for my custom Vuetify theme const vuetify = createVuetify({ components, directives, theme: { defaultTheme: 'light', themes: { dark: { colors: { background: '#000000', ...

The onClick function within the .map function is continuously triggered

I am encountering an issue with my code where a Dialog confirmation prompt from Material UI keeps getting called unexpectedly. The problem seems to arise when I add a value to the function that is triggered by a button click within a loop of an array usi ...

Customize the text color of the active tab in Material-UI Tabs

I am facing a situation where I have this specific object: const tabStyle = { default_tab:{ color: '#68C222', width: '33.3%', backgroundColor: '#FFFFFF', fontSize: 15 }, active_tab: ...

What distinguishes between the methods of detecting falsy and truthy values?

While working with JavaScript / Typescript, I often find myself needing to verify if a length exists or if a value is true or false. So, the main query arises: are there any differences in performance or behavior when checking like this... const data = [ ...

Rendering Highcharts React Pie Chart Multiple Times

Here is the code snippet: import React, { useEffect, useRef, useState } from "react"; import * as Highcharts from "highcharts"; import HighchartsReact from "highcharts-react-official"; export const PieChart = (props: any) =&g ...

Is there a way to incorporate content onto a webpage solely through the use of CSS and JavaScript?

Currently, I am in the process of developing a real estate website that utilizes a paid service for displaying real estate listings. The unique aspect of this setup is that my website operates as a subdomain of the main listings website, resulting in a URL ...

Exploring the PayPal Checkout JavaScript SDK's CreateOrder call and interpreting the response

I am currently exploring how to use the JavaScript SDK to display PayPal payment buttons on a website. I am new to working with JSON and REST API calls, so I am facing some challenges in implementing this. The createOrder function is running smoothly and ...

Employing ng-show and other related features within directive "A"

After browsing through similar inquiries, I am still unable to comprehend the solution. If I have a directive available at this link: http://pastebin.com/QtAzGv62 and now need to incorporate the functionality of "ng-show" (or any other standard angular di ...

The new Date function is malfunctioning on Firefox

Could you please explain why this particular function is not functioning correctly in Firefox (V 34 latest)? It appears to be working successfully on all other browsers, but 'DatePosted' is displaying as Invalid Date. Do you have any insights on ...

ng-view does not support ng-repeat rendering

I have a basic app using ng-view and ng-repeat. Initially, it worked fine without ng-view, but after switching to ng-view, the ng-repeat stopped functioning correctly. Oddly, when I clicked on the "menu" link, it displayed another set of $var instead of ch ...

The last value label in Google Charts bar chart getting cut off

I've searched extensively for a solution to this issue regarding the haxis labels, but I have not been able to find one that addresses it... In the image provided below, you'll observe that the last percentage label on the horizontal axis is mis ...

What causes the discrepancy in the expiresIn value of my JWT when it is transmitted from the server to the front-end?

After setting the token expiry date on the server, I decided to log out the value to double-check it. However, upon checking the value on my React front-end, I noticed a significant change in the value received compared to what was sent from the server. Is ...

Exploring Angular $resource with a playful twist

Is there a recommended method for mocking the $resource object? I've looked online, but all my attempts ended with KARMA testing. It's not what I'm looking for. I'm thinking of creating a fake object so that I can easily switch betwee ...

The requested page for angular-in-memory-web-api could not be located within the Angular 4.2.2 CLI web-api functionality

Currently, I am delving into the Angular framework (specifically version 4.2.2) and going through the Tour of Heroes tutorial. As I progressed to the HTTP section, the tutorial introduced the use of angular-in-memory-web-api to simulate a web api server. ...

Select an option within a for loop nested in an each function

How To Fetch JSON Data and Create a Shopping Cart $.ajax({ url: "myurl", type: 'POST', dataType: "json" }).done(function(response){ $.each(response,function(k,v){ //UL this products info list ...

Tips for showing a variety of headers on your page

I am struggling to align multiple headers on the same horizontal line. Despite my efforts, only two of them display correctly while the third keeps dropping down a line. To see what I mean, take a look at this image: view current layout Here is the code ...