This document shows how easy it is to build a UI with VanJs and Bootstrap.
Using simple examples, this document demonstrates how the library is used. The integrated form generator allows you to create a basic template for your forms.
Why to use VanJs
VanJS (Vanilla JavaScript) is used primarily because it is the world's smallest reactive UI framework, packing modern framework features into an ultra-lightweight, 1.0kB bundle. It bridges the gap between pure vanilla JavaScript and heavy frameworks like React, allowing you to build reactive web apps instantly without complex tooling.
Why to use Bootstrap
Bootstrap is used because it dramatically speeds up web development by providing a ready-made library of responsive, mobile-first UI components. Instead of writing thousands of lines of custom CSS and media queries from scratch, developers can rapidly build complete, functional layouts simply by dropping predefined classes onto HTML elements.
Why to use vanjs-bootstrap
Using vanjs-bootstrap is a great choice if you want to build highly responsive, modern UI applications with Bootstrap while keeping your JavaScript bundle size as small as humanly possible.
Developed as a community add-on, vanjs-bootstrap serves as a bridge between VanJS (the world's smallest reactive UI framework at just 1.0kB) and the popular Bootstrap CSS utility library.
Key Alternatives Compared
Strategy
Framework Footprint
Learning Curve
Ideal For
vanjs-bootstrap
~1.0kB + CSS
Minimal (1 hour)
High-performance miniapps, ultra-lean web tools
React Bootstrap
~42kB+ (React DOM)
Steep (JSX + Build steps)
Large enterprise web apps with pre-existing React codebases
VanUI
Custom / Very Low
Low
Vanilla VanJS
Credits
A big thank you to Tao Xing for his excellent product VanJs.
I would like to thank Geoffrey Emmans, an excellent full stack developer, who supported the work on this app
Thanks also to the countless programmers around the world who have done the preparatory work with browsers, JavaScript NodeJs and so on for many years.
Button
export function Button ({bsSize, class, color='secondary', outline, dropdown, ...props}, children)
Let’s start with the Button component to understand the underlying principle of this component library.
The Button is a function structured like a VanJS tag; it returns an HTML element. The first argument is an object containing attributes, while subsequent arguments represent the children.
In essence, these attributes and their values are passed on to the resulting HTML element. However, certain attributes serve specific functions, altering the appearance or behavior of the HTML element.
A simple example is the 'bsSize' attribute: if its value is set to 'sm', the class 'btn-sm' is added to the element.
Most of these specialized attributes can be of the 'van.state' type, allowing you to remotely control the component's appearance within the document. You can try this out for yourself in the demo below.
The FormBuilder is arguably the most important feature in this library. It simplifies the creation of forms to the greatest possible extent. The individual steps for using it are:
Create a FormBuilder with function FormBuilder(args)
Start a new row with addRow(class)
Add a form group with label and input control with add(props)
Add the form into dom tree with variable dom
Add a listener for changes with onChange((name,value,event)=>{})
Check form validation with getFormValid() when onvalidate is used in add
Basic Form
const { div, pre } = van.tags;
// create a display for valuesconstValueDisplay = pre({class:'mt-2 p-2 bg-body'});
// create a form builderconst fb = vanB.FormBuilder({
// set initial valuesvalues: {name:'Jack', email:'jack@black.com'}
})
// add a change event
fb.onChange( () =>ValueDisplay.innerHTML = JSON.stringify(fb.values) )
// add a input control// only 'name' and 'label' are required
fb.add({label: 'Name', name: 'name'})
// add a second field with 'type'
fb.add({label: 'Email', name: 'email', type: 'email'})
// add element
fb.addChildren( ValueDisplay );
// append the form to demo container
container.appendChild( fb.dom )
// show values in ValueDisplay
fb.emitChange() // display values
html
Horizontal Form Grid
The specification cols: '2 4' allocates 2 units for the label and 4 units for the input. The 'autoRow' setting eliminates the need to call 'addRow'; 'addRow' is invoked automatically after 12 units.
Optional add a listener function(name,value) for input change
FormBuilder Properties
Properties inherited from FormControl.
property
comment
values
input values as object {name: value,..}
onChange(func)
Subscribe input value change events. func=function(name,value,event)
emitChange(name, value)
Notify change to all subscribers
handleInput(event)
input element oninpup(event) handler
args(props)
Function returns completetd props for a input control. Generate 'value', 'oninput' and 'name'.
Own properties.
property
comment
dom
Container for the form groups to be inserted. You can 'van.add' something here
row
Actual row element
rowClass
Default row class
cols
Default cols attribute for inserted groups
autoRow
If true, will add a new row if the columns in a row exceeds 12
colCount
Number of colums in actual row
id
Form tag id
add(props, ...children)
The main function used to insert a form group.
addRow(arg)
Add a new row with ...args injected. i.e. addRow({class: "m-2"})
addChildren(...children)
van.add(fb.row ?? fb.dom, ...children).
getFormValid()
Function returns true/false when all input values are valid. Can be used as Button disabled value
setValues(values)
update a set of field values in the form (experimental)
groupIdByName( name ) inputIdByName( name ) labelIdByName( name )
helpers to get the generated id's
getInputElement (name)
get the input element by field name
Function add(props, ...children)
The main function used to insert a form group.
The props argument decides how the inserted form group is created.
The further arguments are added as an appendix to the input component.
Children are some form-text or validation info
Add Properties
property
comment
name
string becomes input name
label
string or function becomes a label component
type
Type attribute for the input control
oninput
Optional for special usage. Is generally generated automatically
input
a input control alternative to type. See Custom Input
class
class added to the enveloping group
inputClass
class added to the input control
bsSize
Bootstrap size
cols
space separated string "left right" for the Bootstrap column sizes i.e. "3 6"
col
Bootstrap column size of the group alternative to cols. Used for form class "row g-3"
id
HTML id of group. Will get random id if omited. Label id is "formId-id-l", input id is "formId-id-i"
separated
special for FormCheck. Separate label and check if true
isvalid
Boolean, adds :is-valid or :is-invalid to input class
onvalidate
function(value) {return value_is-valid }. Add a validation check for input and add isvalid argument
You can indicate invalid and valid form fields with .is-invalid and .is-valid.
For simplicity, the isvalid attribute can be used. Since this can also be a van.state, dynamic validation is possible.
Or even simpler, you pass a function onvalidate then the FormBuilder automatically creates an isvalid attribute. You can then use the FormBuilder function getFormValid to check whether all fields are valid.
onvalidate functions takes a value as argument and returns true/false.
The next example uses a better e-mail validation and a complex password validation.
functionDynamicValidation() {
const {div, ul, li} = van.tags;
const { Button, FormBuilder } = vanB;
constrequired = v => !!v;
constisEmail = v => {
var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(v).toLowerCase());
}
const fb = FormBuilder({ rowClass: "mb-2", autoRow: true, cols: "3 6" });
fb.add({label: "Name", name: "name", type: "text", onvalidate: required});
fb.add({label: "E-mail", name: "email", type: "text", onvalidate: isEmail},
div({class: "invalid-feedback"}, "Please enter a valid E-mail."),
div({class: "valid-feedback"}, "Looks good!")
);
fb.add({label: "Password", name: "password", type: "password",
onvalidate: v => {
let regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@.#$!%*?&])[A-Za-z\d@.#$!%*?&]{8,15}$/;
return regex.test(v)
}
},
div({class: "valid-feedback"}, "Looks good!"),
div({class: "invalid-feedback"}, "Password must include", ul(
li("At least one lowercase alphabet i.e. [a-z]"),
li("At least one uppercase alphabet i.e. [A-Z]"),
li("At least one Numeric digit i.e. [0-9]"),
li("At least one special character i.e. [‘@’, ‘$’, ‘.’, ‘#’, ‘!’, ‘%’, ‘*’, ‘?’, ‘&’, ‘^’]"),
li("Also, the total length must be in the range [8-15]")
)
));
fb.add({label: "Agree to terms and conditions", name: "agree",
type: "checkbox", onvalidate: required },
div({class: "invalid-feedback"}, "You must agree before submitting.")
);
constsubmit = () => modal.Modal({
header: "Submited",
body: JSON.stringify(fb.values),
width: 'fit-content',
}).open();
constBtn = Button({color: 'primary',
disabled: () => !fb.getFormValid(),
onclick: submit,
}, "Submit");
returndiv(
fb.dom,
div({class: "col-12 m-3"},
Btn,
),
);
}
container.appendChild(DynamicValidation())
Form Controls
The individual Bootstrap form controls are implemented within the library and can also be used independently. However, since they all essentially serve the same purpose (namely, acting as a user interface for a value within the program) they are simply specified via the "type" parameter within the FormGroup or FormBuilder's 'add' function.
The 'add' function uses the 'typeMap' to find the component for a type.
typeMap
type
component
'text'
Input
'textarea'
Input
'select'
SelectInput
'radioselect'
RadioSelectInput
'checkbox'
CheckboxInput
'radio'
RadioInput
'switch'
FormCheckInput
'combobox'
ComboboxInput
A special feature of SelectInput, RadioSelectInput and ComboboxInput is that the options are not specified as children, but as an attribute "options". The value here is a list. See selectOptions for details.
The 'ComboboxInput' was changed in version 1.2. The new one do not use Bootstraps popper and has a better keyboard handling.
The listed parameters are checked against 'van.state' and can therefore be dynamic. Other parameters in 'props' are simply passed through.
You can find the function and appearance of the components in example Form Layout
Custom Input Control
In order to build your own input field, you should consider the following points.
The outer "div" must have the class "form-control". It is ideal to take into account the argument "bsSize" which leads to the classes "form-control-sm" or "form-control-lg".
The "value" argument is used for initialization.
Changes are sent via the "oninput" argument with an "event" as a parameter. Within this library, a fake "event" in the form "{target:{name,value}}" is usually sufficient.
To keep the component dynamic, "van.val()" can be used
This shows how to program an input field to select an alignment. The field should select the string values "left", "right", "center" or "justify". This is followed by a small demonstration form. In the form the field is specified as "input". The specification of “type” can be omitted.
function selectOptions (list, dom=false, selected)
The form controls in this library use the selectOptions function. It converts different kind of lists into a uniform format {value, children} that can easily be mapped into a DOM as <option> elments.
Is the parameter "dom" "true", the function returns a ready mapped dom option list.
The "list" parameter accepts four notations:
'TextValue1,TextValue2'
a komma separated list
['TextValue1', 'TextValue2'...]
a array of values
[['Text1', Value1], ['Text2', Value2]...]
a array of display / value pairs
[ { value: 1, ['children' || 'text' || 'displayValue'] }
a array of objects
Notations can be mixed inside a array.
For example [ '', ['text 1', 1], ['text 2', 2] ] will be converted to:
Icons, the small images used on buttons or in the text, make the UI appealing and clear. One or more libraries such as Font Awesom, Bootstrap or Simple Icons serve as the source. However, it is not uncommon for additional icons to be required that you create yourself, such as your own logo.
This library contains simple functions for displaying and managing icons from different sources.
Create a HTMLElement to display a small (1em by default) image.
The value of 'size' is a 'style' value and applies to 'width' and 'height', for example '16px', '2.5em', '60%' or 'inherit'. Other '...props' like 'class' or 'style' are passed on.
First argument is
the key to an image registered with {@link setIcon}
a UTF-8 char
a SVG string
a object with property 'src' to a image url
a HTMLElement or a Icon function
a Font Awesome class
example key of icon in iconMap
The 'editItem' was registered with setIcon('editItem', '<svg ...'
It is recommended to register the icons in the iconMap with a name and use them in the program under that name. For better organization, you can register them in a JavaScript file that is imported into the main program. Here is an example.
When SVG icons are used frequently on a page—such as the "copy" button on this site—it makes sense to use a sprite. This is where spriteify comes in. The function returns a sprite containing all the SVGs defined in the iconMap and converts the registered SVGs into references. This sprite can then be appended to the <body> element.
function spriteify (options)
This function is experimental
options:
idPrefix = 'icon-',
svgClass = '',
prettify = false
const {Icon, iconMap, setIcon, getIcon, spriteify } = vanB
const map = newMap(iconMap);
const before = map.get('editItem')
const sprite = spriteify({prettify: true, map})
const after = map.get('editItem')
// make outputconst { div, h5, pre } = van.tagsconst output = div(
h5('The sprite'),
pre(sprite),
h5('Icon before spriteify'),
pre(before),
h5('Icon after spriteify'),
pre(after)
)
container.appendChild(output);
Navbar
This component simplifies the use of the Bootstrap navigation bar.
"Navbar" is a handy tool for quickly putting together a main menu. It’s easy to get lost in the multitude of HTML tags, but a great feature here is that the actual menu can be defined separately—using a JSON-style format—and swapped out as needed. The example is fairly self-explanatory, but for the sake of clarity, here are the options explained in detail.
Navbar Arguments
function Navbar({class: clas, sticky = true, menu, ...props})
class
optional class string or van.state for the <nav> element
sticky
add 'sticky-top' to class
menu
The "menu" is an object with properties "brand", a dom element and "items", the array of menu items. "items" can be nestet for one level.
NavItem Arguments
function NavItem({href='#', label, items, level=0, Comp, hidden=false, ...props})
The object "item" is passed as an argument to the function "NavItem".
label
A string, function or van.state
href
Optional url, default is void(0)
items
A array of items. The "NavItem" is a submenu when set
Comp
A optional function returning a van dom, preferably a "NavLink" element
All properties are passed to the function as an argument
hidden
item is not visible when true
active
Add "active" to class when true.. Can be a van.state.
disabled
Add "disabled" to class. Can be a van.state.
divider
Shows a divider in submenu
...props
Additional properties are passed on
NavLink
function NavLink({label, class: clas, active, disabled, divider, level=0, ...props})
Returns a <a class="nav-link" /> and can be used for custom items like the "ToggleTheme" in example.
Modal functions are removed from vanjs-bootstrap since version 1.2 because it pulls the bootstrap.js and popoer and can not be used in backend without a DOM. Install it like:
install * from modal from "vanjs-bootstrap/modal"
ModalFrame
export function ModalFrame (options)
The function ModalFrame creates a complete modal dom struture like:
<divclass="modal fade"id="exampleModal"tabindex="-1"aria-labelledby="exampleModalLabel"aria-hidden="true"><divclass="modal-dialog"><divclass="modal-content"><divclass="modal-header"><h1class="modal-title fs-5"id="exampleModalLabel">Modal title</h1><buttontype="button"class="btn-close"data-bs-dismiss="modal"aria-label="Close"></button></div><divclass="modal-body"><p>Modal body text goes here.</p></div><divclass="modal-footer"><buttontype="button"class="btn btn-secondary"data-bs-dismiss="modal">Close</button><buttontype="button"class="btn btn-primary">Save changes</button></div></div></div></div>
With "ModalFrame" you only need to specify the van functions for header, body and footer:
backdrop
boolean, default true.
Includes a modal-backdrop element.
Alternatively, specify static for a backdrop which doesn’t close the modal when clicked.
focus
boolean, default true
Puts the focus on the modal when initialized.
keyboard
boolean, default true
Closes the modal when escape key is pressed.
dispose
boolean, default true
Dispose dialog on hide.
In addition to the dropdown menu, a popup menu and a context menu are also implemented based on the modal dialog. The MenuItem function simplifies the creation of menus.
The items are 'MenuItem' or simple objects.
This function returns a Modal object. Call function open(event) to show. Function open accepts the click event to open the menu at click position.
Demo
// import * as modal from 'vanjs-bootstrap/modal'// import * as vanB from 'vanjs-bootstrap'const {ContextMenu, MenuItem} = modal;
const {Button} = vanB
const {div, h3} = van.tagsconstdemo = () => {
const result = van.state("");
const menu = ContextMenu(
{label: 'Context Menu', header:1},
MenuItem({label: 'Menu Item', onclick:()=>result.val='Menu Item'}),
{label: 'Item1',onclick:()=>result.val='Item1'},
{label: 'Item2',onclick:()=>result.val='Item2'},
);
returndiv({class: "row"},
div({
class: "col-11 p-4 m-3 bg-body-tertiary border rounded-2",
oncontextmenu: event => menu.open(event),
},
h3('right click in this area to open context menu')
),
div({class: "col-3"}, () =>`Result: ${result.val}`),
)
}
container.appendChild(demo());
i18n
Translation tool. A very simple object for multilingual texts. The texts are stored in the variable 'dict' and are divided into language and chapter.
The current language is set with the 'setLanguage' function. The texts are retrieved with the function 't'. Texts are added with the 'addWords' function.
"i18n" is removed from vanjs-bootstrap. Ok it is realy tiny but do not belong here. But you can import it with
dict
object tree structured according to language, chapter and subchapter
getLanguage()
current language
setLanguage(newLanguage)
t('category.key')
returns the text of the current language to a key.
the key contains the category, the subcategory and the actual key, separated by a dot
tPath('category')
returns a t function for a category
addWords(words, [lang], [chapter])
inserts an object tree with texts into the dict
DragSort
A helper to sort a list per drag and drop. Since version 1.1 it is no more part of vanjs-bootstrap core and must imported separately
import dragSort from "vanjs-bootstrap/drag-sort"
export function dragSort (list, setList)
list: array to be sorted
setList: function to store reordered list
Function DragSort returns an object with all required function. The function dragProps of the object can inject all html attributes like draggable, ondragstart and so on.
The function used to be a React Hook, but works great in VanJs and is now used in this library by TagInput.