What is the best way to transfer the ID from a div to a corresponding CSS identifier?

In my Sightly for an AEM component, I have the following setup. How can I use jQuery to dynamically insert the generated id into multiple CSS styles within each card on the page?

<div id="${card.id}" class="card flex-card radius-lg rel bgcolor ${card.cardTheme}"
                  role="region" tabindex="-1">
                  <sly data-sly-test.isImageTheme="${card.cardTheme == 'theme-light-bg-img' || card.cardTheme == 'theme-dark-bg-img'}">
                      <style data-sly-test="${isImageTheme}">
                          @media (min-width:1025px) {
                            #id-placeholder {
                              background-image: url(${card.imageLifestyle @ context='attribute'});
                              background-size: cover;
                              background-position: bottom right;
                            }
                          }
                          @media (min-width:768px) and (max-width:1024px) {
                            #id-placeholder {
                              background-image: url(${card.imageLifestyleTablet @ context='attribute'});
                              background-size: cover;
                              background-position: bottom right;
                            }
                          }
                          @media (max-width:767px) {
                            #id-placeholder {
                              background-image: url(${card.imageLifestyleMobile @ context='attribute'});
                              background-size: cover;
                              background-position: bottom right;
                            }
                          }
                      </style>
                  </sly>

I've attempted to update the CSS using jQuery without success. Here is the latest code snippet I tried:

    $(".card").each(function() {
        var id = $(this).attr('id'); 
        var style = $(this).find('style').html(); 
        style = style.replace(/#id-placeholder/g, '#' + id); 
        $(this).find('style').html(style); 
    });

Answer №1

It's not recommended to directly target an Id in your HTML with CSS.

Instead, you can utilize css variables and the style attribute to set different images for various screen sizes.

You can then access these variables in your CSS to apply styles that are common across all cards.

A css variable can be changed dynamically and assigned to an element by starting its name with --.

Please note that the following examples are used for illustration purposes as I am not familiar with aem or sightly.

To start, create a class like my-responsive-card which will style all cards uniformly:

<div id="${card.id}" 
     class="card flex-card radius-lg rel bgcolor ${card.cardTheme} my-responsive-card" 
     role="region" 
     tabindex="-1">
  <!-- ... --> 
</div>

<style>
.my-responsive-card {
  background-size: cover;
  background-position: bottom right;
}
</style>

Next, use the style attribute to define three css variables for different image sizes - --image-desktop, --image-tablet, and --image-mobile:

Define each variable just like any other css property:

<div id="${card.id}" 
  class="card flex-card radius-lg rel bgcolor ${card.cardTheme} my-responsive-card" 
  role="region" 
  tabindex="-1" 
  style="--image-desktop: ${card.imageLifestyle @ context='attribute'}; --image-tablet: ${card.imageLifestyleTablet @ context='attribute'}; --image-mobile: ${card.imageLifestyleMobile @ context='attribute'}">
  <!-- ... --> 
</div>

<style>
.my-responsive-card {
  background-size: cover;
  background-position: bottom right;
}
</style>

Once each card has its css variables set, you can access them in the stylesheet using media queries as seen previously.

To access a css variable, use the var() css function:

<div id="${card.id}" 
  class="card flex-card radius-lg rel bgcolor ${card.cardTheme} my-responsive-card" 
  role="region" 
  tabindex="-1" 
  style="--image-desktop: ${card.imageLifestyle @ context='attribute'}; --image-tablet: ${card.imageLifestyleTablet @ context='attribute'}; --image-mobile: ${card.imageLifestyleMobile @ context='attribute'}">
  <!-- ... --> 
</div>

<style>
.my-responsive-card {
  background-image: var(--image-desktop); 
  background-size: cover;
  background-position: bottom right;
} 

@media (min-width:768px) and (max-width:1024px) {
  .my-responsive-card {
    background-image: var(--image-tablet); 
  }
}

@media (max-width:767px) {
  .my-responsive-card {
    background-image: var(--image-mobile); 
  }
}

</style>

Keep in mind that your first media query condition is unnecessary since it represents the default value.

Answer №2

To easily render the ids using Sightly/HTL variables:

<div id="${card.id}" class="card flex-card radius-lg rel bgcolor ${card.cardTheme}"
                  role="region" tabindex="-1">
                  <sly data-sly-test.isImageTheme="${card.cardTheme == 'theme-light-bg-img' || card.cardTheme == 'theme-dark-bg-img'}">
                      <style data-sly-test="${isImageTheme}">
                          @media (min-width:1025px) {
                            #${card.id} {
                              background-image: url(${card.imageLifestyle @ context='attribute'});
                              background-size: cover;
                              background-position: bottom right;
                            }
                          }
                          @media (min-width:768px) and (max-width:1024px) {
                            #${card.id} {
                              background-image: url(${card.imageLifestyleTablet @ context='attribute'});
                              background-size: cover;
                              background-position: bottom right;
                            }
                          }
                          @media (max-width:767px) {
                            #${card.id} {
                              background-image: url(${card.imageLifestyleMobile @ context='attribute'});
                              background-size: cover;
                              background-position: bottom right;
                            }
                          }
                      </style>
                  </sly>

