How can I conditionally change css styles with js? - javascript

I'd like to implement some javascript that uses an if statement to change some css styles. Not sure how to do it, any help would be great!

If you want to change a single style of an element using JavaScript, use
document.getElementById(id).style.property = new style
eg :
document.getElementById("myDiv").style.color= "red";
To add a new CSS class to an element, use
document.getElementById(id).classList.add("mystyle");
To remove
document.getElementById(id).classList.remove("mystyle");
Demo :
function changeSingleStyle() {
var color = document.getElementById("myDiv").style.color;
if (color === "red")
document.getElementById("myDiv").style.color = "yellow";
else
document.getElementById("myDiv").style.color = "red";
}
function addClass() {
document.getElementById("myDiv").classList.add("mystyle");
}
function removeClass() {
document.getElementById("myDiv").classList.remove("mystyle");
}
.mystyle {
color : red;
background: green;
font-size: 50px;
}
<div id="myDiv"> This is a div </div>
<button onclick="changeSingleStyle()">changeSingleStyle</button>
<button onclick="addClass()">addClass</button>
<button onclick="removeClass()">removeClass</button>

First of all, to change CSS using JavaScript, the syntax looks like the following:
document.getElementById(id).style.property = new style
For example, if you want to change the display property of an element with id = "container" to block, it would be:
document.getElementById("container").style.display = "block";
Given this, you could easily add an IF statement depending on what condition you want. For example:
if(condition)
{
document.getElementById("container").style.display = "block";
}

