DEV Community

artydev
artydev

Posted on • Updated on

DML and CSS in JS

Using DML and a CSS in JS library seems to be a perfect match.
Here I am using bss.

You can test it here DML&BSS


<html lang="de">
 <head>
    <meta charset="utf-8">
    <title>title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://efpage.de/DML/DML_homepage/lib/DML-min.js"></script>
    <script src="https://unpkg.com/bss"></script>
 </head>
 <body>
    <script>
     function Menu (list) {

         let hoverCls = b`
           background: deeppink;
           color: white;
           cursor: pointer;
         `

         let outCls = b`
           background: white;
           cursor: pointer;
         `

         let menuCls = b`
           border: 2px solid pink;
           width: 200px;
           margin: 5px
           padding: 0;
           list-style-type: none;
         ` 

         let itemCls = b`
           padding:10px;color:blue
         `

         function toggleCls(el, addCls, removeCls) {
           el.classList["add"](addCls); 
           el.classList["remove"](removeCls) 
         }

         function handleHoverOut (el) {
           el.onmouseover = () =>  { toggleCls(el, hoverCls, outCls)} ;
           el.onmouseout = () => { toggleCls(el, outCls , hoverCls) };
         }

         let menu = ul(list, {"class" : menuCls});

         for (let item of Array.from(menu.childNodes)) { 
           item.classList.add(itemCls)
           handleHoverOut(item)
         }

         return   menu; 
     }

     h1("DML & Bss (css in JS)", "text-align:center")

     Menu(["item1","item2","item3"])

     Menu(["item11","item22","item33", "item44"])

    </script>
 </body>
</html>


Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
efpage profile image
Eckehard

Lovely!

as you use mouseover and mouseout, there is no need to use a class. You are able to apply the attributes directly to the DOM elements:

  <script>
    function Menu(list) {
      let menu = ul(list, "border: 2px solid pink; width: 200px; margin: 5px; padding: 0; list-style-type: none;");
      for (let el of menu.childNodes) {
        el.onmouseover = (e) => {setAttributes(e.srcElement, "background: deeppink;color: white;cursor: pointer;") };
        el.onmouseout = (e) => { setAttributes(e.srcElement, "background: white;color: black;cursor: pointer;") };
      }
      return menu;
    }

    h1("DML & Bss (css in JS)", "text-align:center")

    Menu(["item1", "item2", "item3"])

    Menu(["item11", "item22", "item33", "item44"])

  </script>
Enter fullscreen mode Exit fullscreen mode
Collapse
artydev profile image
artydev Author

Ok, thank you Eckehard :-)