-1

Hello guys am working on a colorpicker named colpick, i am using .css() for changing the colors of different elements and i uses same .css() a repeatedly in my js and the elements are more so i started var the elements and using var for them something like this

var colorElement = "a, upper"
$(colorElement).css('color', '#' + hex);

but i also wants to edit the color/style of the element when we hover, and all then when i try to add elements with :hover or :link or :focus or active,etc like this

var colorElement = "a:hover, upper:focus, headline:active, bar, footer"
$(colorElement).css('color', '#' + hex);

then it stop working (those pseudo containing elements not work) so any idea how i can use them ?

Regards,

HMR
  • 3
  • 5
  • Have you tried forcing important to override other styles? `$(colorElement).css('color', '#' + hex + ' !important');` – Shakespeare Apr 14 '16 at 13:27
  • You cannot modify the style of pseudo-elements that way, as they are not in the DOM. You can add/remove classes (or other attributes, for that matter) on the elements, and then create CSS rules that affect the pseudo-elements. You can also dynamically create CSS rules (that is, update ` – Pointy Apr 14 '16 at 13:37

1 Answers1

0

jQuery does not create CSS rules, it only changes the current DOM. So to change CSS style after hover, focus, etc. you must add methods that will change it.

see how-to-define-the-css-hover-state-in-a-jquery-selector

$(".myclass, .myclass2").hover(function(e) { 
    $(this).css("color",e.type === "mouseenter"?"red":"transparent") 
})

Update: Look at CSSX which can change CSS styles dynamically:

var sheet = cssx();
var rule = sheet.add('a:hover, upper:focus, headline:active, bar, footer');
var setColor = function (hex) {
   return { 'color': '#' + hex };
};

//...

rule.update(setColor('ff0000'));
Community
  • 1
  • 1
Radek Pech
  • 3,032
  • 1
  • 24
  • 29
  • but that only profitable for hover, and if i do like that for others then the js can become a bit bigger in size as i have to use same bunch of elements many times and for every hover, active,link,etc i have to create a new function. do you know any way to involve all all elements containing pseudo to be done in one go ? – HMR Apr 14 '16 at 13:45
  • @HMR you can use multiple selects `$('el1, el2, el3, ...')` and you can register handler for more events `$(...).on('event1 event2 event3 ...', function() {...})`. But this is something jQuery was not designed for so expect lots of messy methods... You may alternatively try to change CSS using custom properties (`body.style.setProperty('--color', newValue)`) or document stylesheets (`document.styleSheets[0].cssRules`) but it will not work in all browsers. – Radek Pech Apr 14 '16 at 14:14
  • @HMR look at https://github.com/krasimir/cssx . It may be what you are looking for. – Radek Pech Apr 21 '16 at 11:46