9

How to call js script file (app.js) in the section of @code

<script src="~/js/app.js"></script>
<script src="~/js/app.js">
function indexSlider(){
 alert(1);
}

@code{
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (!firstRender)
        {
            return;
        }

        await JSRuntime.InvokeAsync<string>("indexSlider");

    }
}
3
  • 1
    Why did you want to call js file?If you just want to load the app.js like using third-party js,you could set it to _Host.cshtml.If you want to invoke the method in app.js,you could follow the docs:learn.microsoft.com/en-us/aspnet/core/blazor/… Commented Jan 15, 2020 at 9:54
  • can you specify more your problem its unclear , what is your error, what are you trying to achieve? Commented Dec 24, 2022 at 23:08
  • Does this answer your question? Call JavaScript function (from external library) with Blazor Commented Feb 3, 2023 at 7:33

2 Answers 2

1

Example JS code timer

var clock;
var date;
function startTime(element) {
    let timeString = new Date().toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric', second: 'numeric'});
    let dateString = new Date().toLocaleDateString('en-US', { dateStyle: 'full'});
    element.innerHTML = dateString + " - " + timeString;
    clock = setTimeout(startTime.bind(null, element), 1000);
}
function stopTime() {
    clearTimeout(clock);
}

In your wwwroot folder find index.html

<script src='js/yourJS.js'></script>

In your razor component or page

@inject IJSRuntime jsRuntimeService

<div @ref='timeElement'></div>

@code
{
ElementReference timeElement;
     protected overried async Task OnInitializedAsync()
     {
        await jsRuntimeService.InvokeVoidAsync("startTime", timeElement);
        await jsRuntimeService.InvokeVoidAsync("Alertfunction");
     }
}
Sign up to request clarification or add additional context in comments.

Comments

0
@inject IJSRuntime JSRuntime
@code{
IJSObjectReference module;
module = await JSRuntime.InvokeAsync<IJSObjectReference>("import","~/js/app.js");
await module.InvokeVoidAsync("indexSlider", null);}

this is how you can do it and in your js file define a function like this.

export function indexSlider() 
{ //do something};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.