Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add or Append HTML inside of a Polymer Element's template from Javascript

Tags:

polymer

In an attempt to get carousel functionality working inside of a Polymer element, I am programmatically creating the markup needed for the Slick carousel inside of my element's script. Assume in this code snippet that this.videos has already been loaded as an array of objects that contain youtube video information, specifically an id and name property:

// Create Carousel Container
var carousel = $('<div id="carousel"></div>');

// Add Slides
this.videos.forEach(function(element, index, array){

    // Create a template for each slide
    var slideTemplate = $('<div><iframe width="420" height="315" src="//www.youtube.com/embed/' + element.id + '" frameborder="0" allowfullscreen></iframe></div>');

    // Append Each Slide to the Carousel
    slideTemplate.appendTo(carousel);

    // jQuery Method
    $('#carousel').appendChild("<div></div>");
});

Neither of the "append*" methods above are working, and the resultant DOM contains no div#carousel element. What is the proper way to add HTML to a Polymer element's template?

Here is a previous SO question I asked that explains why I have to attempt this method of injecting markup inside the element from javascript. It has to do with that lingering template tag in the markup > look under UPDATE 2 for the full run-down.

like image 711
eriklharper Avatar asked Sep 08 '26 20:09

eriklharper


1 Answers

There's no reason to write code :) The best way to do this is use Polymer's data-binding features rather and setup the DOM template ahead of time. In general, you should never need to touch the DOM like this. Here's the basic idea:

<div id="carousel">
  <template repeat="{{v in videos}}">
    <div><iframe src="//www.youtube.com/embed/{{v.id}}"></iframe></div>
  </template>
</div>

When this.videos is populated, the template engine will automatically stamp the markup for you.

like image 174
ebidel Avatar answered Sep 13 '26 01:09

ebidel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!