How to change css with javascript - javascript

I need to change dynamically my css properties. I know that the right way to do it is with: document.getElementById("XXXX").style.fontSize = "xx-large";
However, when I have this css:
#year1 .subdomain-text {
fill: #000;
font-size: 6px;
}
I haven't been able to find the way to access it, and I have tried any possible permutation (nothing works!):
document.getElementById("year1.subdomain-text").style.fontSize = "xx-large";
document.getElementById("year1").style.fontSize = "xx-large";
document.getElementById("subdomain-text").style.fontSize = "xx-large";
document.getElementById("#year1.subdomain-text").style.fontSize = "xx-large";
....
Any idea how to make it happen?
Thanks!

You are using .getElemenByID() which means you specify just the ID name no need to include the class name i.e. document.getElementById("year1").style.fontSize = "xx-large";
Example here :http://jsfiddle.net/Nb7wy/1770/

document.getElementById retrieves html element by its id attribute. In your case, it should be:
document.getElementById("year1")
If the id is unique, as expected, the class is not necessary for the selector in the css rule either. You could just remove the class from your css rule.
For other cases where combining selectors is needed, it can be used document.querySelector(css_selector) (instead of document.getElementById).
Working code:
<html>
<head>
<style>
#year1 .subdomain-text {
fill: #000;
font-size: 6px;
}
</style>
</head>
<body>
<p id="year1" class="subdomain-text">Texto prueba</p>
<input type="button" onclick="test();" />
<script>
function test() {
document.getElementById("year1").style.fontSize = "xx-large";
}
</script>
</body>
</html>

Related

Change background-color of button with JavaScript

