Dynamically add !important to all CSS properties - javascript

How can I dynamically add !important for all CSS properties?
For example in my <head></head> section I have:
<style>
.text-center {
text-align: center;
}
.text-left {
text-align: left;
}
.main-container {
border: 3px solid yellow;
padding: 10px 5px;
margin: 3px;
}
</style>
I need:
<style>
.text-center {
text-align: center !important;
}
.text-left {
text-align: left !important;
}
.main-container {
border: 3px solid yellow !important;
padding: 10px 5px !important;
margin: 3px !important;
}
</style>
I tried to use Window.getComputedStyle(), but I must provide to this method the element for which I want to get the computed style. In my case I can't provide these elements.

I was having an issue with printing (with css styling) in Chrome and Firefox..
even adding -webkit-print-color-adjust: exact!important; didnt work in my case
until i figured out that the style need to have !important attribute. When working with WYSWYG Editor, this could be a problem for printing. So I need to add !important to every css style attribute found in every element.
Here's how I solved it using jQuery
//add !important rule to every style found in each element
//so the browser print render the color/style also
var el = $('.content *');
if (el.length) {
el.each(function(item) {
var _this = $(this);
var attr = _this.attr('style');
var style = '';
if (typeof attr !== typeof undefined && attr !== false) {
if (attr.split(';').length) {
attr.split(';').forEach(function(item) {
if (item.trim() != '') {
style += item.trim() + '!important;-webkit-print-color-adjust: exact!important;';
}
});
_this.attr('style', style);
}
}
});
}
Here's the result in Printing Preview before and After adding the Code Hack

I run into this problem with pandas DataFrame Styler. It generated a <style> tag element with all the styling info. But the styling is overridden by linked css files.
So my solution is to replace all ; with !important; using JavaScript
CSS:
<style type="text/css" >
#T_195822c0_1b0f_11e9_93d2_42010a8a0003row10_col4 {
background-color: yellow;
} #T_195822c0_1b0f_11e9_93d2_42010a8a0003row73_col5 {
background-color: yellow;
} #T_195822c0_1b0f_11e9_93d2_42010a8a0003row100_col2 {
background-color: yellow;
}</style>
Javascript:
var st = document.getElementsByTagName("STYLE")[0];
st.innerHTML = st.innerHTML.replace(/yellow;/g,'yellow !important;')
You can adapt replace rules to your need.

Related

How to change the scrollbar styling via javaScript

I have implemented a customized scrollbar (code is provided below).
I want to use the javaScript event "onScroll" to change the scrollbar thumb styling while scrolling, but I don't know the right way to do so.
Is there a way to access the scrollbar style, perhaps as a JavaScript object, i.e.:
Container.style.-webkit-scrollbar-thumb.backgroundColor = 'black';?
Here is some code to demonstrate how my scrollbar is implemented:
CSS:
#container::-webkit-scrollbar {
width: 10vw;
}
#container::-webkit-scrollbar-thumb {
background-color: grey;
border-radius: 50px;
border: 5px solid black;
}
#container::-webkit-scrollbar-thumb:hover {
border: 2px solid black;
background-color: grey;
}
#container::-webkit-scrollbar-track {
background-color: black;
border-bottom-left-radius: 12px;
border-top-left-radius: 12px;
}
JavaScript:
elementsContainer.addEventListener("scroll", function wheelStyle() {
//elementsContainer.WHAT??
});
Here is my solution:
The idea is to create a CSS stylesheet rule dynamically and update it while scrolling.
Here is the snippet I used to test in stackoverflow itself (by running it from the console directly):
// Based on https://stackoverflow.com/a/31126328/1941313
appendRule = (sheet) => {
console.log({sheet});
const len = sheet.cssRules.length;
sheet.insertRule('body{}', len);
return sheet.cssRules[len];
}
ruleForScroll = appendRule(Array.from(document.styleSheets).slice(-1)[0]);
randomColor = () => Math.floor(255 * Math.random());
component = document.querySelector('.left-sidebar--sticky-container.js-sticky-leftnav');
component.addEventListener("scroll", function wheelStyle() {
ruleForScroll.selectorText = '.left-sidebar--sticky-container.js-sticky-leftnav::-webkit-scrollbar-track';
ruleForScroll.style["background"] = `rgb(${randomColor()},${randomColor()},${randomColor()})`;
});
This specifically affects the side menu of stackoverflow, changing the scrollbar's color randomly while scrolling.
Here is an independent solution in a CodePen. Note that an important prerequisite for the style to apply is the following css rule:
.test::-webkit-scrollbar {
width: 10px;
height: 10px;
background-color: transparent;
}

