Injecting CSS into a dynamically created element within a Polymer component using jQuery

Having an issue when trying to add a CSS class to a jQuery created element within a Polymer component.

The code for the Polymer component is as follows:

<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>

I am passing an array of images into the Polymer component, which I use to set as the background image of a dynamically added div using jQuery. Although jQuery successfully adds the class "image" to the dynamically created div, the effects of the class are not visible. The div does not adjust its height to 100%. Even after inspecting the div, the class is present but no changes are seen.

Why isn't the class affecting the dynamically generated div? It seems like there might be an issue related to Polymer since this should normally work without any problems.

NOTE: It's crucial that I can dynamically generate these divs at any given time. Also, the background image style is already being applied correctly.

Answer ā„–1

You can achieve the same result without using jQuery by utilizing pure polymer and the

<template is="dom-repeat">
tag. This approach is more declarative and aligns better with the polymer philosophy, utilizing the native <img> tag. Additionally, it requires fewer lines of code. Below is a functional example featuring some charming 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>

https://i.sstatic.net/hO8gT.jpg https://i.sstatic.net/hO8gT.jpg

By following this method, dynamically adding another kitten becomes effortless.

document.querySelector('image-add').push('imageUrls', 'http://placekitten.com/g/200/300')

With just a simple step, behold our third adorable kitten.

https://i.sstatic.net/hO8gT.jpg https://i.sstatic.net/hO8gT.jpg https://i.sstatic.net/hO8gT.jpg

Answer ā„–2

Here is a possible solution:

<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>")
            new_image.attr("style","background-image:url('" + this.images_to_slide[1] + "')"); // by doing this, you add inline style to the newly generated div
            new_image.addClass("image");
            new_image.appendTo(container);

        }
    });
</script>

I hope this helps solve your issue.

Answer ā„–3

It appears that to create the element, you must use the following code:

document.createElement('div');

Next, you need to assign it to a variable like this:

var new_element = document.createElement('div');

After that, you can manipulate it with jQuery by adding classes and styles:

var new_element = document.createElement('div');
$(new_element).attr("id","image_1").addClass("image animating").css({"background-image":"url('" + this.images_to_display[current_image_index] + "')"});

Once you have set up the classes, you can add the element to the Polymer DOM for them to take effect:

var new_element = document.createElement('div');
$(toPlaceInDom).attr("id","image_1").addClass("image animating").css({"background-image":"url('" + this.images_to_display[current_image_index] + "')"});
Polymer.dom(this.$.container).appendChild(new_element)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Change the classes of the body prior to the initial rendering

I know this may seem like a difficult task, and I understand that what I want to achieve might be nearly impossible. My goal is to incorporate a dark/light mode switch on my website. The challenge lies in the fact that the site consists of static files on ...

What could be causing this issue where the call to my controller is not functioning properly?

Today, I am facing a challenge with implementing JavaScript code on my view in MVC4 project. Here is the snippet of code that's causing an issue: jQuery.ajax({ url: "/Object/GetMyObjects/", data: { __RequestVerificationToken: jQuery(" ...

What is causing find_by_css to return nothing when using nth-child?

Currently, I am facing an issue when trying to extract the "href" link from the following HTML code: https://i.stack.imgur.com/Gtzf4.png This is the code that I'm using: from selenium import webdriver from splinter import Browser from bs4 import Be ...

Issues with implementing @font-face on a singular font

I've encountered an issue while setting up a website for a client concerning the fonts. Most fonts are displaying correctly, but there is one font, "chunkfive", that is not working as expected. The problem becomes more severe in Internet Explorer wher ...

What could be causing the lack of data to be returned by jQuery.getJSON?

I've come across this method: function getUserName(guid) { var name = "Unknown"; $.getJSON(urlCurrent, { "method" : "get_user_info", "guid" : guid, "auth_token" : temporaryAuthToken }, function(data) { if ...

Difficulties in Adjusting the Size of Three Image Columns within a Website's Body

While working on my website layout, I encountered a problem with inserting three image columns in the body section. The images turned out to be too large and extended beyond the footer. Moreover, the third image was larger than expected, dominating the web ...

Bootstrap: Create a square by setting the height equal to the width of the .span2 element

I'm looking to create a div that is the height of a ".span2" (essentially a square) and is also responsive. Here's what I have so far: <div class="span2 square>Hello</div> .span {height: @span2;} However, I haven't been able to ...

Using Ajax to update a MySQL database with an array from jQuery

I need some assistance in updating a MySQL table using data from a jQuery array through AJAX. I've tried searching for similar issues without any luck, possibly due to my lack of familiarity with the correct terms in web development and coding. Allow ...

Parallax Effect in CSS Background

I am currently working on my website at and have implemented a "parallax-bg" class to create a parallax background effect. Interestingly, the parallax effect is working flawlessly for the hero section at the top and the texture in the middle, but it&apos ...

Ways to patiently wait in a for loop until the ajax call is completed

I am a beginner in web development and currently working on a small website project that involves using ajax to display new comments. Below is the function I have created: function show_comments() { $('div#P_all_posts>div').each(function () { ...

Exploring the inner workings of a JSON with Ajax and PHP

I'm working on a project that involves a JSON file called items.json. My goal is to create a search box where users can input either the name of an item or its category, and see live search results as they type. Here's what Iā€™m aiming for: If ...

Tips on adding a date range selection or multi-date selection capability within a single Kendo calendar

Can a single Kendo calendar instance incorporate both date range selection and multi-date selection features? ...

Looking to activate a button only when the checkbox is selected and in an enabled state

I'm struggling to make the button enable when the checkbox is checked and enabled. Additionally, it should be dependent on the textarea scroll above it. Once the checkbox is checked, the page needs to scroll up and down to activate the button. Here& ...

Is it possible to combine numerous -webkit-transition animations in my css code without using keyframes?

I'm experimenting with chaining multiple -webkit-transition animations in my CSS without using keyframes. I understand it's possible to achieve this by calling a keyframe animation, but I prefer to simply overwrite the properties. However, for s ...

Is there a way to use a Google Chrome command line switch to simulate the dimensions of a

Seeking information on the available Google Chrome command line switches for emulating device sizes. Specifically, I need to test a component that utilizes CSS @media queries for min-device-width/min-device-height. Previous attempts with --window-size an ...

Having trouble getting the CSS class to work in MVC4 with jQuery implementation

I recently created a view page where I implemented some jQuery code: <script type="text/javascript"> $(document).ready(function () { var hdrname = $('#headername').text(); alert(hdrname); if (hdrname == "Pending Assignment") { ...

Tips for utilizing fontawesome effectively in a select menu

I'm having trouble displaying fontawesome icons in a select element, as they do not appear correctly in the drop-down list. .FontAwesomeSelect { font-family: Font Awesome\ 5 Free; font-size: 18px; } <link href="https://use.fontaw ...

What is the method for obtaining the value of a label?

<div id="xyz"> <table id="quantityTable"> <tr> <td> <asp:Label ID="qtyValue" runat="server"></asp:Label> </td> </tr> </table> </div ...

Is there a way to showcase a block of Python code using a combination of HTML, CSS, and Javascript to enhance its

On my website, I want to display code blocks similar to how StackOverflow does it. The code block should be properly colored, formatted, and spaced out for better readability. All the code blocks on my site will be in python. def func(A): result = 0 ...

What steps are involved in developing a jQuery Validator function to enforce username restrictions?

Currently, I have implemented a method to enforce strong passwords like this: $.validator.addMethod('goodPassword', function(value, element){ return this.optional(element) || value.length >= 6 && /\d/.test(val ...