css unable to set display:block - javascript

I'm unable to use css to set the display to block after i have used javascript to set it to none.
Is this normal or i'm missing something here?
.lightbox:target {
display: block;
}
function onClickLightBox(event) {
event.preventDefault();
target.style.display = "none";
}
lightbox.addEventListener('click', onClickLightBox);
I have had the same problem when using javascript set the display, Then #media was unable to change it once the screen resized.

The is normal.
Setting the .style.* properties sets the inline style.
Inline style is more specific than any selector.
Only an !important rule will override an inline rule (unless the inline rule is also !important).

target.style.display = "none"
should be:
event.target.style.display = "none";
As mentioned by Quentin, it adds an inline style, but I don't recommend it. You may need to use !important, which may make things even more confusing.
I recommend using CSS for styling, and add/remove/toggle a class to the current element through javascript.
Adding a class:
event.target.classList.add = 'myClass';
Removing a class:
event.target.classList.remove = 'myClass';
Toggle a class:
event.target.classList.toggle = 'myClass';
Documentation on classList

Related

Cannot style Jquery element using CSS

I have a Jquery selectmenu called #Main which implicitly gets a #Main-button. When I try to set #Main-button's width using css as
#Main-button {
width:200px;
}
it has no effect.
When I explicitly set
$( "#Main" ).selectmenu({ width:200})
it has the desired effect and under Firebug I see that it has appended a style="width:200" on the #Main-button, which is what I tried using CSS at the first place.
What is different? I've checked that the my CSS style sheet gets called AFTER the Jquery one, so there is no precedence issue
Also I notice that html elements turned to Jquery elements cannot be styled using CSS targeted at the specific element, even with the use of unique id's,but require the use of Jquery classes like .ui-menu etc
why do they behave differently? are there any specific styling gudilines when Jquery is involved?
In your CSS you've
#Main-button {
width:200px;
}
but the JS is adding dynamic inline style based on content. So it's having style attribute.
So in terms of CSS specificity their CSS beats you.
You must use !important in your rule to avoid overriding of your CSS.
#Main-button {
width:200px !important;
}
To style selectmenu or every jquery widget, you need to use jquery default classes. Your selector must be like
#Main-button.ui-selectmenu-menu li a
And also you can extend _renderItem and _renderMenu functions of selectmenu for different styling.

remove css property with pure js failed

I tried the following code to remove a property from my css but doesn't work.
document.getElementById("wrap").style.removeProperty('overflow-x');
The CSS:
#wrap{
overflow-x : hidden;
}
When I run the javascript, I get the error Cannot read property 'style' of null
The code posted would remove overflow-x style in the following scenareo:
<div id="wrap" style="overflow-x: hidden"></div>
CSS applied properties are not applied directly to the style attribute of an element - they are applied at a layer higher.
Effectively, there's nothing to remove on the style property, but you can set a value there instead, which would override the value applied from CSS properties (unless css has !important flag specified)
Try this instead:
document.getElementById("wrap").style.overflowX = 'visible';
As your specific scenario is about applying the style based on some browser detection, I suggest the following javascript:
var userAgent = window.navigator.userAgent.toLowerCase();
var is_ios = /iphone|ipod|ipad/.test( userAgent );
if (!is_ios) document.body.className += 'not-ios';
With CSS:
.not-ios #wrap {
overflow-x : hidden;
}
You could also use class "wrap" instead of id to make this more re-usable (if required)

:hover doesn't work with jquery script

I have a <ul> where each li reponds on :hover. Here is the css:
.profile_nav_item:hover {
border-color: #af0621;
}
But it want these borders to stay colored when I click them.
I have this jQuery function:
$('a[rel="tab"]').click(function(e){
var url = $(this).attr('href');
$('.profile_nav_item').css('border-color', 'transparent');
$('.profile_nav_item', this).css('border-color', '#af0621');
But after clicking, the :hover css property isn't called anymore. Does anyone know how I could fix this?
Here is the fiddle: http://jsfiddle.net/zRJK9/
You need to reset CSS properties to '' (empty string) for the style sheet to kick in again.
$('.profile_nav_item').css('border-color', '');
basically you are forcing the element style to #af0621 after which the stylesheet will do nothing to override it (element styles take priority).
Passing an empty string value to css() removes the inline style setting.
JSFiddle: http://jsfiddle.net/zRJK9/6/
Because inline css attribute has more priority then included one. So when you set it with jQuery it got like this: style="border-color: #af0621". Try to use !important in your css:
.profile_nav_item:hover {
border-color: #af0621 !important;
}

CSS Hover being de-activated

I am displaying a page of thumbnails, which if you hover over them, their description is displayed.
for this I am using a span element with CSS
.thumb:hover .thumbText {
display: inline-block ;
}
This works fine initially.
But as this needs to work on a touch device and touch does not have hover, I added a button to show all descriptions.
This also works fine, but once I have used the Button Toggle, Description my javascript function has somehow disabled the CSS hover and I can not work out why.
var CaptionsOff = true;
function toggleCaptions() {
if (CaptionsOff) {
/* Turn Captions ON */
$('.thumbText').css("display", "inline-block")
$("#btnCaption").html("Hide Thumb Captions");
CaptionsOff = false;
} else {
/* Turn Captions OFF */
$('.thumbText').css("display", "none")
$("#btnCaption").html("Show Thumb Captions");
CaptionsOff = true;
}
The site is
http://mclportal.net/wcit/June26.html
That Javascript code adds the CSS to a style attribute on the element. For example:
<span style="display:none">Caption</span>
Style attributes take priority over CSS files. To change this, modify your CSS script like this:
.thumb:hover .thumbText {
display: inline-block !important;
}
This code means that the display from the CSS is used, rather than from the attribute.
Also, you are missing semicolons.
Hope this helps.
Alternatives:
Toggle a class
$(".buttonCaption").toogleClass("showCap")
.thumb:hover .thumbText, .showCap {
display: inline-block;
}
Set the display to nothing, rather than none. Assumes that the captions are have display:none as default in CSS. Other two solutions are probably better than this.
$('.thumbText').css("display", "");
Add !important to your class rule. The .css() method adds the style to element's "style" attribute which has higher priority.
.thumb:hover .thumbText {
display: inline-block!important ;
}
Setting inline style to $('.thumbText') in toggleCaptions() overrides the stylesheet. Toggle a class instead of setting inline styles.
add this in else with your code::$('.thumbText').removeAttr("style");

Changing CSS pseudo-element styles via JavaScript [duplicate]

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)?

Categories

Resources