How to change an ID depending on the color of an element with Javascript

I'm trying to learn javascript on my own, so I'm lacking a lot. I'm trying to change the color of multiples elements depending on the color in the css of another element.
I want the javascript to detect the <div id> with a specific color, and then change the id of another <div id2>
I tried this :
if (document.getElementById("name").css('color') == "#7a5cd4") {
document.getElementById('border').setAttribute('id', 'red');
document.getElementById('line').setAttribute('id', 'linered');
}
#name {
font-size: 35px;
color: #7a5cd4;
}
#border {
width: 25px;
height: 25px;
border: 3px solid black;
padding: 10px;
margin: 10px;
border-radius: 100%
}
#red {
width: 25px;
height: 25px;
border: 3px solid red;
padding: 10px;
margin: 10px;
border-radius: 100%
}
#line {
width: 200px;
height: 20px;
border: 1px solid black
}
#linered {
width: 200px;
height: 20px;
border: 1px solid red
}
<center>
<div id="name">name</div>
<div id="border"></div>
<div id="line"></div>
</center>
window.getComputedStyle is a function that takes an element as a parameter and returns an object containing all of the styles that are being used on that object. We can then call getPropertyValue on the result to get the value of a css property.
These functions return colours in the form rgb(r, g, b), so we will need to compare the value to rgb(122, 92, 212), instead of #7a5cd4.
HTMLElement.style, however, would not work in your case as it only gets the inline style, which is when you specify the style in your html, like <div style="color: red">.
Also, it is recommended to use classes for selecting elements, instead of ids, as you can place multiple of them on the same element.
const element = document.getElementById('name');
const styles = window.getComputedStyle(element);
if (styles.getPropertyValue('color') == 'rgb(122, 92, 212)') {
document.getElementById('border').setAttribute('id', 'red');
document.getElementById('line').setAttribute('id', 'linered');
}
In order to change the id of element you:
document.getElementById('oldid').id = 'newid'
This rest of this answer fit to inline style (element style="color: value") while #BenjaminDavies answer fit more to your original question:
In order to check/change color property you:
var divOldColor = document.getElementById('oldid').style.color; // get the color to variable
if (divOldColor == '#7a5cd4') { // do something }
Put it all together we get something like this:
if (document.getElementById('name').style.color == '#7a5cd4') {
document.getElementById('border').id = 'red';
document.getElementById('line').id = 'linered';
}
.css() is not a vanilla JS function. Use .style.cssPropertyName instead.
if (document.getElementById("name").style.color === "#7a5cd4") {
document.getElementById('border').setAttribute('id', 'red');
document.getElementById('line').setAttribute('id', 'linered');
}

vaadin-combo-box / vaadin-combo-box-overlay change background color / Polymer API

I'm trying to override the background color present in vaadin-combo-box-overlay element.
Here is the css that I want to override, more specifically the background property, source taken from (https://github.com/vaadin/vaadin-combo-box/blob/master/vaadin-combo-box-overlay.html)
:host {
position: absolute;
#apply(--shadow-elevation-2dp);
background: #fff;
border-radius: 0 0 2px 2px;
top: 0;
left: 0;
.......
}
So I've tried something like:
:root ::content vaadin-combo-box-overlay.vaadin-combo-box-overlay {
background: red !important;
background-color: red !important;
}
Also I've tried with :host but I guess it should be used :root because I use this dropdown in a dialog, and the overlay component doesn't seem to be a child of the dialog. I've tried different combinatons as the one mentioned above without any success.
Also I'm wondering why the background is not parameterized as the text color is:
#selector .item {
cursor: pointer;
padding: 13px 16px;
color: var(--primary-text-color);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Specifying a different value for --primary-text-color I'm able to change the text color..
Thanks.
you can do it with javascript like that.
ready: function() {
var domElem=Polymer.dom(this).node.$.YOUR-VAADIN-ELEMENT-ID.$.overlay.style.backgroundColor="red";
}
OR
ready: function() {
var css = '#selector .item { background-color:red; }';
var style = document.createElement('style');
style.type = 'text/css';
style.appendChild(document.createTextNode(css));
Polymer.dom(this).node.$.tourSelector.$.overlay.$.selector.appendChild(style);
}
Would like to have a working CSS selector, but i cant set breakpoints in CSS to find out the right selectors!
You should use dom-module for styling vaading parts see example below:
<dom-module id="combo-box-overlay-styles" theme-for="vaadin-combo-box-overlay">
<template>
<style>
[part~="content"] {
background-color: red;
}
</style>
</template>
</dom-module>
Read more here https://github.com/vaadin/vaadin-themable-mixin/wiki
Thanks Patrick !!
I wasn't thinking about to do try it this way.
Here's what I did, a hacky solution though.
ready : function(){
var combo = this.$$('#comboid');
combo.addEventListener('vaadin-dropdown-opened'', function() {
var overlay = Polymer.dom(this.root).querySelector('#overlay');
overlay.style.backgroundColor = primaryBackground;
});
},
I only have access to the overlay when the combo is expanded, so in the value change listener the combo would be expanded.

Including style tag in javascript

I want to include style tag in the javascript. ie., I am printing notices and the number of notices change dynamically. I receive the notices in a JSON object and hence require styles to be applied to each notice separately.
For now I just want the border around each notice or text
function retrive()
{
/*var css = ' { border :2px dashed; }',
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css'; Not working*/
var myObj = JSON.parse(localStorage.getItem("Notice"));
if(myObj.length == 0)
{
$('#title').append(
'<br><br>Currently There are no Notices to be displayed'
);
}
else
{
for(var i = 0; i < myObj.length; i++)
{
$('#heading').append(
'<br><br><strong><center>'+ myObj[i].title+'</center></strong><br>'+myObj[i].introtext
);
}
}
}
I am printing the notices in the else block using for loop by finding the object length and appending it to the heading. This is where I want to print border to be printed around each block
<div>
<ul id="heading" style = "font-size : 16px;">
</ul>
</div>
If I use style here, border is appears to whole block or a single border to all notices.
<div>
<ul id="heading" style = "font-size : 16px; border : 2px dashed">
</ul>
</div>
,which is obvious.
Thanks.
I believe that you could handle this entirely with CSS and applicable classes. If you need to make changes based on the number of items, you could define classes for the different sets of count values that would result in the same CSS settings and simply apply that class to the header. Based on what you have in your code, that doesn't look to be the case and the example below should approximate what you're trying to achieve.
Note: I'm assuming that you're using a standard CSS reset to remove list styles. If not, then I suggest that you should.
<style>
#title p {
padding-top: 1em;
}
#heading {
font-size: 16px;
}
#heading li {
border: 2px dashed;
}
#heading li span.item_title {
font-weight: bold;
display: block;
text-align: center;
}
#heading li span.item_text {
display: block;
}
</style>
function retrive()
{
var myObj = JSON.parse(localStorage.getItem("Notice"));
if(myObj.length == 0)
{
$('#title').append('<p>Currently There are no Notices to be displayed</p>' );
}
else
{
for(var i = 0; i < myObj.length; i++)
{
$('#heading').append('<li><span class="item_title">'+ myObj[i].title+'</span><span class="item_text"'+myObj[i].introtext+ "</span></li>" );
}
}
}
If you use CSS classes you will be able to change the design more easily later, by modifying the CSS, rather than the JavaScript and HTML.
<style>
.heading
{ font-size : 16px; border : 2px dashed; }
</style>
<div>
<ul id="heading" class="heading">
...
</ul>
</div>
You can put the HTML in your JavaScript as you already have it, and use as many classes as you need.
In addition, try to avoid using <strong> and <br> and use CSS to control the layout.
You can apply a css style to each notice inside of #heading.
Something like this should work fine (place this in your css file or inside of a style tag) :
#heading strong {
border: 2px dashed;
}
I would recommend surrounding each notice in a span and append this to your #heading inside of an li and then applying this style:
#heading li {
list-style:none;
margin: 0 auto;
text-align: center;
}
#heading li span {
border: 2px dashed;
font-weight: bold;
}
you html would look something like this:
<ul id='heading'>
<!-- your newly inserted notice -->
<li><span>text</span></li>
</ul>
This will remove the need for the center and br tags.

