This question already has answers here:
Changing a CSS rule-set from Javascript
(9 answers)
Closed 4 years ago.
I want to set an element's height to window.innerheight but I have to do it in CSS because somehow I don't have access to that element to use javascript to change it's style.
Is there a way to do that? like changing a CSS class in javascript?
I tried this:
document.getElementById('root').style.setProperty('--view-height', window.innerHeight +'px');
and in CSS:
.menu {
height: var(--view-height) !important;
}
and it works but CSS Variables is not supported in older browsers so I can't use that, but I want something similar.
EDIT:
There is many answer yet they all use javascript, i said i CAN NOT USE js to set the element style! i want to do it only by css class style
In modern browsers you can use:
document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyOtherClass');
Although, for accomplishing your specific case, I'd go with לבני מלכה's answer.
Maybe use proper CSS instead:
window.innerHeight +'px' results in the same height as using 100vh. The unit vh means "viewport height" and 100vh is the full height of the inner window.
See: https://developer.mozilla.org/en-US/docs/Web/CSS/length#Viewport-percentage_lengths
Set height in javascript instead use variables
document.getElementById('root').style.height=window.innerHeight +'px';
See example:
document.getElementById('root').style.height=window.innerHeight +'px';
#root{
background-color:red;
}
<div id="root"></div>
To your edit no use js use height:100vh; :
#root{
height:100vh;
background-color:red;
}
<div id="root"></div>
using vh unit is the proper way to do this.. (although Mahboobeh Mohammadi said that it isn't compatible with ios)
height: 100vh; is the full height of the view..
For Normal Js
function addClassById (_id,_class) {
document.getElementById(_id).classList.add(_class);
}
function removeClassById (_id,_class) {
document.getElementById(_id).classList.remove(_class);
}
addClassById("root","newClass")
I advise to you use JQUERY it s very easy to use.
Put this cdn link on your head tag then use it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
//This is for change css
$("#root").css({
"background-color": "yellow",
"font-size": "200%"
});
// This is how to add class
$("#root").addClass('newClass');
// This is how to remove class
$("#root").removeClass('newClass')
I hope it help you.
Related
This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
How to update placeholder color using Javascript?
(5 answers)
Closed 2 years ago.
Is it possible to change a CSS pseudo-element style via JavaScript?
For example, I want to dynamically set the color of the scrollbar like so:
document.querySelector("#editor::-webkit-scrollbar-thumb:vertical").style.background = localStorage.getItem("Color");
and I also want to be able to tell the scrollbar to hide like so:
document.querySelector("#editor::-webkit-scrollbar").style.visibility = "hidden";
Both of these scripts, however, return:
Uncaught TypeError: Cannot read property 'style' of null
Is there some other way of going about this?
Cross-browser interoperability is not important, I just need it to work in webkit browsers.
If you're comfortable with some graceful degradation in older browsers you can use CSS Vars. Definitely the easiest of the methods I've seen here and elsewhere.
So in your CSS you can write:
#editor {
--scrollbar-background: #ccc;
}
#editor::-webkit-scrollbar-thumb:vertical {
/* Fallback */
background-color: #ccc;
/* Dynamic value */
background-color: var(--scrollbar-background);
}
Then in your JS you can manipulate that value on the #editor element:
document.getElementById("#editor").style.setProperty('--scrollbar-background', localStorage.getItem("Color"));
Lots of other examples of manipulating CSS vars with JS here: https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/
To edit an existing one which you don't have a direct reference to requires iterating all style sheets on the page and then iterating all rules in each and then string matching the selector.
Here's a reference to a method I posted for adding new CSS for pseudo-elements, the easy version where you're setting from js
Javascript set CSS :after styles
var addRule = (function (style) {
var sheet = document.head.appendChild(style).sheet;
return function (selector, css) {
var propText = typeof css === "string" ? css : Object.keys(css).map(function (p) {
return p + ":" + (p === "content" ? "'" + css[p] + "'" : css[p]);
}).join(";");
sheet.insertRule(selector + "{" + propText + "}", sheet.cssRules.length);
};
})(document.createElement("style"));
addRule("p:before", {
display: "block",
width: "100px",
height: "100px",
background: "red",
"border-radius": "50%",
content: "''"
});
sheet.insertRule returns the index of the new rule which you can use to get a reference to it for it which can be used later to edit it.
EDIT: There is technically a way of directly changing CSS pseudo-element styles via JavaScript, as this answer describes, but the method provided here is preferable.
The closest to changing the style of a pseudo-element in JavaScript is adding and removing classes, then using the pseudo-element with those classes. An example to hide the scrollbar:
CSS
.hidden-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
JavaScript
document.getElementById("editor").classList.add('hidden-scrollbar');
To later remove the same class, you could use:
document.getElementById("editor").classList.remove('hidden-scrollbar');
I changed the background of the ::selection pseudo-element by using CSS custom properties doing the following:
/*CSS Part*/
:root {
--selection-background: #000000;
}
#editor::selection {
background: var(--selection-background);
}
//JavaScript Part
document.documentElement.style.setProperty("--selection-background", "#A4CDFF");
You can't apply styles to psuedo-elements in JavaScript.
You can, however, append a <style> tag to the head of your document (or have a placeholding <style id='mystyles'> and change its content), which adjusts the styles. (This would work better than loading in another stylesheet, because embedded <style> tags have higher precedence than <link>'d ones, making sure you don't get cascading problems.
Alternatively, you could use different class names and have them defined with different psuedo-element styles in the original stylesheet.
I posted a question similar to, but not completely like, this question.
I found a way to retrieve and change styles for pseudo elements and asked what people thought of the method.
My question is at Retrieving or changing css rules for pseudo elements
Basically, you can get a style via a statement such as:
document.styleSheets[0].cssRules[0].style.backgroundColor
And change one with:
document.styleSheets[0].cssRules[0].style.backgroundColor = newColor;
You, of course, have to change the stylesheet and cssRules index. Read my question and the comments it drew.
I've found this works for pseudo elements as well as "regular" element/styles.
An old question, but one I came across when try to dynamically change the colour of the content of an element's :before selector.
The simplest solution I can think of is to use CSS variables, a solution not applicable when the question was asked:
"#editor::-webkit-scrollbar-thumb:vertical {
background: --editorScrollbarClr
}
Change the value in JavaScript:
document.body.style.setProperty(
'--editorScrollbarClr',
localStorage.getItem("Color")
);
The same can be done for other properties.
Looks like querySelector won't work with pseudo-classes/pseudo-elements, at least not those. The only thing I can think of is to dynamically add a stylesheet (or change an existing one) to do what you need.
Lots of good examples here:
How do I load css rules dynamically in Webkit (Safari/Chrome)?
This question already has answers here:
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
(26 answers)
How to update placeholder color using Javascript?
(5 answers)
Closed 2 years ago.
Is it possible to change a CSS pseudo-element style via JavaScript?
For example, I want to dynamically set the color of the scrollbar like so:
document.querySelector("#editor::-webkit-scrollbar-thumb:vertical").style.background = localStorage.getItem("Color");
and I also want to be able to tell the scrollbar to hide like so:
document.querySelector("#editor::-webkit-scrollbar").style.visibility = "hidden";
Both of these scripts, however, return:
Uncaught TypeError: Cannot read property 'style' of null
Is there some other way of going about this?
Cross-browser interoperability is not important, I just need it to work in webkit browsers.
If you're comfortable with some graceful degradation in older browsers you can use CSS Vars. Definitely the easiest of the methods I've seen here and elsewhere.
So in your CSS you can write:
#editor {
--scrollbar-background: #ccc;
}
#editor::-webkit-scrollbar-thumb:vertical {
/* Fallback */
background-color: #ccc;
/* Dynamic value */
background-color: var(--scrollbar-background);
}
Then in your JS you can manipulate that value on the #editor element:
document.getElementById("#editor").style.setProperty('--scrollbar-background', localStorage.getItem("Color"));
Lots of other examples of manipulating CSS vars with JS here: https://eager.io/blog/communicating-between-javascript-and-css-with-css-variables/
To edit an existing one which you don't have a direct reference to requires iterating all style sheets on the page and then iterating all rules in each and then string matching the selector.
Here's a reference to a method I posted for adding new CSS for pseudo-elements, the easy version where you're setting from js
Javascript set CSS :after styles
var addRule = (function (style) {
var sheet = document.head.appendChild(style).sheet;
return function (selector, css) {
var propText = typeof css === "string" ? css : Object.keys(css).map(function (p) {
return p + ":" + (p === "content" ? "'" + css[p] + "'" : css[p]);
}).join(";");
sheet.insertRule(selector + "{" + propText + "}", sheet.cssRules.length);
};
})(document.createElement("style"));
addRule("p:before", {
display: "block",
width: "100px",
height: "100px",
background: "red",
"border-radius": "50%",
content: "''"
});
sheet.insertRule returns the index of the new rule which you can use to get a reference to it for it which can be used later to edit it.
EDIT: There is technically a way of directly changing CSS pseudo-element styles via JavaScript, as this answer describes, but the method provided here is preferable.
The closest to changing the style of a pseudo-element in JavaScript is adding and removing classes, then using the pseudo-element with those classes. An example to hide the scrollbar:
CSS
.hidden-scrollbar::-webkit-scrollbar {
visibility: hidden;
}
JavaScript
document.getElementById("editor").classList.add('hidden-scrollbar');
To later remove the same class, you could use:
document.getElementById("editor").classList.remove('hidden-scrollbar');
I changed the background of the ::selection pseudo-element by using CSS custom properties doing the following:
/*CSS Part*/
:root {
--selection-background: #000000;
}
#editor::selection {
background: var(--selection-background);
}
//JavaScript Part
document.documentElement.style.setProperty("--selection-background", "#A4CDFF");
You can't apply styles to psuedo-elements in JavaScript.
You can, however, append a <style> tag to the head of your document (or have a placeholding <style id='mystyles'> and change its content), which adjusts the styles. (This would work better than loading in another stylesheet, because embedded <style> tags have higher precedence than <link>'d ones, making sure you don't get cascading problems.
Alternatively, you could use different class names and have them defined with different psuedo-element styles in the original stylesheet.
I posted a question similar to, but not completely like, this question.
I found a way to retrieve and change styles for pseudo elements and asked what people thought of the method.
My question is at Retrieving or changing css rules for pseudo elements
Basically, you can get a style via a statement such as:
document.styleSheets[0].cssRules[0].style.backgroundColor
And change one with:
document.styleSheets[0].cssRules[0].style.backgroundColor = newColor;
You, of course, have to change the stylesheet and cssRules index. Read my question and the comments it drew.
I've found this works for pseudo elements as well as "regular" element/styles.
An old question, but one I came across when try to dynamically change the colour of the content of an element's :before selector.
The simplest solution I can think of is to use CSS variables, a solution not applicable when the question was asked:
"#editor::-webkit-scrollbar-thumb:vertical {
background: --editorScrollbarClr
}
Change the value in JavaScript:
document.body.style.setProperty(
'--editorScrollbarClr',
localStorage.getItem("Color")
);
The same can be done for other properties.
Looks like querySelector won't work with pseudo-classes/pseudo-elements, at least not those. The only thing I can think of is to dynamically add a stylesheet (or change an existing one) to do what you need.
Lots of good examples here:
How do I load css rules dynamically in Webkit (Safari/Chrome)?
I am trying to change the height of my textarea. Zurb's Foundation has already defined a height of 5rem !important.
Now, when I try to change my height using jQuery, it doesn't change. I tried:
$('textarea').height('500px')
$('textarea').css('height', '500px', 'important);
and nothing works. The CSS of any other property does change with .css(). What can I do?
If 5rem !important is set as inline style then it has the highest precedence then you can not override it by any CSS rule. You have to update the inline style then. Try this:
$('textarea').get(0).style.setProperty('height','200px','important');
From the MDN Docs
CSSStyleDeclaration.setProperty()
No return. Example: styleObj.setProperty('color', 'red', 'important')
Update:
Please read this Answer: Apply !important CSS style using jQuery
You will find really useful info there..
Happy Coding!!
Demo
You can use css - but it does not support Priority field.
Following is the correct syntax:
$('textarea').css('height','500px')
Or if you need important, you can use inline style or a class.
Demo : Add Class
.areaHeight{
height : 500px !important;
}
$('textarea').addClass('areaHeight')
There are other not-so-viable options : cssText
$('textarea').attr('style', 'height: 500px !important');
try this
<textarea id="textareaid"> </textarea>
$('#textareaid').css('height', '500px');
Try using anyone of these to set the height
Type: 1
$("textareaid").height("600")
Type: 2
$("textareaid").css("height","400px")
Make sure ur script is called after the dom element gets created
My DIV of showing the Facebook comments plugin (e.g. .fb-comments) is fixed by CSS, consider that if I cannot modify that CSS, is it possible to resize the comments plugin using pure JS solution after all comments are loaded?
<div style='background-color:red;height:200px;'
class="fb-comments" data-href="http://example.com"
data-num-posts="10"></div>
Demo: http://jsfiddle.net/8MyV3/1/
It is very much possible.
The .fb-comments class is set via CSS, but you can still use the !important flag to overwrite it.
Lets get to it:
First you need to overwrite some CSS:
.fb-comments, .fb-comments * {
width:100% !important;
}
Then you can place your facebook comments widget in its own container
<div class="fb_container">
<div class="fb-comments" data-href="http://example.com" data-num-posts="10"></div>
</div>
Optional - Style it with CSS however you want:
.fb_container{
width: 200px;
}
And then you can change it programatically with JS:
$(".fb_container").css("width","200px");
Here's a working jsFiddle example
This code should do the trick:
$('.fb-comments').attr('data-width', '200');
That will make ".fb-comments" 200px wide.
Need to update three elements to make fully resized.
$('.fb-comments').attr('data-width', '200');
$('.fb-comments span').css('width', '200');
$('.fb-comments span iframe').css('width', '200');
I was trying to adjust the position of my Fancybox with jQuery:
$('#fancybox-wrap').css("top", "200px !important");
And it wasn't working at all even with the !important bit. However if I simply do it with CSS, it's an OK deal:
#fancybox-wrap {
top: 200px !important;
}
Which leaves me really curious: is there something inside Fancybox' codes that's preventing me from changing the wrapper's CSS via JavaScript?
The css function put styles in style attribute. Some navigators seem to not allow usage of !important in inline style. But inline style should overpass css rule even if it is "important". So
$('#fancybox-wrap').css("top", "200px");
should work?
May be not a nice way but you can go this:
cssString = $('#fancybox-wrap').attr("style");
cssString = cssString.replace("top: 200px", "top: 200px !important");
$('#fancybox-wrap').removeAttr("style").attr("style", cssString);