1.1.2 • Published 7 months ago
script-switch-content v1.1.2
Script Switch Content | JavaScript/TypeScript
Description
The script allows you to easily create content and switch between them using buttons.
And it also helps to understand the approximate principle of operation of such logic.
Setting
- Create 2 html tags and assign them an ID attribute. One element will be used for content navigation The second element will be used to define all available content
<div id="menu"></div>
<div id="contents"></div>
- In the menu element, create 2 buttons to switch content and a list in the middle for navigation buttons.
<div id="menu">
<button data-switch-btn-path="back">Back</button>
<ul></ul>
<button data-switch-btn-path="next">Next</button>
</div>
- Now we need to define the content and assign them unique identifiers data-content-id. And the attribute data-content-name to indicate the name of the content
<div id="contents">
<div data-content-name="Content 1" data-content-id="content-1">
Content 1
</div>
<div data-content-name="Content 2" data-content-id="content-2">
Content 2
</div>
<div data-content-name="Content 3" data-content-id="content-3">
Content 3
</div>
</div>
- Now you need to get references to all the necessary elements and call the SwitchContent constructor.
const menuElement = document.getElementById("menu");
const contentsElement = document.getElementById("contents");
new SwitchContent(menuElement, contentsElement);
- Done! You can also style buttons etc.
API
Attributes | Description |
---|---|
data-content-name: string | An attribute that takes the name of the content to create a button for navigating between the content |
data-content-id: string | An attribute that accepts a unique identifier for the content to search for to hide or show |
data-switch-btn-class: string | Assigns classes to buttons for content navigation |
data-switch-btn-path: "next" / "back" | Attribute for the content switch button, specifies the side to which the content will be switched |
End
The code will be improved and optimized over time. This is the first time I've written scripts like this, so I think it turned out well for the first time.
30.12.2024 The code has become more documented, and I think it helps some people understand approximately how to do the same.
Author
Github - MineGame01