Exclusive event triggered in Blazor only upon changing the page location

Just starting out with Blazor. I've been working on a Blazor project that utilizes DevExpress components, causing some issues with scrolling. My goal is to have the page start at the top every time I navigate to a new page. Currently, I've found a temporary solution by using the OnAfterRenderAsync method in the Main Navigation Layout to trigger this functionality.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    await JsRuntime.InvokeVoidAsync("ScrollTop");
}

This method is implemented in the MainLayout component and the corresponding code can be found in a separate JS file:

function ScrollTop() {

document.getElementsByClassName('content')[0].scrollTop = 0;

}

Although this approach somewhat works by loading pages at the top, any changes made to in-page components cause the page to scroll back up. Is there a way to modify this so that the event only fires when the page location is changed?

Answer №1

A solution is available for implementing this technique. Begin by creating a new JavaScript file within your wwwroot directory. For instance, name it ScrollToTop.js. Inside this file, insert your code utilizing the export function.

export function Scroll() {
document.getElementsByClassName('content')[0].scrollTop = 0;
}

Within your component, establish an OnAfterRenderAsync method and invoke your function within it:

    protected override async Task OnAfterRenderAsync(bool firstRender)
{
        await using var module = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./ScrollToTop.js");
        await module.InvokeVoidAsync("Scroll");
}

Answer №2

Make sure to include the following code snippet in your MainLayout.razor file:

@inject NavigationManager NavigationManager


protected override void OnInitialized() {
    NavigationManager.LocationChanged += OnLocationChanged;
}

async void OnLocationChanged(object sender, LocationChangedEventArgs args) {        
    await JsRuntime.InvokeVoidAsync("ScrollTop");
}

public void Dispose() {
    NavigationManager.LocationChanged -= OnLocationChanged;
}

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

Assistance required for activating an unidentified function or plugin within a Chrome extension

I am currently working on a project involving a chrome extension designed to automate tasks on a specific website. My main focus right now is trying to trigger the click event of a link that has an event handler set up through an anonymous function as show ...

Issue with adding json_encode to the end

I am trying to add the service using jQuery.each(), but it is not working in my JavaScript code? This is the output I am getting from my PHP code: { "data": [{ "service": ["shalo", "jikh", "gjhd", "saed", "saff", "fcds"], "address": " ...

The image slide change feature ceases to function properly when incorporating two separate functions

I have a function that successfully changes the image of a container every 5 seconds. However, I am facing an issue when trying to add 2 containers side by side and change their images simultaneously. When I run the functions for both containers, only one ...

Using an if/else statement in a Jade Template to conditionally remove a select option

I'm a beginner with Jade and I've been assigned to add a select option to a webpage. Everything is working well, except for when the drop-down list is empty and the page is refreshed, an empty option element is created. I want to find a way to re ...

Tips for entering multiple values in an input field

I am attempting to implement a feature where multiple names can be added from an autocomplete drop-down menu to an input field, similar to the example shown below: https://i.sstatic.net/D4hGA.jpg Here is what I aim to create: Upon selecting an item from ...

Load the index file using any URL parameter in the Express.js Router's "catchall" feature

I have a simple setup for my project, including server.js file in the root directory with the following code: app.use('/', express.static(__dirname + '/public/')); In addition, there is a public folder containing index.html, styles, a ...

Issue with React's MaterialUI Select Component not displaying the values passed as props

In my component, I have a FormControl element that includes a Select element accepting an array of options for MenuItem options, as well as a value as props. The component code looks like this: const TaxonomySelector = (props) => { const { isDisabled, t ...

Hiding a button based on the visibility of another button in the user's viewport

Is there a way to dynamically hide button B when the user scrolls and button A becomes visible on the screen? Additionally, how can we show button B again once button A is no longer visible to the user? Both buttons should never be visible simultaneously. ...

What is the best way to utilize a basic jQuery hide/show function to display everything before hiding it?

I have a dropdown menu where selecting an option will display a specific section based on the matching value and class, while hiding all other sections. How can I set it up so that before any selection is made, all sections are displayed and only hide afte ...

Filtering a list with Vue.js using an array of checkboxes

Currently, I am exploring ways to filter a v-for list using a checkbox model array with multiple checkboxes selected. Most examples I have come across only demonstrate filtering one checkbox at a time. In the demo here, you can see checkboxes 1-3 and a lis ...

What methods are commonly used to calculate the bitsPerSecond rate for media recording?

Is there a specific formula that combines frames per second and resolution to determine the bits per second for video encoding? I'm struggling to figure out the appropriate values to use for specifying the bits per second for 720p, 1080p, and 4k video ...

What is the correct way to incorporate Regular Expressions in Selenium IDE coding?

Using regular expressions to check for a correct answer from a prompt has been challenging. The current expression seems to be giving unexpected results, marking valid answers as false. For instance, when inputting the number 3, Selenium indicates that the ...

The Node.js error message reads: "Cannot set headers after they have been sent" while trying to make a post request

Yes, I understand this issue has been addressed multiple times on stackoverflow, but unfortunately, I haven't found a solution that works for me. The problem arises when trying to make a post request on my nodejs server. The error message states &apo ...

Tips on using CSS to hide elements on a webpage with display:none

<div class="span9"> <span class="disabled">&lt;&lt; previous</span><span class="current numbers">1</span> <span class="numbers"><a href="/index/page:2">2</a></span> <span class="num ...

Should I implement this practice when developing an AJAX website? Is it recommended to enable PHP code within .html files, or should I switch to using .php files instead?

Query: I am interested in executing PHP within HTML documents to include HTML using PHP include();. Question: Would it be more beneficial to change .php to .txt for my AJAX-loaded pages and switch my .html files to .php? This approach might resolve the ...

Error: Unable to access property 'nTr' as it is not defined

When I invoke the fnSelect function, an error occurs in Chrome: Uncaught TypeError: Cannot read property 'nTr' of undefined This is the code snippet causing the issue: $('#ToolTables_table_id_0, #ToolTables_table_id_1').mousedown(fun ...

How can I retrieve the key name associated with each value in a JSON file?

I'm looking to automatically assign a property based on the key name within a JSON file. For example, if the key is "physicalAddress", then the AddressType should also be set as "physicalAddress". Currently, I am utilizing Newtonsoft.Json for this tas ...

AngularJS users are experiencing issues with the "See More" feature not functioning as expected

One of my tasks involves dealing with a block of text that needs to be truncated using ellipsis. To achieve this, I am utilizing jquery dotdotdot. For more information on dotdotdot, please refer to the documentation. I have created a straightforward dire ...

What is the significance of combining two arrays?

const customTheme = createMuiTheme({ margin: value => [0, 4, 8, 16, 32, 64][value], }); customTheme.margin(2); // = 8 This code snippet showcases how to define spacing values in a Material-UI theme configuration. For more details on customization re ...

Import Document from Project - Automation Framework Visual Studio 2010 C# using Selenium WebDriver

Is it possible to upload a file to a webpage using Selenium WebDriver in VisualStudio10 without specifying the file's path on my computer? Instead, can I add the file to the project and access it through code without having to hardcode the file path? ...