I'm writing a HTML webPage, I use a button and I need to change his background-color on mouseover using a javascript function.
Here is the code.
<button onmouseover="funzione(this)">BTN</button>
<script>
funzione(x){
x.style.background-color=#ffffff;
}
</script>
In JavaScript you need get handler to element x e.g.:
var x = document.getElementById("x");
but you should do this with CCS:
button{
background-color: yellow;
}
button:hover{
background-color: lime;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/:hover
This is very basic. You're missing keyword function, and with that style of accessing properties, you need to use camel case. Finally, wrap the color hex within quotes.
function funzione(x){
x.style.backgroundColor= '#ffffff';
}
<button onmouseover="funzione(this)">BTN</button>
The recommended way is use CSS in production, but if you're just into JavaScript and want to explore, it's fine.
If you want in js:
<button onmouseover="set_color(this)">BTN</button>
<script>
function set_color(x){
x.style.backgroundColor='red';
}
</script>
function funzione(x){
x.style.backgroundColor = "#ffffff";
}
<button onmouseover = "funzione(this)">BTN</button>
You can do this simply in CSS, its easy, efficient and less code.
<style type="text/css">
.myHoverButton:hover { background-color: #ffffff; }
</style>
<button id="button1" class="myHoverButton">

JavaScript; Background Color change and change back w/ same input

I made this code, but it wont work. Would be nice if some one can help me. :)
I've tried many things already, but it always didn't worked.
I want it to be so that you press the button and the background gets light, when you press it again it goes back to the origin.
<html>
<head>
<title>test</title>
<style>
.darkerBG {
background: #282828;
}
.lighterBG {
background: white;
}
</style>
</head>
<body class="darkerBG" id="bdbackground">
<script language="javascript" type="text/javascript">
function changeColor()
{
var bdBackground = document.getElementById('bdbackground').class;
if (document.getElementById('bdbackground').class == 'darkerBG')
{
document.getElementById('bdbackground').class == 'lighterBG';
} else if (document.getElementById('bdbackground').class == 'lighterBG')
{
document.getElementById('bdbackground').class = 'darkerBG';
}
}
</script>
<input type="button" class="button" value="test" onclick="changeColor()">
</body>
</html>
You must use className rather than class. class is not a property on a DOM element.
You need to modify the className property on the element rather than class.
For example:
document.getElementById('bdbackground').className = 'darkerBG';
In JavaScript, the correct property is .className instead of .class. You also have an erroneous == in your assignment of document.getElementById('bdbackground').class == 'lighterBG';
Alternatively, consider using .classList.contains(...).
<html>
<head>
<title>test</title>
<style>
.darkerBG {
background: #282828;
}
.lighterBG {
background: white;
}
</style>
</head>
<body class="darkerBG" id="bdbackground">
<script language="javascript" type="text/javascript">
function changeColor() {
var myElement = document.getElementById('bdbackground');
if (myElement.className == 'darkerBG') {
myElement.className = 'lighterBG';
} else if (myElement.className == 'lighterBG') {
myElement.className = 'darkerBG';
}
}
</script>
<input type="button" class="button" value="test" onclick="changeColor()">
</body>
</html>
I have created a working solution for what you are trying to achieve. I created a JSBin with the solution and improved your code slightly: http://jsbin.com/botasehoci/1/edit?html,css,js,output
(Edit, just noticed Quantastical answered with pretty much all the issues I brought up in the time it took me to to post this answer :/ )
The main issues were that:
You needed to include the ID bdbackground on the button element.
You needed to include the initial class name on the button element ("lighterBG")
The correct way to reference the value of the class attribute is using className not class
For the first condition in the if statement, you used an comparison instead of an assignment operator ( i.e. x == a instead of x = a )
This is the updated JS:
function changeColor() {
var button = document.getElementById('bdbackground');
var buttonClass = button.className;
if (buttonClass === 'darkerBG') {
button.className = 'lighterBG';
} else if (buttonClass === 'lighterBG') {
button.className = 'darkerBG';
}
}
This is the updated HTML for the button element:
<input id="bdbackground" type="button" class="lighterBG" value="test" onclick="changeColor()">
.classList()
Use .classList.add() and .classList.remove() to toggle classes. You could use .classList.toggle() but in certain circumstances the toggled states will get discombobulated if there is more than one toggler used at the same time.
Basic Flow
When the function changeColor() is called:
Get a reference to the body with getElementById()
Find out if the body has a class called .darkerBG by using .classList.contains()
If it does have .darkerBG as a class:
Remove the class and ...
add the class .lighterBG
Otherwise:
Remove the class .lighterBG and ...
add the class .darkerBG
SNIPPET
function changeColor() {
var bG = document.getElementById('bdbackground');
if (bG.classList.contains('darkerBG')) {
bG.classList.remove('darkerBG');
bG.classList.add('lighterBG');
} else {
bG.classList.add('darkerBG');
bG.classList.remove('lighterBG');
}
}
.darkerBG {
background: rgba(20, 10, 20, .6);
transition: all 2s;
}
.lighterBG {
background: rgba(200, 100, 200, .6);
transition: all 2s;
}
<html>
<head>
<title>test</title>
</head>
<body class="darkerBG" id="bdbackground">
<input type="button" class="button" value="test" onclick="changeColor()">
</body>
</html>
Instead of using class you can use className or classList with add()/ remove() or toggle().
To check if class exists or not, you can get element attribute (class) by getAttribute('class') , then search in it using indexOf() by your class string.
For best practice try to avoid inline events and use addEventListener instead.
https://jsfiddle.net/5m5ck1fk
//btn = document.querySelector('.button');
var btn = document.getElementsByClassName('button')[0],
bdBackground = document.getElementById('bdbackground');
btn.addEventListener('click', function () {
changeColor();
});
function changeColor() {
if (bdBackground.getAttribute('class').indexOf('darkerBG') != -1) {
bdBackground.classList.remove('darkerBG');
bdBackground.classList.add('lighterBG');
} else if (bdBackground.getAttribute('class').indexOf('lighterBG') != -1) {
bdBackground.classList.remove('lighterBG');
bdBackground.classList.add('darkerBG');
}
}
.darkerBG {
background: #282828;
}
.lighterBG {
background: white;
}
<body class="darkerBG" id="bdbackground">
<input type="button" class="button" value="test">
</body>

Apply JQuery to div's clicked

I am working on making a number list with each number on its individual div. So far I am able to remove the div with Javascript (on click), but I would like to enable JQuery so that I am able to add a class to a div and then remove all divs of that class with a button or something like that.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=203">
<title>Lista Mundial</title>
<style>
.divContainer {
width: 35px;
height: 25px;
border: solid 1px #c0c0c0;
background-color: #e1e1e1;
font-family: verdana;
float: left;
}
.text {
font-size: 15px;
font-family: verdana;
color: black;
margin-top: 4px;
}
h4 {
font-family: Verdana;
color: black;
text-decoration: none;
}
</style>
</head>
<body>
<h4>Double click para borrar un numero</h4>
<script type="text/javascript">
for(var i = 1; i <= 639; i++){
var divTag = document.createElement("div");
divTag.id = i;
divTag.className = "divContainer";
document.body.appendChild(divTag);
divTag.ondblclick = function(){this.parentNode.removeChild(this)};
var pTg = document.createElement("p");
pTg.setAttribute("align", "center");
pTg.className = "text";
pTg.innerHTML = (i);
document.getElementById(i).appendChild(pTg);
}
</script>
</body>
</html>
http://jsfiddle.net/ramonfabrega/AZSy8/
For simplicity, I just tried hiding the div's clicked, but JQuery does not seem to work. So something must be off.
Two issues:
1) jQuery wasn't loaded.
2) You were trying to bind the click event on an invalid selector (divTag instead of div)
Here's an updated fiddle: http://jsfiddle.net/LFC3A/2/
Regarding #2 - jQuery allows you to select an element multiple ways. The most common is to use a selector. The majority of selectors jQuery supports are from CSS 1 - 3, though jQuery supports some of its own custom selectors (such as div:eq, div:gt, and so on...) Check out the selectors page here: http://api.jquery.com/category/selectors/
Now, if your markup was:
<body>
<divTag>My Custom Div Tag</divTag>
<div>My regular DIV</div>
</body>
Then your original fiddle would have worked. In fact, here's an updated fiddle demonstrating that: http://jsfiddle.net/FpMAw/ (I updated your createElement to return a custom element, divTag)
The other way of accessing jQuery is by passing it a DOM element. Something like:
var $body = $(document.body) is equivalent to var $body = $('body')
If you reference that, you now have a jQuery object with a bunch of useful helper methods. So, in our previous example, we can now do:
$body.css('color', 'red')
Hopefully this helps explain a bit more why it didn't work. If you have any other questions, feel free to ask :)
Fiddle Demo
you are not including jQuery library in the fiddle
change $('divTag') to $('div')
Read $( "element" )
$(document).ready(function () {
$('div').click(function () {
$(this).hide();
});
});
Start Learning
jQuery API Documentation
This will create and add a click handler at the same time.
$('<div>').click(function(e){ this.addClass('active');})

