Using Javascript to dynamically update custom CSS properties

I am currently utilizing the paper-scroll-header-panel along with a custom CSS property

 paper-scroll-header-panel {
   --paper-scroll-header-panel-full-header: {
            background-image: url(images/abcd.jpg);
          };
}

in order to customize the full-sized header. However, I am facing an issue where the header image in this custom component needs to change based on the image URL provided by the loading page. I have defined a property and attempted to assign it through a computed property, but my approach does not seem to be effective. This is what I have tried.

<paper-scroll-header-panel style$={{backgroundCover}}>

and within the JavaScript:

Polymer({
  is: 'dummy-layout',
  properties: {
    cover: String,
    backgroundCover: {
        type: String,
        computed: 'computeBackground(cover)'
    }
  },    
  computeBackground: function(cover) {
    return '--paper-scroll-header-panel-full-header: { background-image: url(' + cover + ');};';
    },

Unfortunately, this method does not work as intended. How can I implement a varying background-image for different instances of a component while using a custom CSS component?

Update: The current code is displayed below. Nonetheless, it is still not functioning correctly.

<dom-module id="recipe-layout">

  <link rel="import" type="css" href="recipe-layout.css">
  <style is="custom-style">

    paper-scroll-header-panel {
      position: absolute;
      /* background for toolbar when it is at its full size */
      --paper-scroll-header-panel-full-header: {
        background-image: url();
      };
      /* background for toolbar when it is condensed */
      --paper-scroll-header-panel-condensed-header: {
        background-color: #00bcd4;
      };
    }
    paper-toolbar {
      height: 400px;
      background-color: transparent;
    }
</style>
<template>
 <paper-scroll-header-panel condenses condensed-header-height="56" id="scroller">

        <!-- Main Toolbar -->
        <paper-toolbar>
          <paper-icon-button icon="arrow-back" onclick="javascript:history.go(-1)"></paper-icon-button>
          <div class="flex"></div>
          <paper-icon-button icon="more-vert"></paper-icon-button>
          <div class="bottom title"><content select=".cover-title"></content></div>
        </paper-toolbar>

        <div class="content">
            <content select=".main-content"></content>
        </div>

      </paper-scroll-header-panel>
</template>

  <script>

    Polymer({

      is: 'dummy-layout',

      properties: {
        cover: {
            type: String,
            observer: '_updateBg'
        },
      },

      _updateBg: function(cover) {
        this.async(function() { this.subupdateBg(cover); }, 100);
      },

      subupdateBg: function(cover) {
        var scrollerBg = this.$.scroller;
        console.dir(scrollerBg);
        var newStyle = 'background-image: url('+ cover + ');';
        scrollerBg.customStyle['--paper-scroll-header-panel-full-header'] = newStyle;
        scrollerBg.updateStyles();
    }
  </script>

</dom-module>

Answer №2

@Neil is absolutely correct. The

--paper-scroll-header-panel-full-header
is a CSS variable that can be manipulated. I have created a small example to demonstrate how it can be done: Here is the link.

<dom-module id="dummy-layout">

  <style>
    :host {
      --bg: {
        background-color: red;
      }
    }

    .test {
      @apply(--bg);
    }
  }
  </style>

    <template>
      <div class="test">Hello world</div>
      <button type="button" on-click=btn>Click</button>
    </template>

  <script>
    Polymer({
      is: "dummy-layout",
      properties: {
        data: {
          type: String,
          observer: '_updateStyle'
        },
      },
      btn: function () {
        this.set('data', Math.random());
      },
      _updateStyle: function () {
        var colors = ['blue', 'green'];
        this.i = (this.i || 0) + 1;
        var newStyle = 'background-color: '+colors[this.i%2]+';';
        this.customStyle['--bg'] = newStyle;
        this.updateStyles();
      }
    });
  </script>

</dom-module>

Your code is almost there. The issue lies in the fact that your style changing code is never triggered because the value is not changed. If you incorporate a button or any other element to change it, the code will work as intended. Here is your modified code: Link to modified code

Answer №3

If you take a look at the code source for paper-scroll-header-panel(https://github.com/PolymerElements/paper-scroll-header-panel/blob/master/paper-scroll-header-panel.html), you will notice that the style values specified in '--paper-scroll-header-panel-full-header' are applied to #headerBg (line 127).

This means that changing the background image can easily be done by adjusting headerBg's style. For those using the Polymer Starter Kit, simply add this line in your app.js:

    document.querySelector('paper-scroll-header-panel').$.headerBg.style.backgroundImage = "url(path/to/image)";

Alternatively, in your specific scenario:

    this.$.scroller.$.headerBg.style.backgroundImage = "url(path/to/image)";

Check out the Plunker Demo here: https://plnkr.co/edit/gd6S7q?p=preview

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

Personalized Icons for Google Maps. (Designed for iPhone)

I am currently working on a project where I am designing a website specifically for iPhones. The main functionality of the site is to find the latitude and longitude of a certain location and display it on a Google map. I already have all the necessary det ...

Error with react/display-name in ESLint when using dynamic imports in Next.js

I encountered an error message from ESLint that says: Component definition is missing display name This error occurred in the following code snippet: const Disqus = dynamic(() => import('@/components/blog/disqus'), { ssr: false, loading: ...

From mongoose to swagger: "<field>" validation error - BSONTypeError: The argument provided must be a string containing either 12 bytes or 24 hexadecimal characters

I'm currently working on developing a REST API using Express, Mongoose, and Swagger for API documentation. To automate the process of converting my existing schema to Swagger, I utilized the mongoose-to-swagger package. However, I encountered an issue ...

Creating manageable CSS styles for a wide variety of themes

I need to add themes to a web application that allows users to switch between them seamlessly. The designers want a variety of font colors and background colors, around 20 in total. Is there a way to achieve this without creating multiple .css files, which ...

Enhancing User Experience with Real-Time Control Updates using ASP.Net and Bootstrap

I am struggling to figure out how to update bootstrap controls with ASP.Net. Here is the code I am working with: @{ Layout = null; } <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width ...

What is the best method for storing a list of present and absent students in a database to effectively manage attendance records?

I am struggling to save the daily present/absent details of students in a database for my project. Despite obtaining the student's name and roll number from another table, I can't seem to figure out how to save this information effectively. Any a ...

By utilizing the "order" property, I can arrange divs to start at the bottom and ascend as additional elements are added

Exploring the use of display: flex and order:, I noticed a curious behavior. When I set the order for my first div to 0 (order: 0;), it appears at the top of the page. However, as I add more divs with different orders, they initially show up in unexpected ...

What is the best way to establish a shared file for a constant that can be utilized by both JavaScript and C/C++

In my project, I currently have a C++ program with the following constant in the header file: #define VARIABLE_X 100 Additionally, there is a JavaScript file with the global variable set as: VARIABLE_X = 100; It is crucial that these values always remai ...

Tips for organizing and centering Kendo radio buttons within a Bootstrap grid and form structure

After trying the Bootstrap method [3] without success, I am now implementing the radios according to approach [1]. Even after applying the fix for box-sizing as suggested in [2], it doesn't seem to resolve the issue. <div class="panel panel-defa ...

Encountered an issue while trying to update a ServiceWorker for scope - Received a HTTP error

I encountered a puzzling issue with my Vue PWA app, as our error logs are flooded with instances of a particular user experiencing an error that myself and another person cannot reproduce. Failed to update a ServiceWorker for scope ('https://myapp.com ...

Highcharts facing issues with data rendering

This is the JSON data I have: [ { "project_title":"sdsdsd", "project_ref_id":"112", "amount":"232323.00", "months":"Mar-2015" },{ "project_title":"test project 44", "project_ref_id":"113", "a ...

UVs on a single object in my Three.js project are completely messed up

I've been working on a 3D house model and encountered another frustrating issue that seems to be common with three.js. In Maya, I have created my scene with 9 ungrouped objects, each only a child of the world, with texture maps containing ambient occ ...

Using the ESNEXT, Gutenberg provides a way to incorporate repeater blocks that

If you're like me, trying to create your own custom Gutenberg repeater block with a text and link input field can be quite challenging. I've spent hours looking at ES5 examples like this and this, but still feel stuck. I'm reaching out for ...

A comprehensive guide on effectively monitoring Form Abandonment in Google Analytics using jQuery or JavaScript

Is it possible to accurately track "Form Abandonment" in Google Analytics using jQuery or JavaScript? This method can help generate reports that display how far users progress through form filling before exiting or failing to submit. Are there more effect ...

Adjust the panel size accordingly for smaller screens

My application is utilizing the Spotify API to retrieve names and images. These are then displayed on my webpage within cards/panels in the following format: <div class="col-md-4" v-if="type == 'tracks'" v-for="(track, index) in tracks"> ...

The jQuery plugin qTip does not display the tooltip

I have successfully integrated a feature on my website that displays 12 items per page and allows users to navigate through the pages using jQuery. Additionally, I have implemented a tooltip functionality using qTip, which displays information when hoverin ...

Node.js variable initialization

Here's the issue I'm facing: in this function, I'm attempting to return an array of objects. When I use console.log within the forEach loop, the array is populated as expected. However, just before my return statement, it appears empty. http ...

Struggling to grasp the concept of using z-index in CSS

As a programmer versed in Python, C, Java, and Delphi, I am not a web developer or designer by trade. However, when required to fill those roles, I do my best; please be patient with me. :-) I have created a map (with a background image as a div), where I ...

ng-show directive in AngularJS is not functioning properly when utilized with CLI

After setting up my Angular app with ng new app, I attempted to hide certain elements conditionally using ng-show. Unfortunately, it doesn't seem to be working as expected. <span ng-show="false">Angular App</span> Regardless ...

Transmitting a multidimensional array in JavaScript to an AjaxPro method on a front-end webpage: A step-by-step guide

Imagine a scenario where I have a C# method that requires an array parameter: [AjaxPro.AjaxMethod] public int Test3(string[,] array) { return array.Length; } Next, I define a multidimensional array on the front page using JavaScript: var array = ...