How to use Bootstrap Carousel in Blazor
Asked Answered
H

2

17

newbie in Blazor. Need to try out how to use BS carousel in Blazor.

I used below code in the Default Blazor app. But it does not work. What I need to do?

Thanks

  1. I added this line in the Index.html

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>

  2. In the Counter page. I added the following:

<div class="container">

<div class="carousel-inner">

  <div class="item active">
    <img src="la.jpg" alt="Los Angeles" style="width:100%;">
    <div class="carousel-caption">
      <h3>Los Angeles</h3>
      <p>LA is always so much fun!</p>
    </div>
  </div>

  <div class="item">
    <img src="chicago.jpg" alt="Chicago" style="width:100%;">
    <div class="carousel-caption">
      <h3>Chicago</h3>
      <p>Thank you, Chicago!</p>
    </div>
  </div>

  <div class="item">
    <img src="ny.jpg" alt="New York" style="width:100%;">
    <div class="carousel-caption">
      <h3>New York</h3>
      <p>We love the Big Apple!</p>
    </div>
  </div>

</div>


<a class="left carousel-control" href="#myCarousel" data-slide="prev">
  <span class="glyphicon glyphicon-chevron-left"></span>
  <span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
  <span class="glyphicon glyphicon-chevron-right"></span>
  <span class="sr-only">Next</span>
</a>  

< /div >

-- Update: Index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>BlazorCarouselTest</title>
    <base href="/" />
    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
    <link href="css/site.css" rel="stylesheet" />
    <script src="css/bootstrap/jquery-3.4.0.min.js" type="text/javascript"></script>
</head>
<body>
    <app>Loading...</app>

    <script src="_framework/blazor.webassembly.js"></script>
</body>
</html &gt;
Horrocks answered 9/6, 2019 at 8:49 Comment(3)
No Err msg. It showed all the 3 images vertically. It suppose to show a horizontal scroll image by image. I had downloaed the jquery-3.4.0.js and place it in the same folder as bootstrap.Horrocks
Did your Blazor project include all the required JS for carousel? see the bootstrap quickstart page - specifically the JS section. Maybe show us the head section of your index.html?Sivan
please see updateHorrocks
E
18

Carousel needs a bit of javascript code, it needs to be configured on page load, but, into a blazor page, nobody calls the initialization for the component. The good news is that you can do it by code.

Three easy steps:

1.- Create and include javascript on blazor (you can copy paste this code at bottom of your index.html page )

<script>
window.initializeCarousel = () =>
{
    $('#carouselExampleIndicators').carousel({interval: 2000});

    //see step 2 to understand these news id's:
    $('#carouselExampleIndicators-prev').click ( 
            () => $('#carouselExampleIndicators').carousel('prev') );
    $('#carouselExampleIndicators-next').click ( 
            () => $('#carouselExampleIndicators').carousel('next') );

}
</script>

2.- Change a bit the carousel's html ( remove href from carousel-control-prev divs. Add an id for prev and next controls ):

<div id="carouselExampleIndicators" 
     class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item  active">
      <img class="d-block w-50" src="..." alt="Pepa Pig">
    </div>
    <div class="carousel-item">
      <img class="d-block w-50" src="..." alt="Sponge Bob">
    </div>
  </div>
  <a id="carouselExampleIndicators-prev" 
     class="carousel-control-prev" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a id="carouselExampleIndicators-next" 
     class="carousel-control-next" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

3.- Call the previous code after first render:

@page "/counter"
@inject IJSRuntime JsRuntime;
...

@functions {
    int currentCount = 0;
    bool firstRender = true; 
    ...
    protected async override Task OnAfterRenderAsync()
    {
      if (firstRender) 
      {
        await JsRuntime.InvokeAsync<object>("initializeCarousel");
        firstRender=false;
      }
    }

That's all:

enter image description here

Let us know if you your carousel is moving now!

Edited

Remember to include all js needed to run bootstrap carousel on index.html:

<body>
    <app>Loading...</app>

    <script
    src="https://code.jquery.com/jquery-3.4.1.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
    crossorigin="anonymous"></script>    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" 
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" 
    crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" 
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" 
    crossorigin="anonymous"></script>    
    <script src="_framework/blazor.webassembly.js"></script>

    <script>
    window.initializeCarousel = () =>
    {
        $('#carouselExampleIndicators').carousel({interval: 2000})
        $('#carouselExampleIndicators-prev').click ( 
            () => $('#carouselExampleIndicators').carousel('prev') );
        $('#carouselExampleIndicators-next').click ( 
            () => $('#carouselExampleIndicators').carousel('next') );
    }
    </script>
</body>
Embitter answered 11/6, 2019 at 16:21 Comment(10)
would like to know if the Deskop or Mobile phone in Offline mode, will this cause a problem if the bootstrap or Jquery not downloaded? It is required to create js file for bootstrap and jquery? ThanksHorrocks
Also like to know how you can run the Blazor app in MObile Emulator in VS2019. Your help is much appreciated.Horrocks
Hi @MilkBottle, thanks about your comments. I guess I answered your question with my answer. If you agree, just check answer as solution. For more questions, just write new posts (questions) on this site. RegardsEmbitter
Miraculously this worked! However the javascript override function was a little different for me: @functions { protected async override Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { await JsRuntime.InvokeAsync<object>("initializeCarousel"); firstRender = false; } } }Unto
@Horrocks This is not android emulator, in your browser(chrome) open inspect element then select mobile view and select iphone 5/6/7Declivity
@Unto "Miraculously this worked!" 😂😂🤣🤣🤣Embitter
Tried on Blazor Web Assembly client, .Net 5, gives this error: crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: Could not find 'initializeCarousel' ('initializeCarousel' was undefined). Error: Could not find 'initializeCarousel' ('initializeCarousel' was undefined). I have the script in my index file as described but still gives the same issue when I call await JsRuntime.InvokeAsync<object>("initializeCarousel");Galley
Please let me know if it can run without using JavaScript in Blazor Wasm app in .NET 5.Marylnmarylou
Hi @BrijeshKumarTripathi, be free to try it by yourself with net 5 and bootstrap 5 and come back with results and conclusions. Thanks.Embitter
@daniherrera thanks for your inspiration. Now I got the JavaScript free solution and I have posted my solution at https://mcmap.net/q/745891/-javascript-free-bootstrap-carousel-in-blazor-webassemblyMarylnmarylou
M
-2

I am able to auto scroll the carousel in blazor without javascript. I also got prev and next buttons working and when user clicks on prev or next it enters into manual mode and it stops scrolling automatically. You can check my solution at https://mcmap.net/q/745891/-javascript-free-bootstrap-carousel-in-blazor-webassembly

Marylnmarylou answered 20/4, 2021 at 4:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.