I'm having problems adding a CSS class to a jQuery created element inside of a Polymer component.
Here is the Polymer component:
<dom-module id="image-add">
<style>
.image {
height: 100%;
}
</style>
<template>
<div id = "container">
</div>
</template>
<script>
Polymer({
is: "image-add",
properties: {
images_to_add: {
type: Array
}
},
ready:function(){
var shadowRoot = this.shadowRoot || this;
var container = $(shadowRoot).find('#container');
var new_image = $("<div></div>")
new_image.css({"background-image":"url('" + this.images_to_slide[1] + "')"})
new_image.addClass("image");
new_image.appendTo(container);
}
});
</script>
</dom-module>
As you can see im passing in an array of images into the Polymer component which im using to place in the background of a dynamically added div with the help of jQuery. Now jQuery then adds the class of "image" to the dynamically added div but the problem I face is I don't see the effects of adding that class. i.e. the div doesn't go to a height of 100%. and when i inspect the div it has the class but no effects of the class.
Why isn't the effects of the class being applied to this dynamically added div? I'm guessing it has something to do with Polymer as normally this would work.
PLEASE NOTE: I have to be able to generate these divs at any point in time dynamically. And the background image style is being applied fine already.
You don't need jQuery for this. You can do it much more simply with pure polymer using the <template is="dom-repeat">
tag. This is more declarative and uses the native <img>
tag which is more in keeping with the polymer philosophy. It's also far fewer lines of code. Here's a working example with some adorable kittens.
<dom-module id="image-add">
<template>
<template is="dom-repeat" items="{{imageUrls}}" as="imageUrl">
<img id="{{calcImageId(index)}}" src="{{imageUrl}}">
</template>
</template>
<script>
Polymer({
is: "image-add",
properties: {
imageUrls: {
type: Array,
value: function() {
return [
'http://placekitten.com/g/200/300',
'http://placekitten.com/g/200/300'
];
}
}
},
calcImageId: function(index) {
return 'image_' + index;
}
});
</script>
</dom-module>
Now, adding another kitten dynamically is a snap.
document.querySelector('image-add').push('imageUrls', 'http://placekitten.com/g/200/300')
And there we have it, our third kitten.