javascriptjquerypolymerweb-componentpolymer-elements

How to change a property of a polymer element with jquery? (to fix app-drawer glitch on load)


I have an app-drawer in my code:

<app-drawer-layout fullbleed force-narrow>
<app-drawer swipe-open opened="{{drawerOpened}}">
   ...
</app-drawer>

And the drawer always glitching (opens and closes) for like 0.2 second while site is loading its shell (app-toolbar, app-drawer, etc.). I can see these glitches in the edge and firefox (sometimes) browsers.

So I decided to fix it by adding visibility:hidden:

<app-drawer swipe-open opened="{{drawerOpened}}" style="visibility:hidden;">
   ...
</app-drawer>

and make is visible again in 2 seconds after the page's shell is loaded(-ish):

  setTimeout(function(){
        $(document).ready(function() {
            $("app-drawer").css( "visibility", "visible;" );
        });
    },2000);

But this jquery code does not making it visible.

While searching the internet I found that I need to use Polymer.dom(this.root).querySelector instead of using $("app-drawer"), but I have no idea how to implement it in this code, since I'm a beginner. Any help?


Solution

  • Depends where you app-drawer is defined.

    If it is directly in your first level of < body >, you can access it with jquery (by ID, class, tagname w/e).

    <script>
      window.addEventListener('WebComponentsReady', function(e) {
        // imports are loaded and elements have been registered
        $("app-drawer").css( "visibility", "visible;" );
      });
    </script>
    

    If your app-drawer is in a custom element, you need to pass the shadow root (because jQuery is not looking into shadow root via selector).

    You can pass the shadow root and reach the element by using polymer dom functions. Just get a reference to the element where your app-drawer is defined and have a look to the $ variable.

    document.querySelector("#YOUR-ELE-AROUND-APP-DRAWER").$.appDrawerID.style.visibility = "visible";
    

    https://www.polymer-project.org/1.0/docs/devguide/local-dom#node-finding

    Third solution can be to use jquery directly inside your custom element where app-drawer is defined and access it.

    ready: function() {
          // access a local DOM element by ID using this.$
          $("app-drawer").css( "visibility", "visible;" );
        }
    

    https://www.polymer-project.org/1.0/docs/devguide/registering-elements#ready-method

    Example fiddle: https://jsfiddle.net/PatrickJaja/55cbdft5/