Let's say you want to change the width of many elements, to simulate a table, for example. I realize you could do this:
$(".class").css('width', '421px');
This alters the inline style='width: 421px;' attribute for each element. Now, what I'd LIKE to do: is change the actual CSS rule definition:
.class {
width: 375px; ==[change to]==> 421px;
}
When it comes to 100's if not 1000's of nested <ul> and <li> that need to be changed, it seems like this would be better for performance than trying to let jQuery do the work through the .css() method.
I've found this example - this IS what I'm trying to do:
var style = $('<style>.class { width: 421px; }</style>')
$('html > head').append(style);
I'm NOT trying to swap classes ($el.removeClass().addClass()), because I can't have a class for EVERY optimal width (379px, 387px, 402px..).
I could create a <style> element and dynamically set the width, however I'm thinking there's a better way.
document.styleSheets[0].addRule works in Chrome, 'not a function' in FF
What works for me is to include an empty style block in the header:
<style id="custom-styles"></style>
And then manipulate that with something like this:
$('#custom-styles').text('h1 { background: red }')
I've tested this appears to work in current version of Chrome (well, Chromium - 63.0) and Firefox (57.0.4).
Related
What is the best practice for creating specific page breaks in SAPUI5 and is it actually possible?
Classical CSS atributes page-break-after and page-break-beforedoesn't seem to work in my case. For example, I have two sap.m.VBox elements and I attached them a CSS class which specifies page-break-after: always !important;when printing, but nothing happens. If I add
* {overflow-x: visible !important; overflow-y: visible !important;} then it will break and continue to draw the content in next page if it doesn't fit in one page, but it doesn't work in IE.
I have tryed also adding an empty div element that would work as a page break indicator, but still CSS wouldn't do anything. I guess that's because everything in SAPUI5 is put into one content div.
You can solve this by adding an empty element in between.
If you want a break that is 200 pixels high, your page content can look like this:
return new sap.m.Page({
content:[
oVBox1,
sap.m.Panel({height: "200px", width: "100%}),
oVBox2
]
});
ofcourse you might want to set your panel background-color to transparent ;)
The "page-break-after" is ignored because the property display of SAPUI5 views is set to inline-block.
Simply override the CSS style for the corresponding class with a custom CSS and it should work:
.sapUiView {
display: block;
}
I learned html and css a week ago. I completed my first project only to find that a div tag I used was not resizing to mobile formats. I have done some research and it seems the answer may reside with JQuery or .JS. I am working within a contained environment, Wordpress.com, and I don't know Java Script yet, but I am familiar with if then statements from studying logic for years.
So I effectively have two problems:
Can I use JQuery with inline html: no css?
How do I do it?
I know I am way off here. I am in the process of going through a .JS tutorial on codeacademy, but I am not finished.
Just thought I would try for advice here. I may not even be in the ballpark!
Here is my div tag and here is what I attempted:
<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>
$(window).resize(function() {
if ($(this).width() < 951) {
$('.divIWantedToHide').hide(<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>);
} else {
$('.divIWantedToHide').show(<div style="width:450px;height:5px;background-color:#FFFFFF;"></div>);
}
});
Javascript is kind of over-kill for this kind of thing.
I would suggest using CSS media queries.
Paste this in and it should work just fine :)
<style>
#YourDiv{
height:5px;
background-color:#FFFFFF;
}
#media only screen and (min-width:951px){
#YourDiv{width:950px;}
}
#media only screen and (max-width:950px){
#YourDiv{width:450px;}
}
</style>
<div id="YourDiv"></div>
Instead of having your style defined in the div tag, your div now has a unique name (an id) that can be styled separately. This is incredibly useful, and most would argue necessary, once you start building more complicated pages. The #media tags do basically the same thing as your if statements, where min-width:951px will set the style when your window is AT LEAST 951px and max-width:950px sets the style when your window is AT MOST 950px. The rest of the styles that don't change are set above ONE time because they are the same regardless of window size.
And now, just for fun I'll show you how to do it in pure Javascript as well:
http://jsfiddle.net/AfKU9/1/ (test it out by changing the preview window size)
<script>
var myDiv = document.getElementById("myDiv");
window.onresize = function(){
var w = window.innerWidth;
if (w > 600){
myDiv.setAttribute("style",'position:absolute;height:50px;background-color:#CCC;width:400px;' )
}
else{
myDiv.setAttribute("style", 'position:absolute;height:50px;background-color:#333;width:100px;' )
}
}
</script>
$('.divIWantedToHide').hide() will hide the div !!
In order to apply css to this div you need to use css:
$('.divIWantedToHide').css('width':'950px','height':'5px','background-color':'#FFFFFF');
If you want to append any div and apply css to it then use append/html
$('.divIWantedToHide').append('<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>');
or
$('.divIWantedToHide').html('<div style="width:950px;height:5px;background-color:#FFFFFF;"></div>');
No, at wordpress.com you won't be able to use inline JavaScript. Not in regular posts using the HTML editor nor using the Custom Design upgrade that only includes a CSS editor.
Maybe you'll benefit from the following:
Preprocessor
WordPress.com has support for CSS preprocessors LESS and Sass (SCSS Syntax). This is an advanced option for users who wish to take advantage of CSS extensions like variables and mixins. See the LESS and Sass websites for more information. You can select which syntax you would prefer to use at the bottom of the Appearance -> Customize -> CSS panel.
If you want to resize or apply another style to some elements adapted to the device screen size, yout can just use the #media css property.
#your_div_id {
width: 950px;
/* ... */
}
#media (max-width: 38em) {
#your_div_id {
display:none;
}
}
You are trying to hide a div with class '.divIWantedToHide'. But your div does not have any class.
So you should add to your div the class:
<div class="divIWantedToHide" style="width:950px;height:5px;background-color:#FFFFFF;"> </div>
And then, you can show and hide it like here:
$(".divIWantedToHide").hide()
$(".divIWantedToHide").show()
Lately I wondered about editing elements styles not by switching their classes on dom, but by changing the actual ruleset for the css class or selector.
So instead of something like
$('.some').hide()
or
$('.some').addClass('hidden')
Why not alter a rule directly with document.styleSheets and stuff?
Wouldn't this approach be generally more performant, at least with many elements, as we'd let the browser handle the ruleset changes natively?
You could for example add an style to .some, like display: none; and all .some elements would be immedeatly be hidden. There is no need to iterate over all those elements in js and hide them manually(like the example above).
Changing rulesets directly would more likely encourage classes that are context aware(or however you would call this..), as you'd hide all #persons > .item or something.
I still don't know best practices regarding classes that are named with context in mind, like for example control names like .calendar .ticket .item, versus single functionality classes like .hidden .left .green, as I usually need both types of conventions.
I am just asking what you think about this and what are benefits and drawbacks of the modifiying stylesheet approach versus how libraries like jquery handle changing styles?
Also, what do you think is good practice, what do you regard more as a hack?
cough javascript and hacking cough
Manipulating document.styleSheets is tricky due to differing implementations and the lack of a rule selector API. Currently if you want to manipulate a rule in a stylesheet you have to go through this process:
iterate over document.styleSheets
iterate over rules within current styleSheet object
if rule matches our class, edit the rule styles
Then there's the cascading issue. How do you know that a particular style on the rule you've matched won't be overridden by a different rule somewhere in the pages stylesheets? If you just bail out after changing the first matching rule you find, you can't be sure that the styles you set will actually be applied to the element, unless you stick an !important on each one, which will leave you with a whole different set of problems.
Even when you've manipulated the style sheet rules, the browser still has the same job to do — it has to recalculate all the styles by applying the cascade.
So, manipulating styleSheets doesn't look too appealing now, does it? Stick to class switching, trust me. Using jQuery and modern APIs like querySelectorAll make it plenty fast and the browser still does all the hard work like recomputing the style values.
Such a tricky question :(
But if you take boilerplate for instance, it has a some standard classes to use like:
/* Hide from both screenreaders and browsers: h5bp.com/u */
.hidden { display: none !important; visibility: hidden; }
/* Hide only visually, but have it available for screenreaders: h5bp.com/v */
.visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: ; position: absolute; width: 1px; }
/* Hide visually and from screenreaders, but maintain layout */
.invisible { visibility: hidden; }
Where it gets tricky is, IF it is something you need to hide because of JS, then you should ONLY hide it with JS. Then it will function if JS is disabled.
If it is something that is not JS dependent, then you hide it in the HTML.
So JS function = hide with JS (either by using JS or adding hide classes)
Basic HTML hide = hide with HTML class
Styleswitching vs JS switching
Basicly JS switching gives you the oppertunity to add effect etc, just using predefined classes limits that somewhat. But would love to see some ressource comparisons :)
I have p.first_p:first-letter in my stylesheet, as I checked, it works well when class first_p is set in HTML. Problems start when I use javascript to find elements and then set their class.
Under Chrome and Opera it works fine (I need to check IE 8 and 9, and FF3).
FF 5.01 changes the class, but still pseudo class setting doesn't affect the element.
It seems that FF needs to 'refresh' css settings of element before pseudo class starts working, so I made rather dirty workaround - script replaces affected node with its clone.
Is there a better way to solve that issue? Some way to make FF recalculate everything it knows about node? Also that workaround isn't enough for IE 7.
Edit: yeah, pseudo-element not pseudo-class, my bad
It is definitely a bug. A possible work-around would be changing the display style of the element. Unfortunately, this needs to be done delayed, after the previous style change applied:
element.className = 'first-class';
element.style.display = 'inline';
setTimeout(function(){
element.style.display = '';
}, 0);
Demo: http://jsfiddle.net/pvEDY/3/
You're running into https://bugzilla.mozilla.org/show_bug.cgi?id=8253
Is it possible to not use javascript?
I'm guessing that you're applying first_p to the first paragraph of particular elements.
It possible for you to use the :first-child selector instead?
I'm not sure if this will work, but you could try something like the following, assuming you want to apply this to children of divs with class "copy"
.copy p:first-child:first-letter{
color: #abcdef; /* or whatever */
}
this definitely works and you don't need javascript, except for crappy old IE.
Alternatively you could try this:
.element p:first-letter{
font-size: 20px;
}
.element p + p:first-letter{
font-size: inherit;
}
This css makes any paragraph that is not preceded by another paragraph have a styled first letter. Would that solve your problem?
Wait, you want it to work in Firefox. Try this:
.element p:first-of-type:first-letter{
font-size: 20px;
}
It selects the first matching element. The :first-of-type pesudo-element is supported by Firefox, Opera, Chrome and Safari according to SitePoint's page for :first-of-type
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)?