Javascript : Change selection background - javascript

How should I do this in Javascript?
// CSS
*::-moz-selection{
background:transparent;
}
I tried these but doesn't really works:
// Javascript
document.mozSelection = "transparent";
document.body.mozSelection = "transparent";

You can add a rule to the stylesheet.
// Get the first stylesheet
var ssheet = document.styleSheets[0];
if ("insertRule" in ss) {
ss.insertRule('#yourdivcontainer::-moz-selection { background: transparent; }', 0);
}
IMO, it's not a good practice anyway. You should create a CSS class with the selection color and change the class itself via JS instead of the style.

:: selectors are for pseudo-elements, CSS objects that don't correspond to actual element nodes. Because there is no element node to match ::-moz-selection, you can't style it directly on an element's .style.background property.
Instead you would have to insert a new stylesheet rule duplicating the above CSS (see this question for a couple of methods of doing that).

Related

What's the most efficient way to style multiple html elements when generating them with JS?

I'm currently building a web app for some popular software on steam and decided to generate the elements with JS. The reason for doing this is because I'm going to force a refresh after the user confirms a settings menu, and then check localStorage on each customizable element and act accordingly.
The problem is that while rendering the HTML elements I'm styling them individually, compared to just using a class in standard css. I looked around for a potential solution and the only one I could find was by defining the class in the css file and then applying that class through js, but I'll end up with a lot of wasted classes this way.
for(let i=0; i<title.length; i++) {
// creation
const a = document.createElement("a");
// styling
a.style.display = "block";
a.style.width = "90%";
a.style.margin = "auto";
a.style.padding = "20px";
a.style.backgroundColor = "#2f2f2f";
// attaching it to element as child
sets.appendChild(a);
}
This is currently how I have all my elements being created, which is less than ideal. I want to know whether or not it's possible to create a css class from within js, or at least the best method of achieving the end result. It might not be a problem at the current stage, but I'm likely going to have hundreds of elements sharing the same styling in the near future.
**thanks for the help in advance.
Use setAttribute
a.setAttribute('class', 'my-css-class');
You can then add the styles with css:
.my-css-class {
background-color: #2f2f2f;
}
In terms of pure efficiency, I don't think you can do a lot better than this except maybe generate an HTML string and use innerHTML but I wouldn't do that as it might save a few miliseconds but it makes the code less maintainable in the long run. The fragment is already a better alternative as suggested by #fcalderan. You can also use a CSS class as pointed by #Sirence. Also, if you care about code-style, it's a little loss on performance but a gain in readability, you can use forEach() instead of a classic for loop.
CSS:
.set-title {
display: block;
width: 90%;
margin: auto;
padding: 20px;
backgroun-color: #2f2f2f;
}
JS:
let fragment = new DocumentFragment();
title.forEach(t => {
const a = document.createElement("a");
a.className = 'set-title';
fragment.appendChild(a);
});
sets.appendChild(fragment);

Update CSS in JavaScript / jQuery

The following code is an example of open and close actions of a sidebar, where some CSS values should be updated to correctly show the sidebar.
function openNav() {
document.getElementById("sidebar").style.width = "250px";
document.getElementById("mainContent").style.marginLeft = "250px";
document.getElementById("codePanel").style.marginLeft = "10px";
}
function closeNav() {
document.getElementById("sidebar").style.width = "0";
document.getElementById("mainContent").style.marginLeft = "0px";
document.getElementById("codePanel").style.marginLeft = "40px";
}
Now I ask myself if there is a better way to do this if I eg update more different styles?
Because in this code, I would need to add more and more similar looking lines of code which looks really clunky.
If you add an initial class to all your elements that you want to update
<div id="sidebar" class="update"></div>
<div id="codePanel" class="update"></div>
Then add some styles (be aware of style specificity)
#sidebar.update {
width : 200px;
}
#sidebar.update.updated {
width : 250px;
}
#codePanel.update.updated {
color : red;
}
You can easily add that class to multiple elements in a loop
var elems = document.querySelectorAll('.update');
elems.forEach(function(elem) {
elem.classList.add('updated');
});
as the other members mentioned it is better to use class, what I want to add is
that you can create those css classes based on specific style for example create a class called marginLeft50 which sets the left margin to 50 so whenever you want to update an element css you can simply do $('sidebar').addClass('marginLeft50');
keep in mind that you can add multiple classes to a single element, and since you mention jquery in your tags, jquery takes care of looping through all the targeted elements and updating each one of them
and as simply you can $('selector').removeClass('className') whenever you need to

Asigning CSS property to variable in JavaScript [Polymer]

