Inherit/Extend CSS properties onto another element - javascript

What's the most efficient way in jQuery to extend/inherit CSS properties from one element to another?
Desired effect
$('#blah').extendCSSTo('#me') // Is there a plugin or a good way to do this?
$('#me').css({ background: 'blue' });
#me will now have all the CSS of #blah and also background
CSS:
#blah {
padding: 5px;
width: 200px;
height: 20px;
border: 1px solid #333;
font-family: "Verdana";
}
#me {
position: absolute;
left: 5px;
top: 5px;
}
<div id="blah"></div>
<div id="me">test</div>
Edit: This will be used in a plugin so using classes and simply doing .addClass is not an option
I'm looking for the same effect as setting default value for plugin options, but instead for CSS:
$.extend([css object], [#blah css object], [#me css object])

$('#me').addClass('class');
This works, not sure if you can use the css relative to an ID though.

Try this.
function CloneStyle(sourceID, targetID){
var myStyle;
var source = document.getElementById(sourceID);
var target = document.getElementById(targetID);
if (window.getComputedStyle) {
myStyle = window.getComputedStyle(source).cssText;
}
else if (source.currentStyle) {
myStyle = $.extend(true, {}, source.currentStyle);
} else {
throw "antique browser!";
}
target.style.cssText = myStyle;
}
Now call like.
CloneStyle("blah", "me");
$('#me').css({ background: 'blue' });
Fiddle here: http://jsfiddle.net/naveen/3FdDp/

If you were to use CSS classes rather than ID references you could do the following:
$("#me").addClass($("#blah").attr("class"));
Which would copy the classes from #blah to #me

Related

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.

Dynamically add !important to all CSS properties

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.

Style all but one element to dim background

Looking to achieve a dimmed-background effect by dimming (or changing the opacity of) all elements on the page but one; I've been trying out :not() as well as some jQuery selectors to try and exclude all but the element, but to no avail. Does anyone know of the best way to do this with SASS/Compass or, failing that, jQuery?
So far, I've tried things like:
.opacityFade:not(.classToExclude) {
STYLES HERE
}
or
$('controlElement').click(function(){
$(body).not('desiredTargetToExclude').toggleClass('classThatFadesStuffOut');
});
Ideally, I'd like to avoid having to write more JS and better separate responsibilities,but there might not be a way to do that. Little new to Front-End development, so I'm not aware of a best way to go about doing this; thanks!!
You can achieve this by placing a blanket over all elements, and then pulling the element you want to display out of the DOM order with the z-index property
.item {
background: #f00;
width: 100px;
height: 100px;
display: inline-block;
margin: 10px;
}
.item.selected {
position: relative;
z-index: 200
}
.blanket {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: black;
opacity: 0.5;
z-index: 100;
}
Note that the element needs to have a non static position.
See http://jsfiddle.net/cyberdash/fCMaT/
you could add another class to the non-dimmed/active div. I'll put together a fiddle.
http://jsfiddle.net/nqT7V/
In Jquery:
$(".item").click(function(){
var $this = $(this);
$this.parent().addClass("dimmed");
$this.parent().find(".item").removeClass("active");
$this.addClass("active");
});
$(".holder").click(function(e){
if (e.target != this) return;
var $this = $(this);
if ($this.hasClass("dimmed")){
$this
.removeClass("dimmed")
.find(".item").removeClass("active");
}
});

How can I give a javascript element a CSS class?

I've got the following code
var addressPopupMenu = window.createPopup();
function showAddressPopup() {
var popup = document.getElementById('addressFullSpan');
popupMenuBody = popupMenu.document.body;
popupMenuBody.style.backgroundColor = "#336699";
popupMenuBody.style.border = "solid 2px; white";
popupMenuBody.style.fontSize="130%";
popupMenuBody.style.color="white";
popupMenuBody.style.padding="10px";
popupMenuBody.style.paddingLeft="30px";
As you can see I'm repeating popupMenuBody.style. How can I give popupMenuBody.style a css class so I dont have to repeat this for every popup
edit: it's not working
I've added popupMenuBody.className = "popups";
.popups
{
background-color: #29527A;
border: solid 2px; white;
fontSize:120%;
pcolor:white;
padding:10px;
paddingLeft:30px;
textTransform:capitalize;
}
also yes, i am including the .css in my page its working else where on the page
popupMenuBody.className = "class_name";
popupMenuBody.className = "my class";
.popups
{
background-color: #29527A;
border: solid 2px white;
font-size: 120%;
color: white;
padding: 10px;
padding-left: 30px;
text-transform: capitalize;
}
use jquery addClass?
http://api.jquery.com/addClass/
I would do it using Jquery and addClass():
$('#addressFullSpan').addClass('name')
jQuery has the method addClass() for applying a CSS class to an element
http://api.jquery.com/addClass/
Have you tried :
var addressPopupMenu = window.createPopup();
function showAddressPopup() {
var popup = document.getElementById('addressFullSpan');
popupMenuBody = popupMenu.document.body;
popupMenuBody.className = "className";
...
}
To assign a CSS class to an element created in JavaScript, you can just use the following line of code:
popupMenuBody.className = "popups";
You've said that this doesn't work, but this is actually because your CSS is broken. I'm assuming that you've copy/pasted some JavaScript into your CSS file and changed it a bit, and as a result, your property names are all wrong. What you actually need for your CSS is this:
.popups
{
background-color: #29527A;
border: solid 2px white;
font-size:120%;
color:white;
padding:10px;
padding-left:30px;
text-transform:capitalize;
}
Notice that I have:
removed the ";" between "2px" and "white"
renamed "fontSize" to "font-size"
renamed "pcolor" to "color"
renamed "paddingLeft" to "padding-left"
Your CSS should now get applied correctly.
To avoid overwriting existing classnames on popupMenuBody, do this:
popupMenuBody.className += ' class_name';

Categories

Resources