Passing variable to css as title - javascript

I see that you can create "variables" inside css:
https://www.w3schools.com/cssref/func_var.asp
My files:
(style.css file)
[title~=--myVariable] {
color: red
}
(App.js file)
...
return (
<div className="App">
<h1 title="thisIsTheTitle"> Some text in red color ? </h1>
</div>
)
Is it possible to do so that if my header has a title, then the color is red
otherwise stays at is (black)
UPDATE
I forgot initialize myVariable, so:
(style.css file)
:root {
--myVariable: white;
}

you can set fallbacks with css var().
however please note:
The var() function cannot be used in property names, selectors or anything else besides property values
MDN
update: I saw you're edit, so as the quote above that will not work.

To answer this part:
Is it possible to do so that if my header has a title, then the color is red otherwise stays at is (black)
(style.css file)
.App h1 {
color: black;
}
.red {
color: red;
}
(App.js file)
...
function App({ headerTitle }) {
return (
<div className="App">
<h1 title={ headerTitle }
className={headerTitle ? 'red' : null } >
Some text in red color ? </h1>
</div>
)
}

Related

how to apply css ::before last word

Is there any possibilities to apply different background colour for ::before last word
eg : `
<style>
.test::before{
content : 'stack overflow';
color: red;
}
</style>
<p class="test"></p>
`
In this above mentioned example, I want add different colour for "overflow" text,
any idea ?
To render the output you want to visualize, this could be a way:
.test::before {
content: 'stack';
}
.test::after {
content: ' overflow';
color: red;
}
<p class="test"></p>
But It's not appropriate. If your content is just decorative, why don't you put it into a <span>?

VueJS: dynamic class name inside style tags

I have a VueJS application which contains some Materializecss modals, all wrapped within single page components. Due to the nature of the application I have to assign dynamic unique IDs to each modal. Below is a snippet:
<template>
<div :id="modal_id" :class="'modal '+modal_id">
<div class="modal-content">
.... stuff here
</div>
<div class="modal-footer">
<a class="modal-close waves-effect waves-green btn-flat">Exit</a>
</div>
</div>
</template>
<style type="text/css" scoped>
.modal {
width: 90% !important;
height: 100% !important;
}
.modal_id
{
background-color: black;
}
</style>
<script type="text/javascript">
import pdf from 'vue-pdf'
export default {
data: function() {
return {
modal_id: 'ViewPdf_'+this.$root.g(), // this.$root.g() returns a unique integer
}
},
}
</script>
My question is if it's possible to use Vue to modify the custom class name from within <style></style> tags to match the class name generated when component is mounted. If not, what workarounds I could use?
<style type="text/css" scoped>
.modal {
width: 90% !important;
height: 100% !important;
}
.modal_id // <--- I wish this class name was the same with value of this.modal_id
{
background-color: black;
}
</style>
If the CSS is all contained in your Vue component, you could just produce the style information in your component rather than trying to match up the css selector based on the DOM id.
Specifically, instead of doing this:
<div :id="modal_id" :class="'modal '+modal_id">
Do this:
<div :id="modal_id" :style="modalStyle">
and then within your component, have a computed property for the style, using the guidelines at https://v2.vuejs.org/v2/guide/class-and-style.html#Binding-Inline-Styles
For example:
computed: {
modalStyle: function () {
return {backgroundColor: 'black'};
}
}
You can build a computed property that will react to changes in modal_id and calculate a class name that you want to attach to particular modal.
<template>
<div :id="modal_id" :class="className">
...
</div>
</template>
<script type="text/javascript">
export default {
data: function() {
return {
}
},
computed: {
className: function () {
if (this.modal_id === <your modal_id1>) return 'class1';
else if (this.modal_id === <your modal_id2>) return 'class2';
},
modal_id: function () {
return 'ViewPdf_'+this.$root.g()
}
}
}
</script>
<style>
.class1{}
.class2{}
</style>
the modal_id also should be a computed property if you want to make it dynamic.
Yes, you can edit the css property name with javascript if you use an external css file. Here is a simple example in pure javascript that shows how I change the name of the css name, thereby placing its style on the second paragraph.
//the index of the stylesheet based on load order
var cssIndex = 0;
var cssRules = (document.all) ? 'rules' : 'cssRules';
function changeClass() {
for (i = 0, len = document.styleSheets[cssIndex][cssRules].length; i < len; i++) {
if (document.styleSheets[cssIndex][cssRules][i].selectorText === ".text") {
document.styleSheets[cssIndex][cssRules][i].selectorText = ".text2";
return;
}
}
}
.text {
text-align: center;
}
<button onclick='changeClass()'> Change css property class name </button>
<p id="1" class="text">This is text class</p>
<p id="2" class="text2"> This is text2 class</p>
I hope you can apply it in your Vue code.

