What is the proper and fastest way to change CSS values using JavaScript?
For example, if I have a style.css file:
#h1 {
color: 'red';
}
I need to change the color to any other color and update the CSS file.
document.querySelector('#h1').style.color = 'your-color';
for multiple css property change use with classname add .it reduce the code lines in dom
document.querySelector('#h1').classList.add('your-class')
JS:
document.getElementById("elementsId").style.color= "red";
My recommendation would be not to use Id name like h1 as it may be confusing with the <h1> tag in html. Use more clear variable name like headerId.
for changing multiple css properties use this:
document.getElementById(elementsId).setAttribute("style","width: 500px; background-color: yellow;");
$('h1').css('color','#ff5722');
#h1 {
color: 'red';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1> this color tho</h1>
Jquery is from javascript so once you learn jquery you will sometimes go back to javascript
Related
I want that the user is able to specify his favorite color. The whole page should then change to this specific color scheme.
My CSS is done with this as base:
:root {
--maincolor: black;
}
What would be the best way to change this variable inside my CSS dynamically on a button press or something like this?
PS: I would prefer to set this value only a single time and then be done with it
EDIT: Solution for me:
<script>
var color = "#Html.ViewData["Color"]";
document.body.style.setProperty('--maincolor', color);
</script>
Was enough to change --maincolor as i want. To set the color put this inside a controller:
ViewData["Color"] = "red"
Your best option, in my opinion, is to associate the user to a CSS class, not a color. Then, changing the class per user becomes trivial.
For example, you could store and retrieve this CSS class from your database or other persistence method. Then, upon retrieval, you could simply add the class to your element via Razor like so:
<div class="#UserColorClassName">
<p>
Any text you like here for User: #UserName
</p>
</div>
There are other variations of this method, as well. For example, you could create a database table of "UserCSSClasses" that would house class names and properties for different users.
Or, you could simply store the CSS hex-color and associate that with the user.
An example of this implementation would be as follows:
<div style="color: #(!string.IsNullOrEmpty(UserHexColor) ? UserHexColor : "")">
<p>
Any text you like here for User: #UserName
</p>
</div>
Edit: It sounds like you have a lot of changes to make on a per-User basis, not just one color. For this, I recommend the following solution:
Store the User/class association in the database or other persistence method as described above.
Instead of applying the class on elements inside of your view, apply it to the body element or that of a containing element.
This way, you can change as many classes as you want with CSS overrides:
body.User001 h1 {
color: red;
}
body.User001 p {
color: #c1c1c1;
}
body.User001 p span.caption {
color: red;
}
body.User002 h1 {
color: blue;
}
/* etc... */
I'm new to JavaScript. I managed to add dynamic inputs after clicking on a button but I want to know how to apply the CSS to those added inputs, if anyone can give me a simple example i'd be glad!
Thank you!
Perhaps something like this:
<button onclick="newInput()">Add new input</button>
function newInput() {
var newElement = document.createElement("input");
newElement.className = "newClass";
document.body.appendChild(newElement);
}
And in the style section, or in the .css file, you'll have:
.newClass {
/*Styles go here*/
display: block;
}
Fiddle example of the above: http://jsfiddle.net/8zen9wwo/3/
Here is a very simple example using jQuery:
http://jsfiddle.net/kmrvpz99/
Html Code
<div class="container"></div>
Javascript Code
$('.container').append('<input type="text" class="yourstyle">');
var manualCss = $('<input type="text">').css('background-color', '#333');
$('.container').append(manualCss);
The css File
.yourstyle {
background-color: #000;
}
By defining .yourstyle in the css file, all elements on the html site that possess this class, even those dynamically added via javascript, will use this style. You can however manually modify the css by setting the style attribute on the element directly.
Directory Structure:
index.html
--admin
----suit.css
And the part of the css file is:
#suit-left{width:200px;right:240px;margin-left:-100%}
.suit-columns{padding-left:200px;padding-right:40px;}
I want to write a javascript code in the index.html:
<button onclick="">Change CSS</button>
to change the css file like this:
#suit-left { display: none; }
.suit-columns { padding-left: 0; }
How can I do this?regards,thanks a lot
If you want the apply css on particular element by javascript, do something like this.
<button onclick="changeCss()">Change CSS</button>
UPDATE
<script>
function changeCss(){
var suitInput = document.getElementById('suit-left');
suitInput.style.display = 'none';
//UPDATED the answer
var siteCol = document.getElementsByClassName('suit-columns')[0];
siteCol.style.paddingLeft = '0';
//siteCol.style.paddingRight = '0'; //incase of want padding right 0
}
</script>
What I would recommend here is to manipulate the classes associated with the element rather than changing the class definition itself.
Here is a simple example:
.sideBar{ /* your normal rules here */ }
.sideBar.hidden { display:none; }
In order to hide your sidebar, all you'd have to do is add the hidden class name to the element.
In this way, you would define CSS rules for your sidebar when it is open, and different rules for when it is closed. Once you have those two states pre-defined, all you'll have to do is change/add/remove the class to hide/display your sidebar.
I feel like this was the main issue with your question here. The other tasks you wish to perform such as clicking on a button or actually manipulating the class attribute has been covered in many posts already. Here are some useful links for you -
Add class to given element
Using an HTML button to call a JS function
You can write the script in this way and paste below script at head block of index.html
I assume that you have knowledge of jquery.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
function ChangeCss(){
$('#suit-left').css('display','none');
$('.suit-columns').css('padding-left','0');
}
<script>
<button onclick="ChangeCss();" >
Now it will help!
So basically using css function of jquery you can change css/style attributes.
I hope it will help you.
This should be so simple, but I'm making heavy weather of it.
Div region set out as:
<div class="maincontent">
Stuff in my div
</div>
CSS for that div:
.maincontent{
height: 100%;
background-size: 100%;
margin-left:1%;
margin-right:1%;
font-size:16px;
}
Then I have:
onLoad=changeBackground();
But before that I have the function:
function changeBackground(){
document.getElementByAnything('maincontent').style.backgroundColor="yellow";
}
I know its making the call to the function because if I put an alert box in there that shows. But no matter what combination of getElementBy I can't make any changes to the background?
Please help as its driving me insane!
TIA
Have you tried giving your div an id and using document.getElementById('divId') instead? I think if you want to get the element by class you have to use jquery.
getElementById('maincontent')
and change your div to have an id="maincontent"
Try giving the element an id and doing document.getElementById and then do console.log in firebug or other developer tools and verify that you are actually getting a dom element back.
Once you have verified that you should then be able to switch the background color
You're trying to select the div using its class. This isn't quite as straightforward as getting it by id. Try this:
<div class="maincontent" id='mainContent'>
Stuff in my div
</div>
function changeBackground(){
document.getElementById('mainContent').style.backgroundColor="yellow";
}
You can see a working example here: JSFiddle
If you want to get the element using its class, I would recommend using Jquery or another library.
If you're using in line Javascript then use, instead:
onchange="changeBackground(this)"
And:
function changeBackground(elem){
elem.style.backgroundColor = "yellow";
}
Edited as I suddenly remembered you were discussing events based on div elements. As a div doesn't natively support the onchange event, I'd suggest amending your code to the following (though changing the event-type onmouseover to whatever event you find most appropriate):
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
};
JS Fiddle demo.
Also, to remove the events from in-line code, and to make the JavaScript more portable and less 'intrusive':
function changeBackground(elem){
elem.style.backgroundColor = 'yellow';
}
var maincontents = document.getElementsByClassName('maincontent');
for (var i=0,len=maincontents.length; i<len; i++){
maincontents[i].onmouseover = function(){
changeBackground(this);
}
}
JS Fiddle demo.
Bear in mind, though, that some browsers (such as Internet Explorer 8 and below) don't support getElementsByClassName().
I recommend using jQuery if you want to select a DOM by class name.
Put this code in your <head> part of your html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
and change your function to
function changeBackground() {
$(".maincontent").css("background-color","yellow");
}
I have the following HTML code:
<style>
.thing { color: red }
</style>
<p class="thing">This is a nice thing</p>
I would like to change the ".thing"-style for all current content and all future content which comes to the page via AJAX.
$('.thing').css('color', 'blue');
This would work, but if new HTML code is added to the document via AJAX, all ".thing"-elements will still be colored red.
What I want is to change the whole style property ".thing" for the document and not only for the current elements (with a jQuery selector).
Thanks!
You could add a style rule in the header with the DOM
Demo: The Problem
Demo: DOM Mutation Solution
var newStyles = document.createElement("style");
newStyles.type="text/css";
newStyles.innerHTML = ".thing{color:blue}";
document.head.appendChild(newStyles);
You could use a call back function on your AJAX code to run the jquery css function.
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$('.thing').css('color', 'blue');
}
});
If for some reason you are not able to use any of the techniques given in the duplicate question, you could modify the stylesheet itself, for example:
document.styleSheets[1].cssRules[0].style.color = "blue";
However, the above line is not cross browser (I don't think it will work in IE, which prefers rules instead of cssRules) but it's possible to make it cross-browser compatible with a bit more code.
All it does is change the actual stylesheet, so it's like you had color: blue in there all along. This will affect elements currently on the page, and any that are added in the future (see the fiddle for a working example).
Note that you'll have to modify the indexes to suit your page. The indexes used in the example are just what work for the given stylesheet on jsfiddle.net.
Edit an attempt at a cross-browser solution:
var cssRules = (document.styleSheets[1].cssRules) ? document.styleSheets[1].cssRules[0] : document.styleSheets[1].rules[0];
cssRules.style.color = "blue";
You could add a style rule for blue text
<style>
.thing { color: red }
.thing.blue { color: blue }
</style>
and add "blue" class via call back function on your AJAX
$('.thing').addClass('blue');