I have simple question about asigning values of CSS properties to some variables is JavaScript in Polymer app.
Assume I have one div with width:200px;. In some JavaScript function i want to change width to 200px+10px.
I know i can apply this in JS in this way div.style.top = '210px';, but this is not what I need!
I want to changing this width property, and have full control about this.
So I readed i can make some custom CSS variable to save my width:
:host {
--my-width: 200px;
}
div{
width: var(--my-width);
}
This is nice because now I have one CSS variable, and I can set this attribute to few selectors, elements.
The question is - how to get this variable in JS and change it in that way (pseudocode):
--my-width = --my-width + 10px
I know i can use this
this.updateStyles({
'--my-width': '210px'
});
to replace value, but I want to code something like this:
this.updateStyles({
'--my-width': '--my-width'.value + 10px
});
So that I could changing this width by adding some values (+10px) , not defining new (= 210px)
I'm asking about how to make this and about some good practices in polymer, how to do that.
You can use window.getComputedStyle and getPropertyValue:
const styles = window.getComputedStyle(this);
const myWidth = styles.getPropertyValue('--my-width');
const newWidth = `${parseFloat(myWidth) + 10}px`;
this.updateStyles({ '--my-width': newWidth });
It's worth reading the Polymer docs on custom properties. Although I'm not sure they're 100% up-to-date, they have some useful information re: Shady DOM.
An alternative, depending on your use case and the browsers you're targeting, is the CSS calc() function:
div {
width: calc(var(--my-width) + 10px);
}
You could do the same with updateStyles, of course.

How to override an element's default style with Javascript?

In CSS we can do:
div { font-size:20px }
To set the default font size for all divs. Is there a way to change default styles for elements with JavaScript?
Alternately, how could I find and set the above style rule? You can find classes by searching document.styleSheets[0].cssRules by name, but I don't know how to find the style for div.
EDIT:
Oops, the answer is in my question.
My confusion arose from attempting to alter rules that were set for multiple elements at once.
So you would be able to find and alter the CSS rule for div as above.
What I don't know is how you'd alter the rule for multiple definitions:
div,span { font-size:20px }
You can't find the rule by searching for div, span or div,span.
You can use style.fontSize property for setting font size using javascript. The code will look like
document.getElementById("//id here").style.fontSize = "50px"; //size
See an example here
well if you want to change the style of an determinated div you have to do this in you javascript code
getElementById('div_register').setAttribute("style","font-size:20px");
in this way you are getting de div by its id, and setting a style that you want, you can set differents styles with these and will save code space as declare one by one the style you want...i hope i helped you :-D
With the help of javascript you can change the DOM properties. You can create one outer div and give it some name/id. Then, loop through all inner divs and update the css style attributes.
innerDivs = document.getElementById('odivID').getElementsByTagName('div');
for (var i = innerDivs.length-1; i >= 0; i--) {
innerDivs[i].style.fontSize = "25px";
}
You can do this by n number of ways, but I recommend to use class name:
style
div.my-style {
font-size:20px;
}
script
...
var divs = document.getElementsByTagName('div');
var len = divs.length;
var cn;
if(len --) do {
cn = divs[len].className;
if(cn) {
cn += ' my-style';//<-- spaces to separate with the existing class names, if any
} else {
cn = 'my-style';
}
divs[len].className = cn;
} while(len --);
...
Note: Applying style to all divs will apply to those divs as well on the same page which you don't want to do.
You could create your own css style rule that override the default one.
either
create <style> in <header> using javascript
or, link external css file <link>
please see fiddle using first method: http://jsfiddle.net/b8Hn7/
var myStyle = document.createElement("style");
myStyle.innerText = 'div { font-size: 40px; }';
document.head.appendChild(myStyle);
The above code overrides the default style by creating same rule but place after the default style, there is no need to "locate" the default style and change it.
U can try it with create 'style' dom like my under code:
html:
</div>
js:
var style = document.createElement('style');
style.innerText = 'div{width:100px;height:100px;border:1px solid #c4e;}';
document.body.appendChild(style);

Get Actual CSS Property of element if it dynamically added "!important"

I have a Element with the id="somID";
For Example:
Html:
<div id='somID' ></div>
Css :
#somID{ width:500px;height:500px}
and i have a class named : maximize.
So,
.maximize{width:100% !important; height:100% !important; }
Now dynamically i added the class .maximize to my div #somID
And after that i wanna get the width and height of my #somID by calling with its ID like,
$('#somID').width() or .height()
but i want to take the actual height of element that is defined in its ID but i get the .maximize in result not the height or width that is in #somID.
Any buddy have any idea ? That how to retrieve the height of div#somID if it contains .maximize ??
The problem is, there can be many, many selectors that are applied to a given element, with different specificities. There is no API that allows you to request a property from a selector in CSS - it simply wouldn't make much sense.
Having said that, you can create a hack to solve that issue:
function getOriginalDimensions(id) {
var $a = $("<div>", {id:id});
$("body").append($a);
var width = $a.width();
var height = $a.height();
$a.remove();
return {width:width, height:height};
}
console.log(getOriginalDimensions("somID")); // returns {width:500, height:500}
The above works with your example HTML and CSS.
JSFiddle
This basically creates an element with the same ID, appends it to the body, reads the dimensions and deletes it immediately. This is necessary because the div will have no size if it is just kept as a document fragment and not added to the DOM, because the CSS will not get applied.
In theory you could expand this function to make it work with other selectors.
However bear in mind this is a nasty hack and you should reconsider your approach.
A. Make your measurements and save them as .data attributes of the element :
var $el = $('#somID');
$el.data('original_dims', {
height: $el.height(),
width: $el.width()
}
B. Add class that changes the dimensions of the element :
$el.addClass('maximise');
C. Retrive the original dimensions whenever they are needed
var h = $el.data('original_dims').height;
var w = $el.data('original_dims').width;

Categories

Resources