Carousel - Documentation | www.HtmlElements.com

Overview

Carousel represents a banner web component which displays images or slides with HTML content.

Smart UI for Web Components is distributed as smart-webcomponents NPM package. You can also get the full download from our website with all demos from the Download page.

Smart UI for Web Components is distributed as smart-webcomponents NPM package

  1. Download and install the package.

    npm install smart-webcomponents

  2. Once installed, import the Carousel module in your application.

    <script type="module" src="node_modules/smart-webcomponents/source/modules/smart.carousel.js"></script>

  3. Adding CSS reference

    The smart.default.css CSS file should be referenced using following code.

    <link rel="stylesheet" type="text/css" href="node_modules/smart-webcomponents/source/styles/smart.default.css" />

  4. Add the Carousel tag to your Web Page

    <smart-carousel id="carousel"></smart-carousel>

  5. Create the Carousel Component

    	<script type="module">
    		Smart('#carousel', class {
    			get properties() {
    				return  { dataSource:  [{ label: 'Slide 1', content: 'Content 1'}, { label: 'Slide 2', content: 'Content 2'}, { label: 'Slide 3', content: 'Content 3'}] }
    			}
    		});
    	</script>	   
    		

    Another option is to create the Carousel is by using the traditional Javascript way:
    	const carousel = document.createElement('smart-carousel');
    
    	carousel.disabled = true;
    	document.body.appendChild(carousel);
    		

    Smart framework provides a way to dynamically create a web component on demand from a DIV tag which is used as a host. The following imports the web component's module and creates it on demand, when the document is ready. The #carousel is the ID of a DIV tag.

    	import "../../source/modules/smart.carousel.js";
    
    	document.readyState === 'complete' ? init() : window.onload = init;
    
    	function init() { 
    		const carousel = new Smart.Carousel('#carousel',  { dataSource:  [{ label: 'Slide 1', content: 'Content 1'}, { label: 'Slide 2', content: 'Content 2'}, { label: 'Slide 3', content: 'Content 3'}] });
    	}
    	

  6. Open the page in your web server.
Load scripts

The following code adds the custom element to the page.


<!DOCTYPE html>
<html lang="en">
<head>
 <link rel="stylesheet" href="../../source/styles/smart.default.css" type="text/css" />
 <script type="text/javascript" src="../../source/smart.button.js"></script>
 <script type="text/javascript" src="../../source/smart.carousel.js"></script>
</head>
<body>
 <smart-carousel hide-indicators display-mode="3d" data-source="..."></smart-carousel>
</body>
</html>

Demo

Note how smart.element.js is declared before everything else. This is mandatory for all custom elements.

Appearance

Carousel's structure can be presented as navigation and presentation elements. Navigation elements are arrows(left and right) and indicators. Presentation elements are carousel's slides.

By default each slide can contain following elements:

  • label - Headline part of the slide.
  • content - Text content of the slide.
  • image - By default used as background image.
  • HTMLcontent - Custom HTML content. If the user want each slide to be with different structure.

Slides can be loaded from dataSource object( with label, content, image, HTMLcontent fields) or UL element(each list item represents different slide).

Loading via dataSource property:

<!DOCTYPE html>
<html lang="en">
<head>
 <link rel="stylesheet" href="../../source/styles/smart.default.css" type="text/css" />
 <script type="text/javascript" src="../../source/smart.element.js"></script>
 <script type="text/javascript" src="../../source/smart.button.js"></script>
 <script type="text/javascript" src="../../source/smart.carousel.js"></script>
</head>
<body>
 <smart-carousel data-source="..."></smart-carousel>
</body>
</html>

Loading via UL:

<!DOCTYPE html>
<html lang="en">
<head>
 <link rel="stylesheet" href="../../source/styles/smart.default.css" type="text/css" />
 <script type="text/javascript" src="../../source/smart.element.js"></script>
 <script type="text/javascript" src="../../source/smart.button.js"></script>
 <script type="text/javascript" src="../../source/smart.carousel.js"></script>
</head>
<body>
 <smart-carousel>
  <ul>
      <li><span>Item 1</span></li>
      <li><span>Item 2</span></li>
      <li><span>Item 3</span></li>
  </ul> 
 </smart-carousel>
</body>
</html>

