The new function is the heart of ClearlyJS: it allows you to create HTML elements with attributes and children!
Parameters
JavaScript parameters
type: type of the HTML element (for example h1, div, etc...) or your own element name (for example message, setting, etc...)
attributes: the element's HTML attributes (and the attributes specified in )
...children: children of the element - each element in a new parameter
JSX parameters
In JSX the new function is different:
<type parameters> ...children </type>
Returns
the ClearlyHTML element
Examples
clrly.new("h1", {style: "color: red", class: "element", id: "myId"}, "hello");
<h1 style="color: red" class="element" id="myId">hello</h1>
Creates a new red title with the text: "hello"
clrly.new("div", {}, clrly.new("h1", {}, "Welcome to my app"));
This syntax is a little bit messy, isn't it?
var div = clrly.new("div");
clrly.new(h1, {parent: div}, "Welcome to my app");
With the "parent" attribute you can make the code a little bit easier to understand
<div>
<h1>Welcome to my app</h1>
</div>
JSX is always the best option - it makes the code much more readable
var div = <div></div>;
<h1 parent={div}>Welcome to my app</h1>
The "parent" attribute is available on JSX too!
Creates a new div and puts a title inside the div
More with JSX
JSX allows you to understand more of your code! Here are some examples of what you can do with it:
variables
You can insert a variable to a JSX element (and its attributes) by using curly brackets:
var x = 5;
<h1>x is {x}</h1>
Shows the value of x
var arr = ["hello", "world", "this", "is", "a", "list"];
for(var i = 0; i < arr.length; i++){
<p>{(i + 1)}. {arr[i]}</p>
}
Shows an array as a numbered list with a for loop
var h1 = <h1>Example</h1>;
<div>{h1}</div>
You can also insert an HTML element as a child of another element
var link = clrly.toFile("this is a blob apge");
<a href={link}>Click here</a>
Use the toFile function to create a link to a blob and then add the link in your app!
events
events and listeners - such as onclick can be assigned to JSX elements in a second:
(<button>Click me</button>).onclick = function(){
alert("hello world");
}
Assign an onclick event to a button that alerts "hello world"
return (ClearlyJS components)
JSX and ClearlyHTML elements can be returned from functions and make some super useful components:
var allMessages = <div></div>;
function message(title, content){
return <div parent={allMessages}>
<h1>{title}</h1>
<p>{content}</p>
</div>
}
Every time the function is called - a new div with the specified title and content is being made and assigned to the messages div!