Properties & Events

Adding Properties and Events

Properties

In previous page, we got to know how to write Weblabs Components, and adding children to them. But HTML can do a lot more than that, like adding attributes such as classes and ids.

Weblabs can do all those too! but in some unique ways!

Weblabs's native function returns a WeblabsElement object that has methods such as id(), prop(), event(), class(), and so on to add additional properties to the original element

<p id="paragraph">Hello World</p>

In Weblabs, it would look something like this

import { p } from '@weblabsjs/core/components'

p("Hello World").id("paragraph")

Now let's add some classes

import { p } from '@weblabsjs/core/components'

p("Hello World").class("name1 name2", "name3")

But that is not what Weblabs is limited to. You can easily combine these methods and add Ids and Classes at the same time

import { p } from '@weblabsjs/core/components'

p("Hello World").id("paragraph").class("classname1")

The order at which the classes and ids are called are insignificant, that is the above code can be written as below as well

import { p } from '@weblabsjs/core/components'

p("Hello World").class("classname1").id("paragraph")

Note: Avoid calling class method as recursive methods, because each of the names will be assigned and it will be a bit problematic to connect to a specific one

p("Hello World").class("classname1")
    .class("classname2")

//p will have two classes classname1 & classname2

This does not means you cannot have classes on nested components. Make sure there is no more than one nesting of class to the same component

Events

Events are one of the most critical part for interactivity. Weblabs uses the same approach as above to make your webapp interactive as the most easy way as possible.

The event() method binds a component to events and callback functions very easily. The event method is available for any Weblabs components (even custom ones) and they are very simillar to the addEventListener() method in javascript

Let's see some example

import { button } from '@weblabsjs/core/components'

button("Click Me")
    .event("click", () => { 
            alert("I was clicked") 
        }
    )

As you can see, we used the click event and a callback function to create an event. You can chain multiple of such events, and even custom events that you may create which might do something.

To learn about different events, visit: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events

Last updated

Was this helpful?