"Exploring the use of jQuery to access dynamic CSS properties such as :before and implementing filter

I am facing an issue with jQuery and CSS.

Below is the code snippet:

$("#test").append($("<div>",{
               style:"width:48%; margin-left:1%; margin-right:1%; margin-bottom:10px; float:left; background-image:url(http://test.png); filter:brightness(0.4); -webkit-filter:brightness(0.4);"
        }));

The parent div tag is "#test" and I am trying to append a child div tag with a style similar to ":before" in CSS.

Unfortunately, I am unable to figure out how to dynamically create ":before" code in jQuery. How can I resolve this issue?

Is it possible to generate :before code and append it to "#test"? Specifically, I need to create :before dynamically using jQuery as it is not available in CSS.

This is the challenge.

and this is what I am aiming for.

This div tag is being generated using jQuery.

Answer №1

To change the style of a pseudo-element, you can utilize the CSSRule in pure JavaScript. The key is to define your selector consistently in the CSS code so that the rule can be found successfully. Once the rule is located, styling can be easily modified. Additionally, new rules can be inserted to apply different styles to elements. Here is an updated demo code based on your specific requirements:

HTML:

<div>Pane 1</div>
<div>Pane 2</div>
<div>Pane 3</div>

CSS:

div {
  border:1px solid black;
  width:100px;
  height:100px;
  position:relative;
  display:inline-block;
  color:white;
}
div:before {
  content:'';   
  position:absolute;
  width:100%;
  height:100%;
  z-index:-1;
  background-size:cover;
}

JavaScript:

var divs = document.querySelectorAll('div');

function applyBeforeElementStyleOn(elem, styleProp, styleVal){
    if(!elem.beforeElementStyle) {
      var sheet = document.styleSheets[0];
      var currentTime = new Date();
      var guid = (currentTime + "" + 
                  currentTime.getMilliseconds()).replace(/[ :+()]/g,'') +
                 parseInt(Math.random()*1000);
      var ruleText = elem.tagName + "[" + guid + "]:before {}";
      sheet.insertRule(ruleText, 0);
      elem.beforeElementStyle = (sheet.cssRules || sheet.rules)[0].style;
      elem.setAttribute(guid.toLowerCase(),"");
    }    
    elem.beforeElementStyle[styleProp] = styleVal;
}

var data = [
  {bg: "url(http://placekitten.com/300/300)", brightness: 0.2},
  {bg: "url(http://placekitten.com/100/100)", brightness: 0.9},
  {bg: "url(http://placekitten.com/400/400)", brightness: 0.6},
];
for(var i = 0; i < data.length ; i++){
  applyBeforeElementStyleOn(divs[i], "background-image", data[i].bg);
  applyBeforeElementStyleOn(divs[i], "webkitFilter", 
                            "brightness(" + data[i].brightness + ")");
}

Check out the Demo here!

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

Parse JSON files from a folder and concatenate them to a CSV using Node.js

Thank you for offering your help. I have a collection of JSON files located in a directory with unknown names. I need help with the following: (1) Reading all the JSON files (2) Appending the data from the JSON files to output.csv (3) Adding "-Appended" t ...

Position image/icon within navigation bar

I am currently working on a school project to create a webpage, but I am struggling to align an image/icon with the other buttons in the navbar. Despite my efforts to find a solution through Google searches, I have not been able to resolve this issue. Furt ...

What is the best way to redirect a URL to include www using Node.js?

What is the best way to redirect a URL to start with www? For instance: ---> ...

When using a PhoneGap app to access a webservice, are there any potential cross-site issues that could arise?

How can I access an external web service from a PhoneGap app using AJAX without needing to rely on CORS or JSONP to bypass the cross-origin issue? I've come across a question on Stack Overflow suggesting that cross-site HTTP calls are not a problem wi ...

Enhancing your Selenium test case strategies for better performance