How change content value of pseudo :before element by 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)
Closed 2 years ago.
I have the grap constructured by CSS, which is dynamically changes by JS. I show graph max value by pseudo element as:
.graph:before {
content:""; //value that want set by JS
position:absolute;
top:0;
left:0;
}
That's why I need to set this value by JS. I tried $(".graph:before").css("content", hh); but it didn't help. How to get that value?
I hope the below snippet might help, you can specify the content value you want via JS using the CSS attr() function.
Below you have two options: to use JavaScript or jQuery:
jQuery:
$('.graph').on('click', function () {
//do something with the callback
$(this).attr('data-before','anything'); //anything is the 'content' value
});
JavaScript:
var graphElem = document.querySelector('.graph');
graphElem.addEventListener('click', function (event) {
event.target.setAttribute('data-before', 'anything');
});
CSS:
.graph:before {
content: attr(data-before); /* value that that refers to CSS 'content' */
position:absolute;
top: 0;
left: 0;
}
Update (2018): as has been noted in the comments, you now can do this.
You can't modify pseudo elements through JavaScript since they are not part of the DOM. Your best bet is to define another class in your CSS with the styles you require and then add that to the element. Since that doesn't seem to be possible from your question, perhaps you need to look at using a real DOM element instead of a pseudo one.
You can use CSS variable
:root {
--h: 100px;
}
.elem:after {
top: var(--h);
}
let y = 10;
document.documentElement.style.setProperty('--h', y + 'px')
https://codepen.io/Gorbulin/pen/odVQVL
I believe there is a simple solution using the attr() function to specify the content of the pseudo element. Here is a working example using the 'title' attribute, but it should work also with custom attributes.:
document.getElementById('btn_change1').addEventListener("click", function(){
document.getElementById('test_div').title='Status 1';
});
document.getElementById('btn_change2').addEventListener("click", function(){
document.getElementById('test_div').title='Status 2';
});
#test_div {
margin: 4em;
padding:2em;
background: blue;
color: yellow;
}
#test_div:after {
content:attr(title);
background: red;
padding:1em;
}
<button id='btn_change1'>Change div:after to [Status 1]</button>
<button id='btn_change2'>Change div:after to [Status 2]</button>
<div id='test_div' title='Initial Status'>The element to modify</div>
People who are still looking some solution of same problem, it is doable as follows using jQuery:
<button id="changeBefore">Change</button>
<script>
var newValue = '22';//coming from somewhere
var add = '<style>.graph:before{content:"'+newValue+'"!important;}</style>';
$('#changeBefore').click(function(){
$('body').append(add);
});
</script>
This example illustrate that on clicking button: changeBefore , the value for .graph:before will change as per new dynamic coming value for it.
For more description about changing of :before or :after element style or getting its content:
Lets suppose your HTML is like this:
<div id="something">Test</div>
And then you are setting its :before in CSS and designing it like:
#something:before{
content:"1st";
font-size:20px;
color:red;
}
#something{
content:'1st';
}
Please notice I also set content attribute in element itself so that you can take it out easily later.
Now there is a button clicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:
Define a css with your required style on some class .activeS :
.activeS:before{
color:green !important;
font-size:30px !important;
}
Now you can change :before style by adding the class to your :before element as follows:
<button id="changeBefore">Change</button>
<script>
$('#changeBefore').click(function(){
$('#something').addClass('activeS');
});
</script>
If you just want to get content of :before, it can be done as:
<button id="getContent">Get Content</button>
<script>
$('#getContent').click(function(){
console.log($('#something').css('content'));//will print '1st'
});
</script>
I hope it helps
I had a similar problem, but with icons. I needed to switch the play and pause icons for an audio player in html5.
The problem here was that HTML, CSS and jQuery all interpret differently the "content" values to show icons, due to the use of \ symbol.
So the best workaround is to delete and re-create the node. Here's my code:
<ul class="list list--buttons">
<li><i class="fa fa-step-backward"></i></li>
<li><i class="fa fa-play"></i></li>
<li><i class="fa fa-step-forward"></i></li>
</ul>
And the script
<script type="text/javascript">
$(
function(){
var aud = $('audio')[0];
$('.playpause').on('click', function(e){
e.preventDefault();
if (aud.paused) {
aud.play();
/* from play icon to pause icon */
$('.playpause .fa-play').remove();
$('.playpause').append('<i class="fa fa-pause"></i>');
}
else {
aud.pause();
/* from play icon to pause icon */
$('.playpause .fa-pause').remove();
$('.playpause').append('<i class="fa fa-play"></i>');
}
})
$('.next').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
$('.previuos').on('click', function(e){
e.preventDefault();
aud.src = '{$content:audio-file}';
})
aud.ontimeupdate = function(){
$('.progress').css('width', aud.currentTime / aud.duration * 100 + '%')
}
})
</script>
Hope it helps!
You can use document.styleSheets to modify pseudo selector cssRules
document.styleSheets[0].cssRules[0].style.content = '"111"';
If you use something like an onoffswitch and want to translate the css content attribute with i18next then you can use one of the i18next Framework example from github (i18next Jquery Framework) and then you extended the function with this code:
var before = i18next.t('onoffswitch.before');
var after = i18next.t('onoffswitch.after');
$('.onoffswitch-inner')
.attr('data-before', before )
.attr('data-after', after );
and the css code must be this:
.onoffswitch-inner:before {
content: attr(data-before);
padding-left: 10px;
background-color: #65AFF5; color: #FFFFFF;
}
.onoffswitch-inner:after {
content: attr(data-after);
padding-right: 10px;
background-color: #EEEEEE; color: #999999;
text-align: right;
}

