@@ -316,6 +316,55 @@ btn_open_dialog = button("Open Dialog", title='open dialog button', draggable=Tr
316
316
Many elements are meant to be container elements and have children under them.
317
317
` pyweb.ui.elements ` provides 2 mains ways to add children to an element:
318
318
319
+ ##### adding children to an element after creation
320
+
321
+ Moving elements around and adding children to an elements is a very common use case.
322
+ It's possible to add new elements to an existing element by simply using the
323
+ ` append ` method. For instance, let's rewrite the example above to add the button to
324
+ the div after element creation and actually append the div to the body of the page.
325
+
326
+ ``` python
327
+ # This will change the text of all H1 elements in the page
328
+ from pyweb import pydom
329
+ from pyweb.ui.elements import button
330
+
331
+ btn_open_dialog = button(" Open Dialog" , title = ' open dialog button' , draggable = True , style = {margin: ' 5px' })
332
+ page_div = div()
333
+ page_div.append(btn_open_dialog)
334
+ pydom.body.append(page_div)
335
+ ```
336
+
337
+ ##### mapping elements to events
338
+
339
+ As mentioned above, ` pyweb.ui.elements ` is built on top and fully compattible
340
+ with ` pyscript ` built-ins and ` pydom ` . For this reason, the best way to
341
+ attach event handlers to an element is to simply use the ` @when ` decorator
342
+ provided by ` PyScript ` . So, just like before, let's rewrite the example above
343
+ to change the background color of the button when the button is clicked.
344
+
345
+
346
+ ``` python
347
+ import random
348
+ from pyweb import pydom
349
+ from pyweb.ui.elements import button
350
+
351
+ btn_open_dialog = button(" Open Dialog" , title = ' open dialog button' , draggable = True , style = {margin: ' 5px' })
352
+ page_div = div()
353
+ page_div.append(btn_open_dialog)
354
+
355
+ def random_color ():
356
+ """ returns a random string representing and rgb color"""
357
+ rgbl= [255 ,0 ,0 ]
358
+ return tuple (random.shuffle(rgbl))
359
+
360
+ @when (' click' , btn_open_dialog)
361
+ def change_background_color (event = None ):
362
+ # assign a random RGB color
363
+ btn_open_dialog.style[' background-color' ] = random_color()
364
+
365
+ pydom.body.append(page_div)
366
+ ```
367
+
319
368
320
369
##### specifing the children of an element during creation
321
370
0 commit comments