You can do this with .style.property or .style.cssText
function myStyleFunction() {
document.getElementById('styled').style.color = 'red';
}
function myStyleFunctionCssText() {
document.getElementById('styled2').style.cssText = 'color: lime';
}
<button onclick="myStyleFunction();" id="styled">
Style with .style.color
</button>
<button onclick="myStyleFunctionCssText();" id="styled2">
Style with .style.cssText
</button>
With this code, the button on the left will go red, the one on the right will go lime.
You can also do this easily with jQuery.
function myStyleFunction() {
$(".style").css("color", "magenta");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="style" onclick="myStyleFunction();">Style by class</button>
<button class="style">Style by class 2</button>
This code changes all elements in the classes color to magenta if you click the first button.

function barHtml (percent) {
return `
<div class= "${percent>25 ? "class1":" class2"}"
style="width: ${percent}%;">
</div>`
}
document.body.innerHTML=<div>${barHtml(20)}</div>

Related

Creating a script for a button to close other sections when opening its own sections

This is hard to explain precisely. But here we go:
I have a button that calls a function
<button onclick="myFunction_gsm()">Men</button>
When the button is pressed, it triggers a script. This script grabs a hidden section and displays it. The script goes like this:
<script>
//Gender Selection Script Men//
function myFunction_gsm() {
var x = document.getElementById("men-sizing");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
On the screen this plays out so that you click the button, a section appears, if I click the same button again the section hides again. However, I have another 2 sections. 3 Sections in total. For this example, the above script works for 1 section, the A section. There is also B and C. I would like to include the behavior that when A has been pressed, therefore displaying section A, if I then press the button for B the B section appears but the A section disappears without having to press the A button again. A Dynamic change of sorts.
I am a complete starter for coding but I assume it's something you add into the if statement. Any help would be greatly appreciated.
I would prefer solutions that incorporate the code I have now, since I won't have much use recreating it from scratch. It would solve this, but cause many new problems.
Define a class for all sections, for example sec. On click event pass the selected id, hide all of them and just toggle the selected one.
function myFunction_gsm(sectionId) {
let sec = document.querySelectorAll('.sec');
sec.forEach(itm => {
if(itm.id !== sectionId) itm.style.display = 'none'
})
var x = document.getElementById(sectionId);
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
let sec = document.querySelectorAll('.sec');
sec.forEach(itm => {
itm.style.display = 'none'
})
<button onclick="myFunction_gsm('sec1')">Sec1</button>
<button onclick="myFunction_gsm('sec2')">Sec2</button>
<button onclick="myFunction_gsm('sec3')">Sec3</button>
<div class="sec" id="sec1"> some text 1 here</div>
<div class="sec" id="sec2"> some text 2 here</div>
<div class="sec" id="sec3"> some text 3 here</div>
You might use class names for the sections. Then at the start of the function have all elements with that class name be hidden and afterwards display the currently clicked one.
If you want to preserve the toggle functionality for the section (so clicking A twice displays and hides it again), you want to check the display state of the currently clicked one first before hiding all. And then only display the clicked one if it was hidden before.
The modern approach is to avoid using .style within JS. This add the stylign as inline-style which ahs the highest specificty weight with exeption of important. The modern solution is to use classList to apply, remove or toggle a CSS-Class.
You add a class to CSS to hide element such as: .display-none { display: none; }`
Then you add a function to your button to hide all sections with a certain class by adding the class mentioned at step 1: function hideAll() { document.querySelectorAll('.class-name').forEach(el => el.classList.add('display-none')); }
You add a second function to the onclick trigger of a button thow a certain element by removing the class: element.classList.remove('display-none');
function hideAll() {
document.querySelectorAll('.section').forEach(el => el.classList.add('display-none'));
}
function showA() {
document.querySelector('#section-a').classList.remove('display-none');
}
function showB() {
document.querySelector('#section-b').classList.remove('display-none');
}
function showC() {
document.querySelector('#section-c').classList.remove('display-none');
}
.display-none {
display: none;
}
<button onclick="hideAll(); showA()">Show A</button>
<button onclick="hideAll(); showB()">Show B</button>
<button onclick="hideAll(); showC()">Show C</button>
<section id="section-a" class="section display-none">Section A</section>
<section id="section-b" class="section display-none">Section B</section>
<section id="section-c" class="section display-none">Section C</section>
CSS-only Solution
If you dont want to sue scripts, you could use a pure CSS-Method that works through the :target selector. This allows you to use anchor as "trigger".
Hide the scetiond with display: none; either by selecting them directly or adding a class to them.
use an anchor with an href="#id" instead of a link. This will move the page to that element but also manipulate the websites adress.
Use *:target { display: block; } to show targeted elements:
.display-none {
display: none;
}
*:target {
display: block;
}
/* for styling purpose only */
a {
margin-right: 15px;
}
Show A
Show B
Show C
<section id="section-a" class="display-none">Section A</section>
<section id="section-b" class="display-none">Section B</section>
<section id="section-c" class="display-none">Section C</section>

HTML DOM getElementsByTagName issue

Currently, both this is using a button, but is there a possible to have this query without a button but just onclick?
Changes the target of the anchor to google.com:
<button onclick="document.querySelectorAll('ul>li>a').forEach(function(link){link.href='http://google.de';});"> ChangeHREF </button>
Changes the color of the header of the page:
<button onclick='(document.getElementsByTagName("h1")[0]).style.color="blue"'>XSS attach</button>
Add an eventlister for click on a tag e.g. a DIV that starts a function (change). In this function get with querySelector your header H1 and a class blue. Via CSS the color of the header changes to blue.
So you don't need a button for this.
document.getElementById('myDiv').addEventListener('click', change);
function change() {
document.querySelector('h1').classList.add("blue");
}
h1.blue {
background: blue;
}
<h1>Header</h1>
<div id="myDiv">Press this DIV for change H1 to blue</div>
of course you can here is one I used div and you can use other but in the way makes sense like you can't use select
change.onclick = () => {
document.getElementsByTagName('h1')[0].style.color = 'red';
}
<h1>Hello world</h1>
<div id="change">Change Color</div>
change.onclick = () => {
document.querySelectorAll('a').forEach(link => {
link.href = 'http://google.de';
});
var links = document.getElementsByTagName('a');
console.log(links[0].href);
console.log(links[1].href);
}
a
b
<div id="change">Change</div>

changing the background color on clicking on the button

I'm learning javascript!
What I need to do, is to change the background-color at the same time when the image is changing by clicking on the button.
Changing the picture, from light-On to light-off, is working properly, the only problem is that the color of the background of my html page, is not changing.
function colorize() {
var element = document.getElementById("azul");
element.style.backgroundColor = 'blue';
element.style.color = "yellow";
}
html{
background:
grey;
}
#azul:focus {
background: blue;
}
<div id="branca">
<h1>LOI Lampen aanzetten en uitzetten</h1>
<button id="azul" onclick="document.getElementById('myImage').src = '/img/393533_02.PNG'">Turn on the light</button>
<img id="myImage" src="img/393533_01.PNG" class="mudar">
<div id="yellow">
<button onclick="document.getElementById('myImage', '').src='/img/393533_01.PNG'">Turn off the light</button>
</div>
</div>
You want to change background of html so what you have to do is...
function colorize() {
var element = document.getElementsByTagName("html")[0];
element.style.backgroundColor = 'blue';
}
You were taking button element and changing its color. you have to select html tag as you want to change the background-clor property assigned to it via css.
This is your solution call the colorize function too
<html>
<script>
function colorize() {
var element = document.getElementsByTagName("html")[0];
element.style.backgroundColor = 'blue';
element.style.color = "yellow";
}
</script>
<style>
html{
background:
grey;
}
#azul:focus {
background: blue;
}
</style>
<div id="branca">
<h1>LOI Lampen aanzetten en uitzetten</h1>
<button id="azul" onclick="document.getElementById('myImage').src = '/img/393533_02.PNG';colorize()">Turn on the light</button>
<img id="myImage" src="img/393533_01.PNG" class="mudar">
<div id="yellow">
<button onclick="document.getElementById('myImage', '').src='/img/393533_01.PNG'">Turn off the light</button>
</div>
</div>
</html>
You need to change the background color of the document, not element, which is your button.
Since you are new to JavaScript, let's get you off of some bad habits that you've already picked up.
Do not set up event handlers via HTML event attributes (i.e. onclick, onmouseover, etc.). This is a 25+ year old technique that we used before we had modern standards and best practices and because it's easy to use, people keep using it. But there are a variety of reasons why you should not use this technique and instead separate your JavaScript from your HTML. Instead, keep your JavaScript separate and use .addEventListener() to hook up your elements to their respective callback functions.
Whenever possible, work with pre-made CSS classes because these are easier to manage and reuse than inline CSS styles (via the .style property). You can then easily use the element.classList API to add or remove classes as needed.
See the comments inline below:
// Get references to the elements you'll need to work with
let targetImage = document.getElementById('myImage');
let btnOn = document.getElementById("on");
let btnOff = document.getElementById("off");
// Then, set up your event handlers in JavaScript, not HTML
btnOn.addEventListener("click", changeImage);
btnOff.addEventListener("click", changeImage);
function changeImage(){
// Set the target's source to the data-source attribute for the clicked button
targetImage.src = this.dataset.source;
targetImage.alt = this.dataset.alt // Now update the alt attribute
// Change the background color of the page by adding or removing a
// pre-made class to/from the body based on the button that was clicked
// Since this is a simple if/then scenario, we can use the JavaScript "ternary" operator
// which works like this: some condition ? what to do if condition is true : what to do if false
this.id === "on" ? document.body.classList.add("blue") : document.body.classList.remove("blue");
}
body { background-color: grey; } /* Style the body, not the HTML */
#on:focus { background: blue; color:yellow; }
.blue { background-color:aliceblue; } /* This will be added when on is clicked */
/* Just for this example only */
img { width:100px; }
<button id="on" data-source='https://cdn.wccftech.com/wp-content/uploads/2015/04/bulb_PNG1250.png' data-alt="On Image">Turn on the light</button>
<button id="off" data-source='https://www.radioducoeur.com/liten/radioducoeur/light-bulb-png-home-design-ideas-4-lightbulb-498-x-498-liten.jpg' data-alt="Off Image">Turn off the light</button>
<div>
<!-- <img> elements must have an alt attribute to be valid -->
<img id="myImage" src="https://www.radioducoeur.com/liten/radioducoeur/light-bulb-png-home-design-ideas-4-lightbulb-498-x-498-liten.jpg" class="mudar" alt="default image">
</div>
Here is your code:
<style>
body {
background: grey;
}
</style>
<script>
function colorize(light) {
if (light) {
document.getElementById('myImage').src = '/img/393533_02.PNG';
document.body.style.background = 'grey';
}
else {
document.getElementById('myImage').src = '/img/393533_01.PNG'
document.body.style.background = 'blue';
}
}
</script>
<body>
<div id="branca">
<h1>LOI Lampen aanzetten en uitzetten</h1>
<button id="azul" onclick="colorize(true)">Turn on the light</button>
<img id="myImage" src="img/393533_01.PNG" class="mudar"/>
<div id="yellow">
<button onclick="colorize(false)">Turn off the light</button>
</div>
</div>
</body>
Now in colorize function you can write as much parameters as you want for two different conditions.

Change color of collapsible on click materialize

I would like to change the color of the collapsible header only when I click on it.
<div class="collapsible-header" onclick="connect()"></div>
I have to add the color inside the class element, and I do not really know how to add something to it when I call the "connect" funtion. Is this possible ?
Thank you !
Tried with the following but is not working
HTML
<div class="collapsible-header" onclick="connect(this)">Robot</div>
And in JS
function connect(element)
{
element.style.color = 'red';
if (connection_status == 0)
{
client.connect(options);
};
}
Take a new class and assign the styles you want to append then do this
$(".collapsible-header").click(function(){
$(".collapsible-header").toggleClass("NEWCLASS");
});
https://jsbin.com/sojefubudo/edit?html,js,console,output
<div class="collapsible-header" onclick="connect(this)"></div>
And in javascript :
function connect(element) {
element.style.color = 'red';
}
Have a look on this fiddle:
https://jsfiddle.net/swarn_singh/9a6djpwp/
<div onclick="this.style.color = 'red'">
Change color with inline javascript
</div>
<div onclick="changeColor(this)">
Change color with javascript function
</div>
<script>
function changeColor(element){
element.style.color = 'blue';
}
</script>
<div class="collapsible-header" onclick="javascript:this.className += ' additionalClass'"></div>
Use ToggleClass for better result
(function(){
$("#run").click(()=>{
//$(this).css('background','yellow');
$("#run").toggleClass('yellow');
});
}());
.yellow {
background: yellow!important;
}
.red {
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="run" class="red" style="position:absolute;height:100px;width:10px;"></div>

Add class to elments with same matching class as per clicked element

I need to add an .active class to any button which matches any of the classes as per the div I am clicking:
<button class="valueA"></button>
<button class="valueB"></button>
<button class="valueC valueB"></button>
<div class="DYNAMIC CLASS"></div>
$("div.valueB").on("click", function() {
...
});
The result should be:
<button class="valueB active"></button>
<button class="valueC valueB active"></button>
I tried using .each() but I'm stack with the comparison of the classes.
The thing is that my div has dynamic class just as well as those buttons, so I don't know what matches until they are in the DOM.
One version is to create a click function for every single class that you have in your document. This would look something like this:
$('.valueA').click(function() {
$('.valueA').addClass('active')
})
$('.valueB').click(function() {
$('.valueB').addClass('active')
})
$('.valueC').click(function() {
$('.valueC').addClass('active')
})
This is repetitive code however and should be avoided. So instead you can create a function that adds click handlers to all buttons (that's the example I wrote) and then retrieves the classes attached to the element. It then loops over the array of classes and adds to every element with that class another one.
$('button').click(function() {
var classes = $(this).attr('class').split(' ')
classes.forEach(function(elem) {
$('.' + elem).addClass('active');
})
})
Now if you want to limit the application of said class then you add the element type that the class should be applied to before the .
$('button.' + elem).addClass('active');
or
$('div.' + elem).addClass('active');
You need to get class name of div using .attr() and use class name in selector.
$("div").on("click", function() {
var className = $(this).attr("class");
$('button.'+ className).addClass('active');
});
.active { color: red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="valueA">A</button>
<button class="valueB">B</button>
<button class="valueC valueB">CB</button>
<div class="valueB">B</div>
You don't need to use .each(). You can do it like following.
$("div").on("click", function() {
$('button.active').removeClass('active');
$('button.' + this.className).addClass('active');
});
.active {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="valueA">A</button>
<button class="valueB">B</button>
<button class="valueC valueB">C</button>
<div class="valueA">DIV A</div>
<div class="valueB">DIV B</div>
<div class="valueC">DIV C</div>
Get the name of your divs class and add your .active class to all of your buttons by using the corret selector $('button.valueB').
So a dynamic solution could look like this
$("div.valueB").on("click", function(e) {
var className = e.target.className;
$('button.' + className).addClass('active');
});
Demo

Categories

Resources