An unconventional way to display an image using the :before pseudo-element and a data attribute in CSS

My goal is to use the :before pseudo-element to set an image background, as I plan to overlay content on top of it.

In the past, I have dynamically set a data attribute with :before for other purposes.

Question: Is there a way to change the number using :before, similar to how I'm attempting to do so with an image?

Here is my current approach:

<li data-image="https://via.placeholder.com/150/0000FF">hello 1</li>
background: url(attr(data-image));

Below is the full code snippet:

setInterval(function(){
            var randomImages = ['https://via.placeholder.com/150/0000FF','https://via.placeholder.com/150/FF0000','https://via.placeholder.com/150/FFFF00'];
            var imagIndex = Math.floor(Math.random() * 3);
           $('li:eq('+imagIndex+')').attr('data-image',randomImages[imagIndex]);
         // console.log(randomImages[imagIndex]);
      $('#displayingWithBefore').attr('data-number',imagIndex);
},200);
ul{
            list-style: none;
            line-height: 43px;
        }

        li{position: relative;}

        li:before{
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 40px;
            background: url(attr(data-image));
        }

   #displayingWithBefore{
        position: relative;
        width: 90px;
        height: 90px;
        background:red;
        color: #fff;
    }

#displayingWithBefore:before {
    content: attr(data-number);
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    font-size: 30px;
    text-align: center;
    line-height: 92px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



<div id="container">
       <div id="displayingWithBefore"></div>
        <ul>
            <li>hello 1</li>
            <li>hello 2</li>
            <li>hello 3</li>
        </ul>
   </div>

I'm looking forward to receiving helpful answers.

Any assistance would be greatly appreciated - thank you in advance!

Answer №1

Many developers are calling for the ability to use attributes for URLs, but currently it is not supported.

One workaround is to utilize CSS custom properties:

<li style="--image: url(https://via.placeholder.com/150/0000FF);">hello 1</li>
  /* your code … */
  li:before {
    background: var(--image);
  }

Although browser support for this method is good, you may want to consider alternatives such as inlining the background-image property and using a hidden background trick on the element itself:

<li style="background-image: url(https://via.placeholder.com/150/0000FF);">hello 1</li>
  /* your code … */
  li { background-size: 0 0; }
  li:before {
    background-image: inherit;
  }

Answer №2

It seems like you are looking to randomize the background every 200 ms by changing the data-image attribute. In order to achieve this, you can use jQuery to dynamically apply the styles to the head.

If that's not the case, you can simply set the data-image once and add the style to the head.

In the provided example, I have followed your approach of randomly changing the background every 200ms.

I hope this explanation is clear for you.