Sort sibling <div>s with jQuery

I'm banging my head with the problem that has more to do with 2nd grade mathematics than programming. Here goes: four <div> elements are placed one after another, horizontally. When you click one, script places it in front. You click another one, and it's also placed in front, etc. You get the picture. Now, what I'd like to do is to sort remaining <div> elements (all but the first one) using original order.
Maybe this pic will make things clear:
After step #3, C should be placed after B, so it should go like this: D A B C.
Here's a sample code:
<html>
<head>
<title>mixit</title>
<style type="text/css">
.insidebox{
width: 50px;
height: 50px;
line-height: 50px;
margin: 0 0 0 20px;
text-align: center;
float: left;
border: black solid 3px;
font-family: sans-serif;
cursor: pointer;
}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div id="container">
<div id="a" class="insidebox">A</div>
<div id="b" class="insidebox">B</div>
<div id="c" class="insidebox">C</div>
<div id="d" class="insidebox">D</div>
</div>
</body>
</html>
Now, I understand that I can use .insertAfter() to place element in front, but how should I tackle the sorting part? The keyword is initial order, not alphabetical order. Letters and boxes are given just for illustrative purposes.
This should do what you want.
var $initial = $('.insidebox');
$('.insidebox').click(function(){
var $this = $(this);
$this.parent()
.prepend($this)
.append( $initial.not(this) );
});
You store the initial list and on each click re append it (excluding the current one)
demo http://jsfiddle.net/gaby/Dyafx/
update
Hell.. you do not even need to prepend the current element.. when you append the rest they will go after the clicked one anyway ..
var $initial = $('.insidebox');
$('.insidebox').click(function(){
$(this).parent()
.append( $initial.not(this) );
});
demo http://jsfiddle.net/gaby/Dyafx/1/
Store the initial order as an array. Then sort by array index- the first one (A) will have array index 1, etc.
Do this:
$(document).ready(function(){
$("#container div").click(function(){
$(this).prependTo($(this).parent());
});
});
cheers.

Categories

Resources