Tiny Slider can be installed via npm, yarn, or by directly including the JavaScript and CSS files.
npm:
npm install tiny-slider-react
yarn:
yarn add tiny-slider-react
Direct Download:
Download the latest release from [link to release page] and include the tiny-slider.js
and tiny-slider.css
files in your project.
Tiny Slider provides a simple and intuitive API. You initialize the slider by selecting your container element and providing configuration options. The core functionality is controlled through JavaScript, while styling is primarily managed via CSS. Refer to the configuration options section for detailed information on customizing the slider’s behavior.
After installation (using whichever method you prefer), you need to include the necessary files in your HTML. If using the direct download method, include the CSS file in the <head>
section and the JavaScript file before the closing </body>
tag. For npm or yarn installations, you’ll need to import them into your JavaScript file using your module bundler’s (like Webpack or Parcel) import syntax.
Direct Download Example:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="tiny-slider.css">
</head>
<body>
<div class="my-slider"></div>
<script src="tiny-slider.js"></script>
<script>
//Your JavaScript initialization code here
</script>
</body>
</html>
npm/yarn Example (using a module bundler):
import 'tiny-slider/dist/tiny-slider.css'; // import CSS first
import tns from 'tiny-slider';
//Your JavaScript initialization code here
This example demonstrates a basic slider setup. Replace #my-slider
with the ID of your slider container. Remember to include the necessary CSS and JavaScript as described in the previous section.
<div id="my-slider">
<div>Slide 1</div>
<div>Slide 2</div>
<div>Slide 3</div>
</div>
<script>
const slider = tns({
container: '#my-slider',
items: 1, // Display 1 item at a time
slideBy: 'page', //Move one page at a time
autoplay: false //Disable autoplay
;
})</script>
This code creates a slider with three slides, displaying one slide at a time. You can easily customize this further by adding more slides and modifying the options provided to tns()
. Refer to the configuration section for available options.
Tiny Slider is initialized using the tns()
function. This function takes a single argument: an object containing configuration options. The most basic initialization requires specifying the container element. All other options are optional and provide granular control over the slider’s behavior.
Basic Initialization:
const slider = tns({
container: '#my-slider' // Required: CSS selector or DOM element for the slider container
; })
Initialization with Options:
const slider = tns({
container: '#my-slider',
items: 3,
autoWidth: true,
autoplay: true
; })
Remember to include the Tiny Slider CSS and JavaScript files in your project before initializing the slider. The tns()
function returns an object representing the slider instance, allowing you to access methods and events. Failure to initialize correctly will result in no slider being created. Always check your browser’s console for errors.
The tns()
function accepts a wide range of options to customize the slider’s appearance and functionality. Below are some of the most commonly used options. A complete list with detailed explanations can be found in the full options reference.
container
(required): CSS selector or DOM element of the slider container.items
: Number of items visible at once.slideBy
: Number of items to move on each swipe or click. Can be a number or ‘page’.autoplay
: Boolean to enable/disable autoplay.autoplayTimeout
: Milliseconds between autoplay transitions.controls
: Boolean to enable/disable next/prev buttons.nav
: Boolean to enable/disable navigation.autoWidth
: Boolean to automatically adjust item widths based on content.responsive
: Object to define responsive settings for different screen sizes.The slider instance returned by tns()
provides several methods to control the slider’s behavior programmatically.
goTo(index)
: Navigates to a specific slide at the given index (0-based).next()
: Moves to the next slide.prev()
: Moves to the previous slide.destroy()
: Completely removes the slider and its event listeners.rebuild()
: Rebuilds the slider, useful after dynamically adding or removing slides.Example usage:
const slider = tns({ /* ... options ... */ });
// Go to the third slide (index 2)
.goTo(2);
slider
// Go to the next slide
.next();
slider
// Destroy the slider
.destroy();
slider
//Rebuild after DOM changes
.rebuild(); slider
Refer to the complete methods reference for a full list and detailed descriptions.
Tiny Slider triggers several custom events that you can listen for to perform actions based on slider state changes. These events are dispatched on the slider container element.
tns:loaded
: Fired when the slider has finished initializing.tns:transitionStart
: Fired when a transition begins.tns:transitionEnd
: Fired when a transition completes.tns:indexChanged
: Fired when the current index changes.Example usage (using jQuery):
$('#my-slider').on('tns:loaded', function(){
console.log('Slider loaded!');
; })
Example usage (using vanilla JavaScript):
document.getElementById('my-slider').addEventListener('tns:loaded', function(){
console.log('Slider loaded!');
; })
Refer to the complete events reference for a full list and detailed descriptions. Remember to replace #my-slider
with the actual ID of your slider container. Event handling methods may vary slightly depending on your preferred JavaScript library or framework.
Tiny Slider provides a basic CSS stylesheet for its core components. You can easily customize the slider’s appearance by overriding these styles in your own CSS. The CSS classes are designed to be intuitive and easy to target. For example, you can target individual slides using the .tns-item
class, or the navigation controls using .tns-controls
and its child elements.
Overriding default styles:
Add your custom CSS rules after including the Tiny Slider CSS file to ensure they take precedence. For instance, to change the background color of slides:
.tns-item {
background-color: #f0f0f0;
}
Remember to inspect the generated HTML and CSS to identify the specific classes you need to target for your customizations. Consult the Tiny Slider CSS file for a complete list of available classes.
Tiny Slider offers options to customize the navigation controls (arrows and pagination). You can enable or disable them via the controls
and nav
options during initialization. You can also create your own custom navigation elements and integrate them with Tiny Slider’s API.
Custom Navigation Example:
You can create custom navigation buttons and then link their click events to the next()
and prev()
methods of the slider instance.
<button id="prev-button">Previous</button>
<button id="next-button">Next</button>
<script>
const slider = tns({ /* ...options... */ });
document.getElementById('prev-button').addEventListener('click', () => slider.prev());
document.getElementById('next-button').addEventListener('click', () => slider.next());
</script>
This allows for complete creative control over the navigation’s design and placement.
Tiny Slider supports responsive design through the responsive
option. This option takes an object where keys are breakpoint widths (in pixels) and values are objects containing options to be applied at that breakpoint.
Responsive Configuration Example:
const slider = tns({
container: '#my-slider',
items: 3,
responsive: {
640: { // Screen width 640px and below
items: 1
,
}1024: { // Screen width 1024px and below
items: 2
}
}; })
This configuration displays 3 items on larger screens, 2 items on screens 1024px wide or less, and 1 item on screens 640px wide or less. You can define as many breakpoints as needed to suit your design.
Building accessible sliders is crucial for inclusivity. Tiny Slider doesn’t automatically enforce all accessibility best practices, but it offers options and features to make it easier to build an accessible experience.
Keyboard Navigation: Tiny Slider inherently supports keyboard navigation through arrow keys for moving between slides.
ARIA Attributes: It’s recommended to add appropriate ARIA attributes to your slider elements to enhance screen reader compatibility. For example, use aria-label
to describe slides, aria-current
to indicate the active slide, and role="button"
for navigation controls.
Semantic HTML: Use semantically appropriate HTML elements. Avoid using divs when more specific elements could be applied.
Focus Management: Ensure proper focus management, particularly when using custom navigation. Use focus()
method as needed for better keyboard navigation flow.
Example of adding ARIA attributes:
<div id="my-slider" role="region" aria-label="Product Showcase">
<div class="tns-item" aria-label="Product 1"></div>
<div class="tns-item" aria-label="Product 2"></div>
</div>
Implementing these suggestions will significantly improve the accessibility of your Tiny Slider. Always test your slider with assistive technologies like screen readers to ensure its usability for all users.
Beyond basic initialization, Tiny Slider offers extensive programmatic control over its behavior. You can interact with the slider instance using its methods to dynamically manage slides, navigation, and transitions. This allows for highly customized user interactions and complex integrations.
Dynamically adding/removing slides: Modify the DOM content of the slider container and then call the rebuild()
method to update the slider. This allows you to seamlessly integrate with dynamic content loading and updates.
Responding to events: Use the events system to trigger custom actions based on slider state changes (e.g., tns:transitionEnd
). This enables synchronized animations, content updates, or user feedback.
Controlling autoplay: You can start, stop, or pause the autoplay functionality using the instance methods (though autoplay is typically controlled through options at initialization).
Custom Navigation Integration: Develop highly customized navigation by creating your own controls and binding them to slider’s next()
and prev()
methods.
You can initialize multiple Tiny Slider instances on a single page without conflicts. Each instance operates independently. Make sure each slider has a unique container selector or DOM element.
const slider1 = tns({ container: '#slider1' });
const slider2 = tns({ container: '#slider2' });
This example initializes two separate sliders, one with the ID slider1
and another with the ID slider2
. They will function independently, with no interference between them. Properly identifying each slider with unique selectors is crucial for avoiding unintended behavior.
Tiny Slider can be integrated with various JavaScript libraries and frameworks. Its API is designed for flexibility. However, remember to handle potential conflicts between libraries, especially those manipulating the DOM or event handling. Ensure correct order of inclusion and potential compatibility issues.
For example, when integrating with a framework like React, Vue, or Angular, you’ll need to incorporate Tiny Slider into your component lifecycle and appropriately handle updates to the slider after DOM manipulation.
Common issues with Tiny Slider often involve incorrect initialization, CSS conflicts, or DOM manipulation.
Slider not initializing: Double-check your container selector, ensure Tiny Slider’s CSS and JavaScript are correctly included, and inspect the browser’s console for error messages.
CSS conflicts: Ensure your custom CSS overrides don’t interfere with Tiny Slider’s default styles. Use your browser’s developer tools to inspect styles and identify conflicting rules.
Unexpected behavior after DOM updates: If dynamically adding or removing slides, always call the rebuild()
method on the slider instance to reflect changes correctly.
Performance issues: See the “Performance Optimization” section below.
Consult the FAQ section for frequently asked questions and solutions.
For optimal performance, especially with large numbers of slides or complex configurations:
Minimize DOM manipulation: Avoid frequent modifications to the slider’s DOM structure. Instead, update content and then call rebuild()
.
Optimize images: Use appropriately sized images and optimize them for web performance.
Lazy loading: Implement lazy loading for images to improve initial load times, especially if you have many large images.
Avoid unnecessary calculations: Be mindful of computationally expensive operations within your custom event handlers or functions that interact with the slider.
Use appropriate data structures: If working with many slides, consider using efficient data structures to manage information related to slides, avoiding performance bottlenecks from excessive data lookups or manipulations.
By addressing these factors you can keep your slider performing smoothly even with a large amount of content.
This example shows the most basic slider setup. It displays three slides, one at a time.
<div id="basic-slider">
<div>Slide 1</div>
<div>Slide 2</div>
<div>Slide 3</div>
</div>
<script>
const slider = tns({
container: '#basic-slider',
items: 1
;
})</script>
Remember to include the Tiny Slider CSS and JavaScript files in your project. This example uses only the essential container
and items
options.
This example adds navigation controls (next/prev buttons and pagination) to the basic slider.
<div id="slider-with-nav">
<div>Slide 1</div>
<div>Slide 2</div>
<div>Slide 3</div>
</div>
<script>
const slider = tns({
container: '#slider-with-nav',
items: 1,
controls: true,
nav: true
;
})</script>
Setting controls: true
and nav: true
enables the default navigation features.
This example adds autoplay functionality to the slider.
<div id="slider-with-autoplay">
<div>Slide 1</div>
<div>Slide 2</div>
<div>Slide 3</div>
</div>
<script>
const slider = tns({
container: '#slider-with-autoplay',
items: 1,
autoplay: true,
autoplayTimeout: 3000 // 3 seconds
;
})</script>
autoplay: true
enables autoplay, and autoplayTimeout
sets the interval between transitions (in milliseconds).
This example demonstrates lazy loading images. Replace placeholders with your actual image URLs.
<div id="slider-with-lazyload">
<div><img data-src="image1.jpg" alt="Image 1"></div>
<div><img data-src="image2.jpg" alt="Image 2"></div>
<div><img data-src="image3.jpg" alt="Image 3"></div>
</div>
<script>
const slider = tns({
container: '#slider-with-lazyload',
items: 1,
lazyload: true
;
})</script>
lazyload: true
enables lazy loading. Images are loaded only when they become visible. Use data-src
attribute to specify the image source.
This example creates a slider that loops infinitely.
<div id="slider-infinite">
<div>Slide 1</div>
<div>Slide 2</div>
<div>Slide 3</div>
</div>
<script>
const slider = tns({
container: '#slider-infinite',
items: 1,
loop: true
;
})</script>
loop: true
enables infinite looping. The slider will seamlessly transition from the last slide back to the first.
This example demonstrates a responsive slider that adjusts the number of visible items based on screen size.
<div id="responsive-slider">
<div>Slide 1</div>
<div>Slide 2</div>
<div>Slide 3</div>
<div>Slide 4</div>
<div>Slide 5</div>
</div>
<script>
const slider = tns({
container: '#responsive-slider',
items: 3,
responsive: {
768: { items: 2 },
500: { items: 1 }
};
})</script>
The responsive
option allows specifying different configurations for various screen widths. Here, it displays 3 items on larger screens, 2 items on screens 768px or less, and 1 item on screens 500px or less. Remember to adjust breakpoints to fit your design.
Remember to replace placeholder image URLs and text with your actual content. These examples are designed to be starting points for your own custom sliders. Refer to the options reference for a complete list of available configurations and further customization.
Tiny Slider’s functionality is extensively controlled through options passed to the tns()
initialization function. These options allow fine-grained control over various aspects of the slider’s behavior, appearance, and responsiveness. Below is a summary; refer to the complete documentation for detailed explanations and default values. Options are generally case-sensitive.
Core Options:
container
: (required) CSS selector or DOM element of the slider container.items
: Number of items visible at once.slideBy
: Number of items or ‘page’ to move on each transition.autoWidth
: Boolean; if true, items will automatically adjust width to content.edgePadding
: Number or string; padding on edges for autoWidth mode.gutter
: Spacing between items.Navigation Options:
controls
: Boolean; enables/disables next/prev buttons.controlsText
: Array; custom text for next/prev buttons.nav
: Boolean; enables/disables pagination.navPosition
: String; position of pagination (‘top’, ‘bottom’, ‘left’, ‘right’).Autoplay Options:
autoplay
: Boolean; enables/disables autoplay.autoplayTimeout
: Milliseconds between autoplay transitions.autoplayButton
: Boolean; enables/disables autoplay button.autoplayButtonOutput
: Boolean; controls the autoplay button output.autoplayPosition
: String; position of autoplay button.Looping and Responsiveness:
loop
: Boolean; enables/disables infinite loop.responsive
: Object; defines responsive settings for different screen sizes.Accessibility and Miscellaneous:
lazyload
: Boolean; enables/disables lazy loading of images.speed
: Transition speed (milliseconds).startIndex
: Index of the starting slide (0-based).preventScrollOnTouch
: Boolean; prevent page scroll on touch.swipeAngle
: Maximum swipe angle to initiate slider transition.axis
: Axis of the slider (‘horizontal’ or ‘vertical’).animateIn
: Animation effect when items are entering viewport.animateOut
: Animation effect when items are leaving viewport.animateInElements
: Array of CSS selectors for elements to animate-in.animateOutElements
: Array of CSS selectors for elements to animate-out.onInit
: Callback function executed after slider initialization.onComplete
: Callback function executed when slider transition ends.onUpdated
: Callback function executed when slider is updated (e.g., by rebuild()
).Advanced Options (Consult full documentation):
Numerous other options exist for advanced customizations like custom easing, callbacks for various events, and fine-tuning the behavior of individual components.
The slider instance, returned by tns()
, exposes several methods for programmatic control:
goTo(index)
: Navigates to the slide at the specified index (0-based).next()
: Moves to the next slide.prev()
: Moves to the previous slide.destroy()
: Destroys the slider instance and removes all event listeners.rebuild()
: Rebuilds the slider, useful after dynamic content changes.getInfo()
: Returns an object containing information about the slider’s current state.getCurrentIndex()
: Returns the current slide index.getSliderSize()
: Returns an object containing size details of the slider.getSlideSize()
: Returns size details of the slides.getVisibleItemsNumber()
: Returns number of currently visible items.getUpdatedIndex(index)
: Returns updated index after applying loop.resetSlider()
: Resets the slider to initial state (as defined by options).updateSlider()
: Updates the slider settings based on new options provided.Tiny Slider dispatches custom events on the slider container element. These events provide callbacks for various slider actions:
tns:loaded
: Fired when the slider is fully initialized.tns:transitionStart
: Fired when a slide transition begins.tns:transitionEnd
: Fired when a slide transition ends.tns:indexChanged
: Fired when the current slide index changes.tns:playing
: Fired when autoplay starts.tns:paused
: Fired when autoplay pauses.tns:destroyed
: Fired when the slider is destroyed.tns:updated
: Fired after updateSlider
method is called.These events can be listened for using standard DOM event listeners (addEventListener) or any appropriate library method (e.g., jQuery’s on()
). They allow reacting to slider state changes and integrating custom functionality. Remember that event names are case-sensitive. Consult full documentation for details on parameters passed with each event.
We welcome contributions to Tiny Slider! Whether it’s fixing bugs, adding features, or improving documentation, your help is appreciated. Before contributing, please take a moment to review these guidelines.
Clone the repository: Fork the Tiny Slider repository on GitHub and clone your fork to your local machine.
Install dependencies: Navigate to the project directory and install the necessary packages using npm or yarn:
npm install
or
yarn install
Start the development server: Tiny Slider uses a development server for live reloading during development. Start the server using:
npm run dev
or
yarn dev
This will start a local web server and open the Tiny Slider demo page in your browser. Changes you make to the code will be automatically reflected in the browser.
Tiny Slider uses [testing framework name, e.g., Jest] for testing. To run the tests, execute the following command:
npm test
or
yarn test
Before submitting a pull request, ensure all tests pass. Adding new tests for any changes you make is highly encouraged.
Tiny Slider follows [specific coding style guidelines, e.g., Airbnb JavaScript Style Guide]. Please ensure your code adheres to these guidelines before submitting a pull request. Consistent formatting helps maintain readability and maintainability. Using a code formatter (e.g., Prettier) is recommended to automate formatting.
Create a new branch: Create a new branch from the main
branch for your changes. Use descriptive branch names (e.g., feature/add-new-option
, bugfix/resolve-issue-123
).
Make your changes: Implement your changes and ensure they are thoroughly tested.
Commit your changes: Commit your changes with clear and concise commit messages. Follow conventional commit message format (e.g., feat: add new feature
, fix: resolve bug
).
Push your branch: Push your branch to your forked repository on GitHub.
Create a pull request: Create a pull request from your branch to the main
branch of the Tiny Slider repository. Provide a clear description of your changes and address any feedback provided by the reviewers.
Remember to follow the project’s contribution license agreement (CLA). We appreciate your contributions and look forward to reviewing your pull request!