However, for a cleaner approach, consider storing the background images as data attributes on the card:

<style data-sly-test="${isImageTheme}">
.card .theme-light-bg-img, .card .theme-dark-bg-img {
    background-size: cover;
    background-position: bottom right;
}
@media (min-width:1025px) {
    .card .theme-light-bg-img, .card .theme-dark-bg-img {
        background-image: url(attr('data-backgroundImage'));

    }
}
@media (min-width:768px) and (max-width:1024px) {
    .card .theme-light-bg-img, .card .theme-dark-bg-img {
        background-image: url(attr('data-backgroundImageTablet'));

    }
}
@media (max-width:767px) {
    .card .theme-light-bg-img, .card .theme-dark-bg-img {
        background-image: url(attr('data-backgroundImageMobile'));

    }
}
</style>

Update the HTML as follows:

<div id="${card.id}" class="card flex-card radius-lg rel bgcolor ${card.cardTheme}" role="region" tabindex="-1"
     data-backgroundImage="${card.imageLifestyle @ context='attribute'}"
     data-backgroundImageTablet="${card.imageLifestyleTablet @ context='attribute'}"
     data-backgroundImageMobile="${card.imageLifestyleMobile @ context='attribute'}">
...
</div>

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

Having trouble getting the OwlCarousel directive to function properly

I have successfully created elements in the DOM, but for some reason, the plugin is not rendering the template. I am unsure if the problem lies with the plugin itself failing or if the Angular directive is not functioning as it should. Can someone please h ...

Error encountered while using the jquery with Twitter Search API