setInterval(function(){
            var randomImages = ['https://via.placeholder.com/150/0000FF','https://via.placeholder.com/150/FF0000','https://via.placeholder.com/150/FFFF00'];
            var imagIndex = Math.floor(Math.random() * 3);
           $('li:eq('+imagIndex+')').attr('data-image',randomImages[imagIndex]);
         // console.log(randomImages[imagIndex]);
         $('head').append('<style>li:before{background: url("'+randomImages[imagIndex]+'");}</style>');
},200);
ul{
            list-style: none;
            line-height: 43px;
        }

        li{position: relative;}

        li:before{
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 40px;
            <!--background: url(attr(data-image)); You don't need this--> 
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



<div id="container">
        <ul>
            <li>hello 1</li>
            <li>hello 2</li>
            <li>hello 3</li>
        </ul>
   </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

Steps to insert an image using ajax:

I am currently facing an issue while trying to include a form with an image field. I have successfully implemented the text field, but I am encountering difficulties with the image field. Upon using console.log, I noticed that my image is returning as unde ...

Updating the span element upon click in jQuery

I have this JavaScript code snippet that I am working with: $('a').click(function() { $('a span').first().toggleClass('hide'); $('a span:nth-child(2)').toggleClass('display'); }); .hide { display:none; ...

Tips for developing a versatile code for passport.authenticate

I have a scenario where multiple controllers contain various methods that require user authentication to access database data. I am currently attempting to streamline the authentication process to avoid repetition in my code. Within the controller: const ...

Error: Uncaught TypeError when using a for loop in Vue and GraphQL

I encountered a TypeError while attempting to iterate through a GraphQL query in my Vue project. The script snippet in question is as follows: <script> import { useQuery } from "@vue/apollo-composable"; import gql from "graphql-tag&qu ...

Guide on altering a Tailwind Class depending on the React State or Props

Currently, I am working on a Progress Bar Component and utilizing the following versions: "next": "13.4.4", "react": "18.2.0", "react-dom": "18.2.0", "classnames": "^2.3.2", I ...

Encountering issues with React Apollo hooks after integrating React Native into the monorepo system

I am in the process of setting up a React web app and a React-native app within a monorepo using yarn workspaces. The web and controllers are functioning properly, allowing me to successfully execute graphql queries to my apollo-express server. However, up ...

Turn off the feature that highlights links

Hi there! I'm curious to know if it's feasible to remove the highlighting effect when clicking on a link. I'd like the link to function more like an image, without the appearance of a highlighting box upon clicking. ...

Can TypeScript modules be designed to function in this way?

Seeking to create a versatile function / module / class that can be called in various ways: const myvar = MyModule('a parameter').methodA().methodB().methodC(); //and also this option should work const myvar = MyModule('a parameter') ...

Utilizing dynamic props JSON object to modify the state

Within my component, I am working with a json object passed in as a prop from the parent component, where the API call to populate this json object is made in the parent component itself. My current challenge is figuring out how to properly define the sta ...

Checking JSON formatted actions in Rails 4: A guide to testing

I'm in the process of testing a Rails application where all my actions return data formatted in json. An example of this is within the UsersController # POST /users.json def create @user = User.new(user_params) respond_to do |format| ...

Informing a screen reader in Vue.js through the use of aria-live features

My goal is to make a vue component that dynamically announces information to a screen reader when certain events occur on my website. I have managed to achieve this functionality by having a button populate a span with text containing the attributes aria- ...

"Challenges encountered when using map function to dynamically fill select dropdowns in React with Material UI

I am currently working on populating Material's UI with a list of countries using the following code: import React from "react"; import FormControl from "@material-ui/core/FormControl"; import InputLabel from "@material-ui/core/InputLabel"; import Se ...

What is the best approach to effectively manage right-to-left text-input fields?

I have been working on a project involving a multilingual layout. One concern that has arisen is: What is the proper way to handle text-input in this scenario? To better explain my issue, I created a JSFiddle. If I simply add the attribute dir="rtl", ...

In React, the ES6 prototype method map failed to render anything on the screen

Is there an issue with my map method implementation? var App = React.createClass({ getInitialState(){ return { items:[1,2,3] } }, renderItem(){ return( this.state.items.map((item,i))=> <li key={i}> { ...

Trigger a function in JavaScript by clicking on an element and passing its class

I have written the following code: <?php $extCount = 0; foreach($this->externalReferal as $externalReferal) { $extCount++; ?> <div class='fieldtestPct' > <div class='fieldItemLabel'> < ...

Achieve automated zooming out using highcharts-ng through code

Currently, I am using Highcharts-ng as seen on https://github.com/pablojim/highcharts-ng Upon inspecting the source code, I have noticed some interesting functionalities in the directive utilizing scope.$on which I can leverage for broadcasting. One examp ...

Executing a function following the removal of an element

I am trying to remove an element after exiting a jQuery dialog. I have used the .remove() function, but the element is not accessible after executing .remove(). How can I "destroy" an object in JavaScript and allow it to be called again without refreshing ...

Ways to personalize the onSubmit function within tinacms

Having an issue with my Tina project. I am trying to develop my own submit button in Tinacms project, rather than using the sidebar or top bar provided by tinacms. I want to customize a button for onSubmit functionality. Any suggestions on how to achieve ...

What is the best way to send a List in the model as a parameter for an AJAX request?

I'm currently using MVC 4 ASP.net with Razor views and I have an issue with refining my search results using AJAX calls. The current approach involves creating methods in the controller that include all the search filters, which has resulted in a meth ...

The AJAX call failed because the web service was not properly configured, resulting in a missing parameter value being

I'm encountering an issue with my ajax call that displays a specific message. [WebMethod(EnableSession = true)] public static string UpdateTotalPrice(List<TicketPriceAjax> jsonTickets) { // conducting server-side processing return "a u ...