CSS manipulation using buttons

I am trying to make a small settings page where users can change how the site looks, I want them to be able to click a button and the sites CSS update along with it (along with the background colo(u)r) and I would like the changes saved across all pages.
How would I do this?
From your question, I have come up with a solution that suits your use case better in a neater implementation.
Take the following code for example;
<div id="container">
<div>
<h1>Page Header</h1>
<h3>Page Sub Header</h3>
<p>Page Content</p>
</div>
<div class="buttons">
<button id="default-theme" onclick="setTheme(event)">default</button>
<button id="theme-one" onclick="setTheme(event)">theme one</button>
<button id="theme-two" onclick="setTheme(event)">theme two</button>
</div>
</div>
In the code above, you have some unstyled elements and some buttons to set the preferred theme color.
You can set the theme colors like below in your CSS file. The code below is an SCSS implementation. Check out the live solution on codePen https://codepen.io/sirwhite/pen/mdbNjLG
<style>
// Default theme color
.default-theme {
background: $default-bg;
}
.default-theme h1 {
color: $default-color;
}
.default-theme h3 {
color: $default-color;
}
.default-theme p {
color: $default-color;
}
// Theme One Colors
.theme-one {
background: $theme-one-bg;
}
.theme-one h1 {
color: $theme-one-color;
}
.theme-one h3 {
color: $theme-one-color;
}
.theme-one p {
color: $theme-one-color;
}
// Theme Two Colors
.theme-two {
background: $theme-two-bg;
}
.theme-two h1 {
color: $theme-two-color;
}
.theme-two h3 {
color: $theme-two-color;
}
.theme-two p {
color: $theme-two-color;
}
</style>
Now, use javascript to set the theme color based on the user's selection
var theme = '';
var container = document.getElementById('container');
window.addEventListener('load', function() {
if(localStorage.theme && localStorage.theme !== '') {
theme = localStorage.theme;
container.classList.add(theme);
}
else {
theme = 'default-theme';
}
});
function setTheme(event) {
theme = event.target.id ;
localStorage.theme = theme;
container.classList = [];
container.classList.add(theme);
}
You can use LocalStorage to persist the selected theme value across all pages. When the page loads, you can check if localStorage value is set else set the theme to the default theme.
Check out the live solution on codePen https://codepen.io/sirwhite/pen/mdbNjLG
You could do this with javascript or jquery by calling a function when your button is clicked.
Our HTML, notice how we call myFunction when we click on the button.
<h1 class="item blue">Hello World</h1>
<button onClick="myFunction()">Click Me</button>
Some basic CSS:
.blue {
color: blue;
}
.red {
color: red;
}
Our Javascript will add a class depending on what class is already present. We can change our target variable to add/remove classes from a different element.
function myFunction() {
var target = document.querySelector('.item');
if (target.classList.contains('red')) {
target.classList.remove('red')
target.classList.add('blue')
} else if (target.classList.contains('blue')) {
target.classList.add('red')
target.classList.remove('blue')
}
}
This is a very cookie-cutter way of doing this, but it works and you can take the same principles here and apply it to your code.
To use this site-wide, just use a seperate javascript file and import the same javascript and call the same function on each page.
Hope this helps :)
As per my understanding of the question you want to change the background colour on the button click
<!DOCTYPE html>
<html>
<head>
<style>
.yellows {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<button id="btn">click me </button>
<script>
$('#btn').click(function() {
$('body').toggleClass( "yellows" );
});
</script>
</body>
</html>

How to bypass React's error handling of colors

Trying to figure out if there is away of bypassing React's error handling for colors.
The first inner DIV serves as a default with an empty background if a user inputs a color that is incorrect, whether a Hex color or a string.
The second inner DIV sits on top of the first, and is meant to display the color of this.props.value.
This works fine to show my emptyBackground value in the first div, and when a correct color is inputed by the user, say orange, the second div will display a background color of orange, overlapping the first.
Now if I were to change orange to orangered, this div will change to orangered.
The part I am trying to get around is when I type orangere, it will still show the original orange color instead of the default background of the second div. It seems that react will not prompt a re-render when an improper color has been entered. Any way to get around this?
export default class ColorRender extends Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.props.onChange(e.target.value);
}
render() {
const disabled = this.props.disabled || this.props.readonly;
return (
<div
style={{ position: 'relative' }}
>
<input
type="text"
value={this.props.value}
placeholder={this.props.placeholder}
onChange={this.onChange}
style={{
marginBottom: 20,
width: `calc(100% - ${COLOR_BOX_WIDTH}px - ${COLOR_BOX_MARGIN_RIGHT}px - ${COLOR_BOX_MARGIN_LEFT}px)`,
}}
disabled={disabled}
/>
<div
style={{
...contentStyle,
backgroundImage: `url(${emptyBackground})`,
}}
/>
<div
className="color-display"
style={{
...contentStyle,
backgroundColor: this.props.value,
zIndex: 1000,
}}
/>
</div>
);
}
}
This behavior has nothing to do with React. Modern browsers will simply ignore attempts to set color properties to an unsupported value. You can easily try this yourself by opening up the dev console, selecting a DOM element somehow, and setting its color to orange with something like myElement.style.backgroundColor = 'orange'. Then try setting it to an invalid value like 'orangere'. The element will remain orange instead of reverting to an default or inherited value.
Probably the best way to address this would be to manually check that the user input is a valid color. Something like the is-color package will check not only if it's a valid color name, but HEX and RGB values as well. If the user input is valid, have React render it as usual. But if it's invalid, you can catch that and use a default or inherited value instead.
Although, this is a standard DOM element behavior (as noted by #jered), you can override it with react.
Wrap the .color-display div with another div (the .color-display-wrapper), and set the default color on it. Update the .color-display background via a CSS variable. If the value in the variable is invalid, the background color would be transparent, and the wrapper's background would be displayed.
class ColorRender extends React.Component {
state = { color: 'orange' };
onChange = (e) => this.setState({ color: e.target.value });
render() {
const {color} = this.state;
return (
<div>
<input type="text" onChange={this.onChange} />
<div className="color-display-wrapper">
<div
className="color-display"
style={{ '--color': color }}
/>
</div>
</div>
);
}
}
ReactDOM.render(
<ColorRender />,
demo
);
:root {
--color: transparent;
}
.color-display-wrapper {
width: 200px;
height: 200px;
background: url(https://picsum.photos/200/200);
}
.color-display {
position: relative;
background: var(--color);
height: 100%;
}
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="demo"></div>

Change color of glyph icon

The standard glyph icons are pretty boring
https://www.w3schools.com/bootstrap/bootstrap_ref_comp_glyphs.asp
The following code works, but instead of a filled in star with black, is there a way to make it some other color, e.g., orange?
In addition, is there a more interesting set of icons for download to use for buttons?
const glyphStarEmpty = 'glyphicon glyphicon-star-empty';
const glyphStarFull = 'glyphicon glyphicon-star';
class Checkbox extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false,
currentGlyph: glyphStarEmpty
};
this.toggleChecked = this.toggleChecked.bind(this);
}
toggleChecked() {
if(this.state.currentGlyph == glyphStarEmpty){
this.setState({
currentGlyph : glyphStarFull
})
}
else{
this.setState({
currentGlyph : glyphStarEmpty
})
}
this.setState({
checked: !this.state.checked
});
}
render() {
return (
<button className={this.state.currentGlyph} onClick={this.toggleChecked}></button>
);
}
}
You can do that with simple css
<span class="icon-some"></span>
.icon-some {
color: orange;
}
Wow, why so complicated? Just add some CSS inside the <head> tag:
<style type="text/css">
.glyphicon { color: orange; }
</style>
Another icons that you can use are from font awesome.They have tons of button icons and i'm sure you'll like it,i've used this icons for a lot of websites,to change the colors simply ad some css as other members told you before me
You could use an inline style:
<button style={{ color: 'orange' }} className={this.state.currentGlyph} onClick={this.toggleChecked}></button>
If you want a black outline in addition, try this:
<button style={{ color: 'orange', textShadow: '0 0 1px black' }} className={this.state.currentGlyph} onClick={this.toggleChecked}></button>
You could add a css color property like this:
HTML
<span class="orange glyphicon glyphicon-envelope"></span>
CSS
.orange {color: orange;}
With the help from surrounding answers, the solution became obvious. This is not perfect since I want a black border with a pure white inside (or maybe even the way stackoverflow color scheme using gray for the up/down triangles) for unchecked state for maximum contrast, but I will fix that on my own:
render() {
if(!this.state.checked)
{
return (
<button className={glyphStarFull} onClick={this.toggleChecked}></button>
);
}
else
{
return (
<button style={{ color: 'orange', textShadow: '0 0 1px black' }} className={this.state.currentGlyph} onClick={this.toggleChecked}></button>

Categories