Be among the first to be updated with my insights on the newest .NET tech!
In last article The Role of JavaScript in Blazor I tried to lay out how a Blazor app can leverage JavaScript without being turned into it. Now, I'll cover Blazor WASM's JavaScript interopability feature which allows your Blazor app to execute JavaScript. This is commonly used to invoke custom JavaScript methods and browser APIs. Did you know that it works in both directions? Your JavaScript code can invoke a C# method of your Blazor app. I'll also cover that later on, in this article or you can watch the video. Why I use JavaScript in Blazor? The JavaScript ecosystem has an enormous amount of already built functionality and it can do anything from dynamically updating the layout on static web pages to full-fledged, highly-interactive, single-page web apps. There is a lot of knowledge and function to be learned, borrowed, re-used, ... That's exactly what I use it for in all of my Blazor WASM projects. I implement the JS interop feature for e.g. automatically starting carousels and other components that would be too time-consuming to rebuild. And, to access the browser APIs like navigator.share or the local storage and other useful client-side, browser functionality. Call JavaScript from Blazor For this demo, I scaffolded a new "Blazor Web App" with "RenderMode.Auto" interactivity set globally. The code will be available on my Patreon. I named this project: "JavaScriptInteropWithBlazor" and it contains a server-side project with the same name and a ".Client" project. Take the typical "scroll to top" functionality, let's add that code into the client project's wwwroot/js/custom.js. 1. Add the custom JavaScript code function scrollToElement(elementId) { console.info(Invoked 'scrollToElement'); const element = document.getElementById(elementId); element?.scrollIntoView({ behavior: 'smooth' }); } For demo purposes, I added a log statement simply to verify that it worked. 2. Add the script tag Then, we'll need to make sure this custom code is included in our application. Let's add the