Search code examples
domonclickpolymer

Error in console while hiding the link on click through Polymer/Dom


Hi Stack Overflowians,

I want to hide the Click foo link when I click the same Click foo link.

I have the following code:

<dom-module>
    <div id="foo">
        <a href="#" onclick="toggle_visibility('foo');">Click foo</a>
    </div>

<script>
    Polymer({
        is: 'test-file',

        toggle_visibility: function(id) {
            var e = document.getElementById(id);

            if (e.style.display === "none") {
                e.style.display = "block";
            } else {
                e.style.display = "none";
            }
        });
</script>
</dom-module>

I get the error in Console tab when I click on Click foo link:

Uncaught ReferenceError: toggle_visibility is not defined at HTMLAnchorElement.onclick

I want the link to hide when clicked on Click foo link

Can anyone please help ?

Thanks in advance


Solution

  • In Polymer you declaratively add event handlers by using on- + the event name. So in your case that would be on-click, not onclick.

    Also, you will need to provide the name for a method, not to call it. So your a tag would become something like:

    <a href="#" on-click="toggle_visibility">Click foo</a>
    

    Since that doesn't pass a paramter you can find another way, like using a data- attribute, or maybe if the relationship to the anchor is the same every time just rely on the fact that the div is the parent node:

    toggle_visibility: function(event) {
        var e = event.currentTarget.parentNode;
    
        if (e.style.display === "none") {
            e.style.display = "block";
        } else {
            e.style.display = "none";
        }
    }
    

    UPDATE: also note that, if you go by using a method that would query for the element to toggle the display for, you will most likely have to query the shadowDom, not the document level. So

    var e = document.getElementById(id);
    

    would become:

    var e = this.shadowRoot.getElementById(id);