Search code examples
javascriptweb-componentshadow-domcustom-element

Javascript on click focus latest element with multiple customelements


I have a customelement WebDesktop that can create another customelement AppWindow.

If I create several AppWindow I would like the one I clicked the last to be "focused" when it's created but also that if I click on an already created one it should be focused above the others , it should have a higher z-index.

Is there any way to do this? I don't understand how each already created AppWindow can see how many new elements has been created since it was intially created.

My solution would be to put the zIndex to the amount of current amount of created AppWindow Can each instanced customelement somehow find out how many new elements has been created or something like that? And also keep track if they have been removed?


Solution

  • Here are some techniques that can help

    Closest element UP the dom

    let desktop = this.closest('web-desktop')

    This standard method on every element get's you the desktop an AppWindow is in

    If your AppWindows have shadowDOM the above method will not work,
    as it does not "break out" of shadowDOM

    To pierce through shadowRoot(s) use .closestElement() from: Custom Element getRootNode.closest() function crossing multiple (parent) shadowDOM boundaries

    count children

    Once you know the desktop your AppWindows are in desktop.children
    which you can convert to an Array with [...desktop.children]

    If you have other DOM elements in .children your AppWindows are:
    [...desktop.querySelectorAll('app-window')]

    then [...desktop.querySelectorAll('app-window')]`.length is your AppWindow count

    going fancy with a live HTMLcollection

    The above get you static collections

    desktop.getElementsByTagName('app-window')

    gets you a live HTMLcollection, which can be helpfull: When is NodeList live and when is it static?

    In the Desktop constructor you do:

    this.windows = this.shadowRoot.getElementsByTagName('app-window')

    and a Getter method in Desktop:

    get windowcount(){
      return this.windows.length;
    }
    

    So in an AppWindow constructor you can do:

    let AppWindowIndex = this.closestElement('web-desktop').windowcount + 1;
    

    disclaimer: all off the top of my head, might have made some syntax errors!