I've created a test case that compares two arrays, removing matching elements and throwing an exception for non-matching ones. Although it's functional, the test is quite long and messy. Can anyone suggest ways to optimize or improve it? System ...

Loading intersecting objects with FBXLoader in Three.js

After successfully loading an fbx file using FBXLoader and adding it to the scene object, I encountered an issue where I couldn't interact with the object on click to apply transform controls. Interestingly, all other objects were clickable except for ...

Discover the magic of gradients in tooltips with Bootstrap 5!

I recently encountered some challenges when attempting to apply a gradient color to bootstrap 5 tooltips CSS: .tooltip .tooltip-arrow::before { position: absolute; content: ""; border-color: transparent; border-style: solid; } .bs-toolt ...

Leveraging hapi-auth-basic

I attempted to incorporate a basic authentication strategy following a tutorial I stumbled upon. Here is the setup of my server.js file. 'use strict'; const Hapi=require('hapi'); const sequelize = require('sequelize'); c ...

Numerous DIVs with floating elements and border styling

Trying to align two divs with one floating to the left and with a width of 80%, while the other is floated to the left with 20% width, is causing some issues. I want to add a border on the right side of the first div and apply a box-shadow of 5px since eac ...

Clicking the responsive menu does not reveal the hidden overlay div as expected

Struggling with finding the correct function to open the hidden div of my responsive menu on my new website. Check out my code: https://codepen.io/anon/pen/XRJRGE <a class="page-head__menu" id="js-menu" href="#" onClick="open()">Menu< ...

JS Nav Dots are not activating the Active Class

I have been utilizing a code snippet from this source to incorporate a vertical dot navigation feature into a single-page website. The navigation smoothly scrolls to different sections when a link is clicked, with an active highlight on the current section ...

How can JavaScript be used to delete cache and cookies?

Looking for a solution to clear cache and cookies via JavaScript? I'm currently using Selenium for testing in Microsoft Edge, but the tests are running in the same session as the previous run. I need each test to run in a clean session every time. Unf ...

Mastering Tooltip Placement Using CSS or JavaScript

I have been working on creating a CSS-only tooltip for a web application and so far I have managed to create some useful tooltips with different classes: tooltip-up tooltip-down tooltip-left tooltip-right The distinguishing factors between them are t ...

Tips for setting up the image as the header background in HTML5 and CSS3

I am currently designing a website. I'm wondering if there is a way to create a div with a curved bottom using HTML5, CSS3 and JavaScript. It should resemble the design of the curved header bottom ...

Is it possible to access all the variables within a specific scope or explore different scopes using console.log?

In the process of writing a graph algorithm, I am currently working on implementing a removeEdge method in the graph prototype. This method takes two arguments, which are the two nodes that will be losing their connection. I have successfully achieved a ...

What are the steps to developing a responsive tile using HTML and CSS?

I am exploring the functionalities of CSS and responsive design. To better understand how it works, I created a simple example which can be accessed here. This demonstration showcases a basic tile template. My goal is to display my tiles in 2, 3, 4, or m ...

What is the best way to load a local JSON file as the initial data source in Express and use it as an in

I'm in the process of creating a basic todo application using node.js express, and I've decided to work with an in-memory resource instead of utilizing a database. There's a local json file todo.json that contains some initial data which I ...

Is there a way to drop a pin on the Google Maps app?

Is there a way to pinpoint the specific location on Google Maps? <google-map id="map-container" width="100%" height="100%" class="maps"></google-map> ...

What is the best way to evaluate two values using jQuery?

I need to select them and add a new class. <div class="count_1"> <span class="percentage">10 %</span> </div> <div class="count_2"> <span class="percentage">90 %</span> </div> if (parseInt($(".count_1.per ...

Exploring the Features of Bottom and Right in jQuery

Here is a snippet of jQuery code that I included in a sample program: $('#left').click(function(){ $('.box').animate({ left: "-=40px", }, function(){/* End of Animation*/}); }); $('#right ...