Looking to initiate a twitter search using the jquery and the twitter api, I consulted the documentation before writing this code: $.getJSON("http://search.twitter.com/search.json?callback=myFunction&q=stackoverflow"); function myFunction(r) { co ...

Send formcollection to action without submitting the form

Is there a way to pass formcollection data to FileContentPath actions that return generated pdf/excel files in the controller? The problem is that the formcollection may change depending on the user's interactions with the page. For example, I have l ...

Countdown to Auction jQuery

I am facing a challenge in implementing an auction countdown on my web application. The issue is that only the last countdown timer is working properly. I have attempted to use browser breakpoints to address this problem, but without success so far. func ...

The Bootstrap carousel indicators are not automatically switching because they are placed outside of the main div

I have integrated the latest Bootstrap framework into my website, featuring a visually appealing carousel. The unique aspect of my carousel design is that the indicators are positioned outside the main carousel div. Here is a snippet of my carousel code: ...

center text within grandparent element

Within my Angular application, I have a list where each item can be comprised of either a small image with accompanying text or just text alone. li { display: flex; border: 1px solid black; width: 80%; margin-bottom: 5%; list-style: none; po ...

Using Javascript or jQuery to Enhance the Appearance of Text on a Website

Is there a way to automatically apply styling to specific phrases on our website by searching for instances of those phrases? For example: <div> This is what you get from <span class="comp">Company Name</span>. We do all kin ...

Sending a 2-dimensional array from JavaScript to the server using AJAX

My JavaScript code involves working with a 2D array. var erg = new Array(); for (var i in val) { erg[i] = new Array(); for (var j in val[i]()) { erg[i][j] = val[i]()[j](); } } However, I encountered an issue where only the 1D array ...

How can I implement a real-time progress bar using Rails and Jquery?

This is my first "general" Stack Overflow question - I'm not asking for someone to write code for me, just seeking advice I am searching for a way to incorporate a dynamic progress bar or thermometer (preferably using jQuery) that updates in real-tim ...

jQuery mCustomScrollbars does not correctly resize the height of the div on the initial load

Need help with resizing the height of a div. Currently, I am setting the height of the div using JavaScript, but it only takes effect after refreshing the page (F5). Is there a way to make it work without needing a refresh? Check out the code snippet be ...

Count up with style using the "jQuery Boilerplate" plugin for Jquery!

I am a beginner in creating jQuery plugins. The following jQuery plugin has been created using jQuery Boilerplate. It performs a count-up and notifies when the count-up is completed. I would like to have a function that restarts the count-up by setting t ...

jQuery Datatables provide a powerful and customizable way to display

I've been working on a project that requires me to incorporate Grid functionality into the displayed data. To achieve this, I'm utilizing the Datatable plugin from jquery. The implementation is smooth and flawless. However, a concern arises wh ...

Issue with Table Content Being Truncated After Conversion from HTML to MS Word 2003

I am experiencing an issue where the table content is being cut off on the right side of the page when converting from an HTML page into MS Word 2003. Below is a sample HTML code (where placeholder $CLOB_DATA will be replaced by large CLOB data): <html ...

Is your browser tab failing to display the complete URL?

Encountering a strange issue while working on my current website project: When you click on "about," it does take you to the correct page, but upon refreshing the page, it redirects back to the home page. The same scenario is happening with other pages as ...

The current page I'm working on is scrolling sideways, but I prefer a stationary layout without any scrolling

I am currently facing an issue with my webpage scrolling to the right. This behavior is not acceptable as web pages are not supposed to scroll to the right, correct? Could someone assist me in eliminating this unwanted scroll from my page? I have only u ...

Get JSON information based on index position

Whenever I need to generate JSON data for a shopping cart, I rely on PHP's json_encode() method: { "6cb380f1bfbcd7728be7dfbf2be6bad4": { "rowid": "6cb380f1bfbcd7728be7dfbf2be6bad4", "id": "sku_131ABC", "qty": "4", "price": "35.95", ...

Calculating the quantity of elements within a jQuery array

A JQuery array is proving to be quite problematic. Here's what it looks like, [125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32] Unfortunately, there are duplicates present in this array. My goal is to obtain the count of each unique element ...

Identify the element with the active class name as the primary focus

Can anyone assist with this issue? Below is an example of the code I am working with: import React, { useRef, useEffect } from "react"; function App() { const inputRef = useRef(null); useEffect(() => { const testElement = document.qu ...

The functionality of the margin gets disrupted when the float property is not included

Could someone please explain why the margin stops working when I remove the float property? Is there a connection that I am missing? .header-image { float: left; width: 33%; margin-top: 1em; padding-right: 3em; text-align: right; } ...

Hyperlinks springing to life on mouseover

After spending countless hours tweaking my CSS code, I've hit a roadblock and need some assistance. My issue lies with the links on hover that seem to be jumping unexpectedly. The goal was to create a mobile-responsive hamburger menu that transforms i ...