I would like to be able to update a CSS variable via JS, but when I make the variable update the CSS pseudo element get's destroyed (i.e. just disappears).
Here's the SCSS code:
:root {
--test-thing: "";
}
.folder-1-open span::after {
width: 90%;
height: 85%;
bottom: 0;
left: 5%;
background-color: #fff;
z-index: 3;
content: var(--test-thing);
}
I'm trying to manipulate the variable thusly:
const root = document.documentElement
root.style.setProperty('--test-thing', "Hello World")
The CSS above works perfectly fine on the element (a label) that it's applied to, basically just a white square, but as soon as I try and update the CSS variable --test-thing to add a string via the content prop, the whole thing just disappears.
Is it not possible to do this with a pseudo element or class?
From researching related posts on SO, my understanding was that this was possible using CSS variables.
For context, I’m working off this example of a pure CSS interactive folder (when it’s open is when I’d like to update content proper dynamically).
Ok, I figured out why this is happening, sort of. Still not 100% sure why, but it has something to do with the fact that the new value isn't in quotes. Just put the value in quotes and it works fine.
const root = document.documentElement
root.style.setProperty('--test', "'Hello World'") // <-- this needs to be in quotes
:root {
--test: "";
}
#test {
height: 100px;
width: 100px;
background: #ccc;
}
#test:after {
content: var(--test);
min-width: 100px;
background: #000;
min-height: 30px;
color: #fff;
}
<div id="test">
</div>
Related
I want to change the value of one of the attributes of css class dynamically
Here's my scenario:
I've many elements using one class, instead of getting them all and looping them over and applying style, I want to change the value of one of the attributes of class, which is alredy applied on them. for example
.prodName {
max-width: 270px;
display: block;
}
above class is being used by many elements, and I want to alter one of the attributes of that class like
.prodName {
max-width: 350px <---
display: block;
}
is there any simple method for this in javascript.
Before I post this question, I already searched but didn't find anything easy and useful.
thanks in advance to helping hands.
You can use CSS variables for this case.
const root = document.querySelector(':root');
function play() {
root.style.setProperty('--size', '300px');
}
:root {
--size: 100px;
}
.container {
background-color: red;
width: var(--size);
height: var(--size);
cursor: pointer;
}
<div class="container" onclick="play()"></div>
The only problem with the above approach is support in older browsers. If you have to support IE, and older browsers where CSS variable support is not present, you can handle this problem by adding a class to the body/parent container.
function play() {
document.body.classList.add('large')
}
.container {
background-color: red;
width: 100px;
height: 100px;
cursor: pointer;
}
.large .container {
width: 300px;
height: 300px;
}
<div class="container" onclick="play()"></div>
Add new class to CSS:
.mw350 {
max-width: 350px;
}
Then add new class to the element in JS:
document.querySelector('.prodName').className += ' mw350'; // <-- better to select using unique IDs, like '#prodNameElement'
If you are going to control the css class/attribute change from ts, maybe with a function or var change, you might want to use ngClass: https://www.freecodecamp.org/news/angular-ngclass-example/ and have all the logic where you want it, easily accessible.
I have a jQuery custom scrollbar, and I invoke it like this:
<script>
(function($){
$(window).on("load",function(){
$(".main_text,#C2,.png_container").mCustomScrollbar();
});
})(jQuery);
That works correctly for all of the page elements except .png_container, but unlike the other sections, that section is only used in a JavaScript variable that is used to substitute text in a placeholder ID, and I think that's where the problem is.
Here is how it's called from an "onclick" button event:
<div class="main_text">
<div id="C2">Main Text</div>
</div>
if (type == 101) {
var X = "<header>First Section</header><br>A classic example of good form/<br><br>More information<ul type=\"circle\"><li>Element Point 1<br></li><li>Element Point 1</li></ul><i><span class=\"span_01\">So much better</i></span><br><br><div class=\"png_container\"><img class=\"png_format\" src=\"images/Element 001.png\"></div>"}
document.querySelector("#C2").innerHTML = X;}
The png_container has a separate set of scroll bars, but they are not replaced by the custom scroll bars (the other page sections do get the custom scroll bars).
Here is the relevant css:
.png_container{
overflow: auto;
overflow-y: auto;
overflow-x: auto;
height: 400px;
width: 800px;
border: 2px solid;
border-color: green;
}
#C2{
color:#DBDBDB;
font-family: camphorW04-Thin,calibri,arial;
font-size: 14pt;
text-indent: 0px;
width: auto;
margin: auto;
margin-left: 20px;
margin-right: 250px;
}
So my question is: how can I replace the scroll bars on a section that is embedded in a JavaScript variable, as shown above?
My research has found some similar questions, but none that answer this specific question, so I hope somebody knows the answer. Thanks very much for any ideas.
You initialize the mCustomScrollbar plugin on load this way:
$(window).on("load",function(){
$(".main_text,#C2,.png_container").mCustomScrollbar();
});
The two first selectors have matching elements at this moment. But there is no existing element to match the last selector since .png_container is appended on click.
So you can safely remove .png_container from the load handler...
And initialise mCustomScrollbar on .png_container when it exists.
$(window).on("load",function(){
$(".main_text,#C2").mCustomScrollbar(); // Remove .png_container
});
$(".something").on("click",function(){
if (type == 101) {
var X = "<header>First Section</header><br>A classic example of good form/<br><br>More information<ul type=\"circle\"><li>Element Point 1<br></li><li>Element Point 1</li></ul><i><span class=\"span_01\">So much better</i></span><br><br><div class=\"png_container\"><img class=\"png_format\" src=\"images/Element 001.png\"></div>"}
document.querySelector("#C2").innerHTML = X;
$(".png_container").mCustomScrollbar(); // Add this.
}
I have a menu containing onclick calls. Then my js script catches the data and sends it to a php script for processing and returns it back to my js script which is supposed to place the results into the defined document element. Simple enough, right.
For some reason though, if I set the background color in my css the results will not show. Here are the relevant parts of my code. Can someone point out to me if there is a flaw in my code; and if not, why does this behavior happen and is there a work around.
My css...
.decade { margin-left: 150px; padding: 20px; color: green; }
.slaby { position: fixed; left: 200px; bottom: 86px; top: 50px; right:50px; color: black; padding: 20px; background-color: #ddd; border: 2px solid grey; }
My html...
<div class='tln'>
<span class='point' onclick='mes(this)' go='a' >The 70's</span>
<span class='point' onclick='mes(this)' go='b' >The 80's</span>
</div>
<div id='decade' class='decade'>
<div id='slab' class='slaby'></div>
</div>
My js...
function mes(span) {
var clam = span.getAttribute('go'); var shot = 1;
$.ajax({ url:'', type:'POST',
data:{ page: clam, shoot: shot, },
success: function(snowy){
$('#slab').html(snowy);
$('#decade').html(snowy);}});}
In my js script I am placing the results in both 'slab' and 'decade' elements just for testing purposes. Now with my css the way that it is, div(decade) is showing the results, while div(slab) is still blank.
For some reason: if I remove the background color from the div(slab) The results show here; if I add a background color to the div(decade) the results still show here.
I'm looking for a way to display the results in div(slab); as well as, having css style div(slab)'s background color. Thank you all for any help and have a great day.
Some of the other comments pointed out that #slab is "inside" of #decade so when you are doing $('#decade).html() you are replacing/removing #slab.
Use
$('#decade').append()
instead or alternatively
$('#decade').prepend()
(SOLVED) why will jquery not put results in div with background color set.
I am not sure why the query contents were not being displayed, but changing the style for div(slab) with a z-index provided the results I was looking for.
I set the z-index for div(slab) to z-index: -1; and 'voila', works perfect.
.slaby { position: fixed; left: 200px; bottom: 86px; top: 50px; right:50px; color: black; padding: 20px; z-index: -1; background-color: #ddd; border: 2px solid grey; }
I have no idea why this works because no other element inside or outside of it has a z-index set.
Thank you all for your input and effort. I hope this solution helps somebody.
I am trying to create a div and show a timeout message in there. But it actually distorts other parts of Page. For eg see below. Session Timed out is the div with the message.
Now I don't want this to happen. PFB the JQuery code I am using to create this Div
function ShowSessionTimeOutDiv() {
var styler = document.createElement("div");
styler.setAttribute("style","font-size:15px;width:auto;height:auto;top:50%;left:40%;color:red;");
styler.innerHTML = "<b><i>Session TimedOut, Please refresh the Page</i></b>";
document.body.appendChild(styler);
var currentDiv = $('#GoToRequestControl1_UpdatePanel1').get(0);
currentDiv.parentNode.insertBefore(styler,currentDiv) ;
}
Am I missing something here? The Part in which this div is being displayed is coming from Master Page.
Have you tried the position:fixed styling on it in css, i did that on one of my websites and it didn't distort anything.
A page has a natural flow of its elements based on the default display rules specified by the W3C. When you add a div in between other elements it naturally affects the layout of the page; the positions of the other elements.
In order to drop in a new element without it affecting other elements you have to either reserve space for it, or take it out of the normal page flow.
There are a couple of ways to take an element out of the flow — you can float it, float:left or float:right, which is great, for example, to stack blocks on the left (instead of top-down) and let them wrap to new rows as available width changes. Using a flex layout gives you a lot of control also. But in this case of one thing popping up, changing the positioning of the new element is the most straightforward and can let you put the block exactly where you want it.
I have a demonstration and full explanation in a fiddle showing several examples along the way to getting what you want.
Basically, styling is needed to reposition the timeout message element that you're inserting. Styling is better done with CSS styles, compared to adding a bunch of inline styles. If I put my timeout popup message in a "messagebox" I can make a class for it.
/* Your styles, plus a couple extra to make the example stand out better */
div.messagebox {
font-size: 16px;
width: auto;
height: auto;
top: 40%;
left: 30%;
background-color: white;
border: 2px solid black;
}
Likewise, style the message itself with a class, instead of using inline styles and the deprecated presentational tags <b> and <i>.
/* I want the message in a messagebox to be bold-italic-red text. */
div.messagebox .message {
color: red;
font-style: italic;
font-weight: bold;
}
The big difference is that we will change the positioning of the element from the default static to instead use absolute positioning:
/* I don't really recommend a class called "positioned".
A class should describe the kind of thing the element *is*
not how it *looks*
*/
div.messagebox.positioned {
position: absolute;
width: 40%;
padding: 1.5em;
}
/* The container of the positioned element also has to be positioned.
We position it "relative" but don't move it from its natural position.
*/
section#hasposition {
position: relative;
}
The term "absolute" is tricky to learn ... the element being positioned is given an absolute position within its container, in a sense it's positioned relative to its container... but what position:relative means is relative to its own natural position, so it's easy to get confused at first over whether you want absolute or relative positioning.
Putting it all together, we have some basic HTML that represents major portions of a page — a real page will have far more, but those should be contained within some top-level containers. This shows only those top-level containers.
Then we have some javascript that will add the new element at the appropriate time. Here I just call the function to add it after a delay created with setTimeout(). I'm using full-on jQuery since you're using some in your example, and it makes the javascript more portable and more concise.
function ShowSessionTimeoutStyled() {
var styler = $('<div>').addClass('messagebox').addClass('positioned');
styler.html('<span class="message">The Session Timed Out</span>');
$('#hasposition .above').after(styler);
}
// wait 6 seconds then add the new div
setTimeout(ShowSessionTimeoutStyled, 6000);
div.messagebox {
font-size: 16px;
width: auto;
height: auto;
top: 20%;
left: 20%;
background-color: white;
border: 2px solid black;
}
div.messagebox .message {
color: red;
font-style: italic;
font-weight: bold;
}
div.messagebox.positioned {
position: absolute;
width: 40%;
padding: 1.5em;
}
section#hasposition {
position: relative;
}
/* also style some of the basic parts so you can see them better in the demonstration */
section.explanation {
margin: 1em 0.5em;
padding: 0.5em;
border: 1px solid gray;
}
.demonstration {
margin-left: 1em;
padding: 1em;
background-color: #e0e0e0;
}
.demonstration .above {
background-color: #fff0f0;
}
.demonstration .middle {
background-color: #f0fff0;
}
.demonstration .below {
background-color: #f0f0ff;
}
.demonstration footer {
background-color: white;
}
p {
margin-top: 0;
padding-top: 0;
}
section {
font-family: sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="explanation">
<p>Here, a div is added dynamically, after the "basic part above", but the added div is <em>positioned</em>. You can see the other content isn't affected.</p>
<section class="demonstration" id="hasposition">
<div class="above">Basic part above</div>
<div class="middle">Middle part</div>
<div class="below">Part Below</div>
<footer>This is the page footer</footer>
</section>
</section>
I highly recommend the site Position Is Everything for articles and tutorials on positioning. Some of its other content is outdated — who needs to make PNGs to do drop-shadows any more? — but the way positioning works hasn't changed.
I am currently doing some styling and have thought up an interesting way to do something. I want to create a piece of text that stands out among every other bit of text on the page. Below you can see the way I've done this.
var el = document.querySelectorAll('span[class^=impact]')[0],
col = el.className.split('-')[1];
el.style.textShadow = '2px 2px 0 #' + col;
html, body {
width: 100%;
height: 100%;
margin: 0;
background-image: url('http://i.imgur.com/UxB7TDq.jpg');
}
[class^=impact] {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
font-family: Impact, sans-serif;
font-size: 72pt;
font-weight: 800;
text-transform: uppercase;
}
<span class="impact-008080">impact</span>
As you can see I'm basically getting the first half of the class and applying styles to it and grabbing the second half of the class in JavaScript and applying the shadow then. What I want to do is omit the JavaScript completely and keep it all in CSS.
I do not have a list of colours. Any and all hex colours are supported obviously. I would prefer to keep this format.
CSS attr
Theoretically, this type of thing is what the CSS attr property could be used for when browser support exists. Note that this won't work now, but when browser support does exist, it might look something like this:
HTML
<span class="impact" data-shadow="#008080">Impact</span>
CSS
.impact {
/* you text and positioning styles here */
text-shadow: 2px 2px attr(data-shadow);
}
You can read more about the attr property here:
https://developer.mozilla.org/en-US/docs/Web/CSS/attr
But for now...
Your best bet is probably to continue to use JavaScript, but instead of appending the hex code to the class name, store the hex value in a data attribute of the element, allowing you to keep the class name consistent for all instances of that element.
HTML
<span class="impact" data-shadow="#fff">Impact</span>
CSS
.impact {
/* your text and position styles here */
}
JS
var el = document.querySelector(".impact"),
shadow = el.dataset.shadow;
el.style.textShadow = '2px 2px ' + shadow;
Here's a JSFiddle for reference: http://jsfiddle.net/galengidman/xx6r1n2o/