Navigation elements can be enabled/disabled via fillowing boolean properties:

  • hideArrows - By default carousel arrows are visible. They are navigation buttons stored typically on the left and right side of the carousel. With them, the user can navigate back and forth between slides.
  • hideIndicators - By default carousel indicators are visible. They are presented as a row of small boxes, corresponding to the active slide position. The active item is visually recognizable.
 <smart-carousel>
  <ul>
      <li>
        <span>Slide 1</span>
        <p>Pellentesque in est aliquet.</p>
        <p>Pellentesque in est aliquet, fringilla lorem a...</p>
      </li>
      <li>
        <span>Slide 2</span>
        <p>Pellentesque in est aliquet, fringilla lorem a. </p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
      </li>
      <li>
        <span>Slide 3</span>
        <p>Nulla facilisi. Sed dictum justo sit amet ligula cursus.</p>
        <p>Pellentesque in est aliquet, fringilla lorem a...</p>
      </li>
  </ul> 
 </smart-carousel>

Demo

Behavior

User can navigate between carousel's slides in few displayMode options:

  • default - the viewport displays single slide.
  • multiple - multiple slides are shown in the viewport.
  • 3d - slides are displayed by layout with 3D perspective.

Default mode:

<smart-carousel display-mode="default" data-source="..."></smart-carousel>

Demo

Multiple mode

<smart-carousel display-mode="multiple" data-source="..."></smart-carousel>

Demo

3d mode

<smart-carousel hide-indicators display-mode="3d" data-source="..."></smart-carousel>

Demo

Setting slideShow to true allows automatic slide rotation by custom interval(in milliseconds).

<smart-carousel slide-show interval="10000" data-source="..."></smart-carousel>

The autoPlay feature allows automatically slideshow start. This property can be set to true or to number(represents custom delay in milliseconds).

<smart-carousel slide-show auto-play data-source="..."></smart-carousel>
<smart-carousel slide-show auto-play="6000" data-source="..."></smart-carousel>

Navigation

smartCarousel allows multiple ways for navigation:

  • via arrows - when hideArrows property is set to false.
  • via indicators - when hideIndicators property is set to false.
  • via keyboard - to use this feature, set keyboard to true :
    Key Action
    Arrow Right Moves to next slide.
    Arrow Up Moves to next slide.
    Arrow Left Moves to previous slide.
    Arrow Down Moves to previous slide.
    Home Moves to first slide.
    End Moves to last slide.
  • via mouse wheel - to use this feature, set wheel to true.
  • via swipe left or swipe right - to use this feature, set swipe to true.

Methods

smartCarousel has the following navigation methods:

  • next() - Moves to the slide with the next index.
  • pause() - Pauses carousel's slideshow.
  • slideTo(index) - Slides to the element with the given index.
  • prev() - Moves to the slide with the previous index.
  • play() - Starts carousel's slideshow.

Create, Append, Remove, Get/Set Property, Invoke Method, Bind to Event


Create a new element:
	const carousel = document.createElement('smart-carousel');
	

Append it to the DOM:
	document.body.appendChild(carousel);
	

Remove it from the DOM:
	carousel.parentNode.removeChild(carousel);
	

Set a property:
	carousel.propertyName = propertyValue;
	

Get a property value:
	const propertyValue = carousel.propertyName;
	

Invoke a method:
	carousel.methodName(argument1, argument2);
	

Add Event Listener:
	const eventHandler = (event) => {
	   // your code here.
	};

	carousel.addEventListener(eventName, eventHandler);
	

Remove Event Listener:
	carousel.removeEventListener(eventName, eventHandler, true);
	

Using with Typescript

Smart Web Components package includes TypeScript definitions which enables strongly-typed access to the Smart UI Components and their configuration.

Inside the download package, the typescript directory contains .d.ts file for each web component and a smart.elements.d.ts typescript definitions file for all web components. Copy the typescript definitions file to your project and in your TypeScript file add a reference to smart.elements.d.ts

Read more about using Smart UI with Typescript.

Angular provides the easiest way to set angular CLI projects using Angular CLI tool.

Install the CLI application globally to your machine.

npm install -g @angular/cli
ng new smart-angular-carousel

Navigate to the created project folder

cd smart-angular-carousel