css hover event not working after using javascript?

Here is the code in which i am having the problem-
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
p {
font-family: Tahoma;
line-height: 170%;
color: #000;
font-size: 15px;
padding: 5px 0px 5px 0px;
text-align: center;
}
#col1 {
//some propeties
}
#col1:hover ~ p {
color: #f00;
}
#col2 {
//some propeties
}
#col2:hover ~ p {
color: #ff0;
}
</style>
</head>
<body>
<div id="col1"><span>Hover to view and click to select this color.</span></div>
<div id="col2"><span>Hover to view and click to select this color.</span></div>
<p>This is some text.</p>
<script type="text/javascript">
var pElements = document.getElementsByTagName("p");
$('#col1').click(function(){
for(var i = 0; i < pElements.length; i++) {
pElements[i].style.color = "#f00";
}
});
$('#col2').click(function(){
for(var i = 0; i < pElements.length; i++) {
pElements[i].style.color = "#ff0";
}
});
</script>
</body>
</html>
What i actually want is that when i hover a color div, the color of text in p tag changes for only that time when the color div is hovered. When the color div is clicked the color of text should change permanently.
The problem with is that once i click on 1 of the color divs to finalize it for p tag, and then after that the other color is hovered the color change doesnt take place. The color permanently changes on click as it should happen.
When you set the p elements style with pElements[i].style.color = "#f00"; you are setting a more specific style then the one applied by your hover. In CSS, the most specific style get's applied to the element. The CSS hover class you've got defined will never be applied because it is not specific enough to overwrite the inline styles applied by your javascript code.
You could modify your CSS hover class to use the !important tag, this should allow you to apply the hover style even though it is not as specific as the inline style.
#col2:hover ~ p {
color: #ff0 !important;
}
If its not a problem using JQuery, I think is what you want: Live Example
HTML code snippet
<div id="col1"><span>Hover to view and click to select this color.</span></div>
<div id="col2"><span>Hover to view and click to select this color.</span></div>
<p>This is some text.</p>
CSS code snippet
p {
font-family: Tahoma;
line-height: 170%;
color: #000;
font-size: 15px;
padding: 5px 0px 5px 0px;
text-align: center;
}
#col1 {
//some propeties
}
#col1:hover ~ p {
color: #f00 !important;
}
#col2 {
//some propeties
}
#col2:hover ~ p {
color: #ff0 !important;
}​
JS code snippet
$("#col1").click(function () {
$("p").css("color","#f00");
});
$("#col2").click(function () {
$("p").css("color","#ff0");
});
Hope it helps!

Categories

Resources