Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting src of <img> in a Polymer Element

Below is the code for my polymer element I have tried normal dom binding with and everything works fine

The src of the img however does not work. I checked the html in chrome dev tools and it showed the src all wrong

The src here says /img/12.jpg which means the image is in the folder the html file is in It however refers to the root of the folder instead

Expected src in dev tools: http://localhost:3000/elements/image-hover/img/12.jpg

Observed src: img/12.jpg

What can I do insted of harcoding it to the expected src?

<dom-module id="image-hover">
             <template>
                <img src="{{imgsrc}}"/>
             </template>
        </dom-module>
        <script>
          (function() {
            Polymer({
              is: 'image-hover',

              properties: {
                imgsrc: {
                    type: String,
                    value: 'img/12.jpg'
                }
              }
          });
          })();
       </script>

Edit: I have solved this issue by using the content tag provided by polymer.

<content id="image" select="img"></content>

The question still remains how can I figure out the source of the folder the element is in.

like image 707
TMess Avatar asked Jan 09 '23 06:01

TMess


2 Answers

You can do the following:

<dom-module id="image-hover">
    <template>
        <img src="{{imgsrc}}"/>
    </template>
</dom-module>
<script>
    Polymer({
        is: 'image-hover',

        properties: {
            imgsrc: {
                type: String,
                value: function () {
                    return location.host + "/img/12.jpg";
                }
            }
        }
    });
</script>

The value is now a function that returns a String using the location object. More information can be found on that here. Put simply, it contains information about the current URL.

like image 102
Ben Thomas Avatar answered Jan 18 '23 20:01

Ben Thomas


You can use this.resolveUrl as follows:

          properties: {
            imgsrc: {
                type: String,
                value: function() {return this.resolveUrl('img/12.jpg')}
            }
          }
like image 20
chapulina Avatar answered Jan 18 '23 22:01

chapulina