Smart UI for Angular is distributed as smart-webcomponents-angular NPM package

  1. Download and install the package.
    npm install smart-webcomponents-angular
  2. Once installed, import the CarouselModule in your application root or feature module.

    app.module.ts

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { CarouselModule } from 'smart-webcomponents-angular/carousel';
    import { AppComponent } from './app.component';
    
    @NgModule({
        declarations: [ AppComponent ],
        imports: [ BrowserModule, CarouselModule ],
        bootstrap: [ AppComponent ],
    	entryComponents: [ AppComponent ]
    })
    
    export class AppModule { }
    	

  3. Adding CSS reference

    The following CSS file is available in ../node_modules/smart-webcomponents-angular/ package folder. This can be referenced in [src/styles.css] using following code.

    	@import 'smart-webcomponents-angular/source/styles/smart.default.css';

    Another way to achieve the same is to edit the angular.json file and in the styles add the style.

    	"styles": [
    		"node_modules/smart-webcomponents-angular/source/styles/smart.default.css"
    	]
    	
  4. Example


    app.component.html

     
    <smart-carousel></smart-carousel>
    		

    app.component.ts

     
    import { Component, ViewChild, OnInit, AfterViewInit } from '@angular/core';
    
    
    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
    	styleUrls: ['./app.component.css']
    })
    
    export class AppComponent implements AfterViewInit, OnInit {	
    	
     
    	ngOnInit(): void {
    		// onInit code.
    	}
    
    	ngAfterViewInit(): void {
    		// afterViewInit code.
    		this.init();
        }
    		
    	init(): void {
    		// init code.
    	    
        
            const basePath = '../../../images/', carousel = document.querySelector('smart-carousel');
            carousel.dataSource = generateDataSource(6);
            function generateDataSource(items) {
                const dataSource = Array(items).fill({});
                dataSource.forEach((element, index) => dataSource[index] = {
                    image: `${basePath}carousel-medium-${index + 1}.jpg`,
                    label: 'Slide ' + index,
                    content: 'Content ' + index
                });
                return dataSource;
            }
        
    
    	}	
    }
    		

    app.module.ts

     
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { CarouselModule } from 'smart-webcomponents-angular/carousel';
    
    import { AppComponent } from './app.component';
    
    @NgModule({
        declarations: [ AppComponent ],
        imports: [ BrowserModule, CarouselModule ],
        bootstrap: [ AppComponent ],
    	entryComponents: [ AppComponent ]
    })
    
    export class AppModule { }
    		


After completing the steps required to render a Carousel, run the following command to display the output in your web browser

ng serve
and open localhost:4200 in your favorite web browser.

Read more about using Smart UI for Angular: https://www.htmlelements.com/docs/angular-cli/.

The easiest way to start with React is to use create-react-app. To scaffold your project structure, follow the installation instructions.

	npm install -g create-react-app
	create-react-app my-app
	cd my-app
	npm start
	

Preparation

Open src/App.js andsrc/App.css

  1. Remove everything inside the App div tag in src/App.js:
    <div className="App"> </div>
  2. Remove the logo.svg import
  3. Remove the contents of src/App.css
  4. Remove src/logo.svg

Setup the Carousel

Smart UI for React is distributed as smart-webcomponents-react NPM package

  1. Download and install the package.
    npm install smart-webcomponents-react
  2. Once installed, import the React Carousel Component and CSS files in your application and render it app.js

    import 'smart-webcomponents-react/source/styles/smart.default.css';
    import React from "react";
    import ReactDOM from "react-dom";
    import { Carousel } from 'smart-webcomponents-react/carousel';
    
    class App extends React.Component {
    
    	init() {
    		const basePath = 'https://www.htmlelements.com/demos/images/',
    			carousel = this.refs.carousel;
    		carousel.dataSource = generateDataSource(6);
    
    		function generateDataSource(items) {
    			const dataSource = Array(items).fill({});
    			dataSource.forEach((element, index) => dataSource[index] = {
    				image: `${basePath}carousel-medium-${index + 1}.jpg`,
    				label: 'Slide ' + index,
    				content: 'Content ' + index
    			});
    			return dataSource;
    		}
    
    	}
    
    
    	componentDidMount() {
    		this.init();
    	}
    
    	render() {
    		return (
    			<div>
    				<Carousel ref="carousel"></Carousel>
    			</div>
    		);
    	}
    }
    
    ReactDOM.render(<App />, document.querySelector("#root"));
    
    export default App;
    	

Running the React application

Start the app with
npm start
and open localhost:3000 in your favorite web browser to see the output.

Read more about using Smart UI for React: https://www.htmlelements.com/docs/react/.


We will use vue-cli to get started. Let's install vue-cli

npm install -g @vue/cli

Then we can start creating our Vue.js projects with:

vue create my-project

Open the "my-project" folder and run:

npm install smart-webcomponents

Setup with Vue 3.x

  • Make Vue ignore custom elements defined outside of Vue (e.g., using the Web Components APIs). Otherwise, it will throw a warning about an Unknown custom element, assuming that you forgot to register a global component or misspelled a component name.

    Open src/main.js in your favorite text editor and change its contents to the following:

    main.js

    import { createApp } from 'vue'
    import App from './App.vue'
    
    const app = createApp(App)
    
    app.config.isCustomElement = tag => tag.startsWith('smart-');
    app.mount('#app')
    		
  • Open src/App.vue in your favorite text editor and change its contents to the following:

    App.vue

    <template>
      <div class="vue-root">
        <smart-carousel></smart-carousel>
      </div>
    </template>
    
    <script>
    import { onMounted } from "vue";
    import "smart-webcomponents/source/styles/smart.default.css";
    import "smart-webcomponents/source/modules/smart.carousel.js";
    
    export default {
      name: "app",
      setup() {
        onMounted(() => {
          const basePath = "../../../images/",
            carousel = document.querySelector("smart-carousel");
          carousel.dataSource = generateDataSource(6);
    
          function generateDataSource(items) {
            const dataSource = Array(items).fill({});
            dataSource.forEach(
              (element, index) =>
                (dataSource[index] = {
                  image: `${basePath}carousel-medium-${index + 1}.jpg`,
                  label: "Slide " + index,
                  content: "Content " + index
                })
            );
            return dataSource;
          }
        });
      }
    };
    </script>
    
    <style>
    smart-carousel .smart-carousel-item .smart-carousel-item-content,
    smart-carousel .smart-carousel-item .smart-carousel-item-label {
      font-size: 48px;
      color: #fafafa;
    }
    
    @media screen and (max-width: 700px) {
      smart-carousel {
        width: 100%;
      }
    }
    </style>
    		
    We can now use the smart-carousel with Vue 3. Data binding and event handlers will just work right out of the box.

Setup with Vue 2.x

  • Make Vue ignore custom elements defined outside of Vue (e.g., using the Web Components APIs). Otherwise, it will throw a warning about an Unknown custom element, assuming that you forgot to register a global component or misspelled a component name.

    Open src/main.js in your favorite text editor and change its contents to the following:

    main.js

    import Vue from 'vue'
    import App from './App.vue'
    
    Vue.config.productionTip = false
    Vue.config.ignoredElements = [
    'smart-carousel'
    ]
    
    new Vue({
      render: h => h(App),
    }).$mount('#app')
  • Open src/App.vue in your favorite text editor and change its contents to the following:

    App.vue

    <template>
      <smart-carousel></smart-carousel>
    </template> 
    
    <script>
    import 'smart-webcomponents/source/modules/smart.carousel.js';
    import "smart-webcomponents/source/styles/smart.default.css";
    
    export default {
      name: "app",
      data: function() {
        return {
          images: [
            {
              image: "https://www.htmlelements.com/demos/images/carousel-medium-1.jpg",
              label: "Slide 0",
              content: "Content 0"
            },
            {
              image: "https://www.htmlelements.com/demos/images/carousel-medium-2.jpg",
              label: "Slide 1",
              content: "Content 1"
            },
            {
              image: "https://www.htmlelements.com/demos/images/carousel-medium-3.jpg",
              label: "Slide 2",
              content: "Content 2"
            },
            {
              image: "https://www.htmlelements.com/demos/images/carousel-medium-4.jpg",
              label: "Slide 3",
              content: "Content 3"
            },
            {
              image: "https://www.htmlelements.com/demos/images/carousel-medium-5.jpg",
              label: "Slide 4",
              content: "Content 4"
            },
            {
              image: "https://www.htmlelements.com/demos/images/carousel-medium-6.jpg",
              label: "Slide 5",
              content: "Content 5"
            }
          ]
        };
      },
      mounted: () => {
        const basePath = "https://www.htmlelements.com/demos/images/",
          carousel = document.querySelector("smart-carousel");
        carousel.dataSource = generateDataSource(6);
    
        function generateDataSource(items) {
          const dataSource = Array(items).fill({});
          dataSource.forEach(
            (element, index) =>
              (dataSource[index] = {
                image: `${basePath}carousel-medium-${index + 1}.jpg`,
                label: "Slide " + index,
                content: "Content " + index
              })
          );
    
          return dataSource;
        }
      }
    };
    </script>
    
    <style>
      smart-carousel .smart-carousel-item .smart-carousel-item-content,
      smart-carousel .smart-carousel-item .smart-carousel-item-label {
        font-size: 48px;
        color: #fafafa;
      }
    
      @media screen and (max-width: 700px) {
        smart-carousel {
          width: 100%;
        }
      }
    </style>
    		
    We can now use the smart-carousel with Vue. Data binding and event handlers will just work right out of the box.
    We have bound the properties of the smart-carousel to values in our Vue component.

Running the Vue application

Start the app with
npm run serve
and open localhost:8080 in your favorite web browser to see the output below:

Read more about using Smart UI for Vue: https://www.htmlelements.com/docs/vue/.