Javascript beginner here. I essentially want to make a simple switch. If an element is black, change it to white. If it is white, change it to black.
function changeClass() {
if (document.getElementById('myButton').style.backgroundColor == "white") {
document.getElementById('myButton').style.backgroundColor = "black";
} else {
document.getElementById('myButton').style.backgroundColor = "white";
}
}
<button class="normal" id="myButton" onclick='changeClass()' >Change Colour</button>
This code is quite messy though. Is there a better way to do this?
Toggle a class:
function changeClass(){
document.getElementById('myButton').classList.toggle("the-class");
}
where your CSS is:
.the-class {
background-color: black;
}
...assuming the element's normal background color is white.
More about classList here. Support is good, but you may need a polyfill in older environments.
Example:
function changeClass() {
document.getElementById('myButton').classList.toggle("the-class");
}
.the-class {
background-color: black;
}
<button class="normal" id="myButton" onclick='changeClass()'>Change Colour</button>
You can use classList.toggle()
document.querySelector('#myButton').addEventListener('click',e => {
e.target.classList.toggle('black')
})
.black{
background:black
}
<button class="normal" id="myButton">Change Colour</button>
Use something like classList.toggle()
function switchColor(){
document.getElementById("resultDiv").classList.toggle("toggle")
}
.element {
height: 100px;
width: 100px;
background-color: red;
}
.element.toggle{
background-color: blue !important;
}
<button onclick="switchColor()">Click me</button>
<div id="resultDiv" class="element toggle"></div>
You can create some specific class in your css (say, .black class which contains a background-color: black; rule) and then attach/detach that class based on your condition.
Your DOM element (HTML tag) have a handy classList property, which can be treated as a list of classes attached to this DOM. I suggest to read a bit more about it here.
Overall, your function can be written like:
const element = document.getElementById("coolDiv");
element.classList.contains('black')) {
element.classList.remove('black')
} else {
element.classList.add('black')
}
or even a little more concise with a ternary operator
const element = document.getElementById("coolDiv");
element.classList.contains('black') ?
element.classList.remove('black') : element.classList.add('black')
or just with a toggle function of the same classList property
const element = document.getElementById("coolDiv");
element.classList.toggle('black')
Hope it helps! Cheers!
and if white it's not the defualt color you can refactor using ? operator:
let btn = document.getElementById('myButton');
btn.style.backgroundColor = btn.style.backgroundColor === 'white' ? 'black' : 'white';
For this action not needed external javascript you can write simple inline javascript here the code:
.black-button {
background: black;
color: #fff;
outline: 0;
padding: 20px;
}
button {
transition: 0.3s;
cursor: pointer;
}
<button class="normal" onclick="this.classList.toggle('black-button')">Change Colour</button>
Related
I am somewhat new to Javascript/HTML. Recently I've been given a project to align boxes of Avengers characters using CSS or HTML. Here is an image of what the website should look like:
Now I've gotten the CSS part of the code done: defining the boxes for the images, headings/titles of the characters, and their description (in the main body). For the javascript part, the box of the name of the character should change color when the mouse hovers over it, and change back to its original color once removed. For this matter, I will use a portion of my code for the heading, from Iron Man.
CSS:
.ironManHeading { <!-- iron man's heading (goes under image box) -->
left:0px;
width: 250px;
position: relative;
background-color: #999999;
padding: 10px;
text-align: center;
border: 1px solid black;
}
Javascript:
function mouseIM(){ //onmouseover event: heading changes to red background and white text
document.getElementsByClassName("ironManHeading").bgColor = 'red';
document.getElementsByClassName("ironManHeading").fontcolor = 'white';
} // MOUSE EVENTS FOR IRON MAN
function noMouseIM(){ //onmouseout event: heading changes back to normal colors
document.getElementsByClassName("ironManHeading").style.bgColor = '#999999';
document.getElementsByClassName("ironManHeading").style.fontcolor = 'black';
}
And here is the code from the body:
<h1 class = "ironManHeading" onmouseover = "mouseIM" onmouseout = "noMouseIM">IRON MAN</h1>
This is what I've tried, but the colors stay the same as from the image from above. Am I doing something wrong, or am I missing something? I haven't gotten the hang of declaring classes, so I'm not sure if it's something to do with document.getElementsByClassName.
You can achieve the desired behavior with css only like this:
.ironManHeading:hover {
background-color: red;
color: white;
}
If you still want to use Javascript with onmouseover and onmouseout events here's a similar example:
function onMouseOver(elem) {
elem.style.backgroundColor = "red";
elem.style.color = "white";
}
function onMouseOut(elem) {
elem.style.backgroundColor = "#999";
elem.style.color = "black";
}
div {
background-color: #999;
}
<div onmouseover="onMouseOver(this)" onmouseout="onMouseOut(this)">Here's a test</div>
Why your event handlers don't work?
It's simply because you call the methods like this:
onmouseover = "mouseIM"
but you have to call it like this:
onmouseover="mouseIM()"
that's the way to assign event handler function to a HTML event attribute.
Additionally, you can pass a reference to the object that invoked the function with:
onmouseover="mouseIM(this)"
This spares the need to use the selector of the calling element with document.getElementById(), getElementsByClassName() or querySelector() and gives you the flexibility to use the event handler for other elements too. So in your case you can call the same function for each avenger box by calling the event handler with this parameter. See how I used the elem parameter in my event handler functions above.
Consider using css pseudo-classes as #chrisbyte mentioned. In this case, you shouldn't need javascript to perform what you need, attached link below for you to learn more!
https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
.ironManHeading :hover{
background-color: red;
color: white;
}
With css, you can declare a :hover event that does the same thing as mouseover and mouseout in javascript. Something like:
.ironManHeading { <!-- iron man's heading (goes under image box) -->
/* your original definition */
}
<!-- this is the hover event -->
.ironManHeading:hover {
background-color: red;
color: white;
}
Working example (does not require any javascript, everything is handled by css):
.Heading {
left:0px;
width: 250px;
position: relative;
background-color: #999999;
padding: 10px;
text-align: center;
border: 1px solid black;
}
.Heading:hover {
background-color: red;
color: white;
}
<h1 class = "Heading">IRON MAN</h1>
<h1 class = "Heading">CAPTAIN AMAERICA</h1>
<h1 class = "Heading">THOR</h1>
<h1 class = "Heading">BLACK WIDOW</h1>
So this is a very basic function (found and edited for my purposes) that alternates the div background color to white or black.
I would like to change the code to utilize the css variables I have in the root property and have no onClick functions inside the html. I want to keep html and js seperate, but I don't know how to go about this.
Can I have two buttons that can switch between the css variable colors for the div?
Thank you.
function changeColor(color) {
var element = document.getElementById('box');
element.style.backgroundColor = color;
}
root {
--white { color: #fff}
--black { color: #000}
}
.box {
width: 100px;
height: 100px;
border: 1px solid #aaa;
background-color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box" id="box">
</div>
<button onClick=changeColor('white')>white</button>
<button onClick=changeColor('black')>black</button>
You can set one css variable and onclick change the color.
Use document.body.style.setProperty('--main-color',color) to set color to var
function changeColor(color) {
document.body.style.setProperty('--main-color',color)
}
root {
--main-color{ color: #fff}
}
.box {
width: 100px;
height: 100px;
border: 1px solid #aaa;
background-color: var(--main-color);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box" id="box">
</div>
<button onClick=changeColor('white')>white</button>
<button onClick=changeColor('black')>black</button>
You can add a data-color attribute to your buttons which specifies the color (variable) to change to when clicking on the given button. Then you can add the click event listener to all your buttons with the class color-btn. Then when you click on a given button the event listener will be called, which will get the data attribute from the button clicked, and then use your changeColor function to change the div to the appropriate color (using the variable).
Also, you haven't defined your variables correctly. Firstly, you need to target the root using :root. Then you nee to set your variables using --variableName: COLOR. Lastly, in your changeColor function you need to use .style.backgroundColor = "var(--" +color +")" to correctly use the variable.
See working example below
[...document.getElementsByClassName("color-btn")].forEach(elem => {
elem.addEventListener('click', function() {
const btnColor = this.getAttribute('data-color');
changeColor(btnColor);
});
})
function changeColor(color) {
var element = document.getElementById('box');
element.style.backgroundColor = "var(--" +color +")";
}
:root {
--w: #fff;
--b: #000;
}
.box {
width: 100px;
height: 100px;
border: 1px solid #aaa;
background-color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box" id="box">
</div>
<button class="color-btn" data-color='w'>white</button>
<button class="color-btn" data-color='b'>black</button>
Register an onClick event on those buttons (you would have to assign a unique ID to them to reference them properly)
Example:
document.getElementById("myBtn").addEventListener("click", changeColor("white"));
edit
I see you're using jQuery, so:
$("#myBtn").on( "click", function() {
changeColor("white");
});
That way your HTML doesn't have JS in it. You would have 2 events, one for each button.
<!DOCTYPE html>
<html>
<head>
<style>
:root
{
--color-white:#fff;
--color-black:black;
}
.box
{
width: 100px;
height: 100px;
border: 1px solid #aaa;
}
</style>
<script>
function changeColor(color)
{
var element = document.getElementById('box');
var style = getComputedStyle(document.querySelector(':root'));
element.style.backgroundColor = style.getPropertyValue('--color-' + color);
}
</script>
</head>
<body>
<div class="box" id="box">
</div>
<button onClick=changeColor('white')>white</button>
<button onClick=changeColor('black')>black</button>
</body>
</html>
I am trying to create two buttons: one that adds a circle to the web page and one that deletes a circle.
There can be no more than 5 circles on the stage. If the add button is clicked and there are five circles on the page, an alert will pop up that tells the user no more circles can be added.
var circle = document.getElementById('#div');
$(function() {
$('#buttonOne').on('click', addItem);
$('#buttonTwo').on('click', removeItem);
});
function addItem(){
if (circle > 5) {
alert('You cannot add more than 5 objects');
} else {
document.body.appendChild(div);
};
}
function removeItem(){
if (circle== 0) {
alert('You have not added anything yet');
} else {
$(this).remove();
};
}
.circle {
display: block;
width: 50px;
height: 50px;
border-radius: 50%;
transition: background-color 350ms;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="Add Circle" id="buttonOne"/>
<input type="button" value="Delete Circle" id="buttonTwo"/>
<div class="circle"></div>
<p></p>
<script src="week4.js" type="text/javascript"></script>
There were a few flaws in your code:
When using getElementById, you should just give the id name, not the # character.
this does not refer to a circle in the removeItem function and hence won't work.
Appending circle variables to the body would create duplicate ids, which is not allowed per the HTML specification.
(minor flaw) > 5 would allow 6 circles to be created, so you should change it to >= 5.
(just unneeded code) binding the functions on the buttons does not have to be inside $(function(){});, it works fine without. Spares you a bit of code. :)
I've fixed those flaws for you below. Since I noticed you're already using jQuery functions, I took the liberty of taking advantage of jQuery in my code too. It could of course be implemented without jQuery. :)
$('#addButton').on('click', addItem);
$('#removeButton').on('click', removeItem);
function addItem() {
var circles = $(".circle");
if (circles.size() >= 5) {
alert('You cannot add more than 5 objects');
} else {
$("body").append("<div class='circle'></div>");
};
}
function removeItem() {
var circles = $(".circle");
if (circles.length == 0) {
alert('You have not added anything yet');
} else {
circles.last().remove();
}
}
.circle {
background-color: blue;
display: block;
height: 50px;
border-radius: 50%;
width: 50px;
transition: background-color 350ms;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="addButton">Add a circle</button>
<button type="button" id="removeButton">Remove a circle</button>
JSFiddle
Seems like you are missing some stuff in your js.
getElementbyId function just needs the name of the ID as an argument. So skip the pound sign (#).
Also. You are comparing "circle" to 0. Circle is a ID. And for best practices if several elements should use same ID, you should use the class attribute instead. So you need to figure out how to get out a number from the variable circle in order to compare it to another number.
function addItem() {
var circle = $(".circle");
if(circle.length >= 5) {
alert('You cannot add more than 5 objects');
} else {
$('<div/>').addClass('circle').appendTo($('#body'));
};
}
function removeItem() {
var circle = $(".circle");
if(circle.length == 0) {
alert('You have not added anything yet');
} else {
circle.eq(0).remove();
};
}
$('#buttonOne').click(addItem);
$('#buttonTwo').click(removeItem);
.circle {
background-color: blue;
display: block;
height: 50px;
border-radius: 50%;
width: 50px;
transition: background-color 350ms;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="buttonOne">b1</button>
<button id="buttonTwo">b2</button>
<div id="body"></div>
I need to remove CSS hover functionality using JavaScript.
I have a button on a form which submits data to our db server. Using OnClientClick() of an ASP.NET Button control I would like to change the element's text to 'Submitting..' using getElementById(), change the background color of the button to Light Grey and more importantly disable the following .button:hover effect I have in my CSS.
.button:hover,
.content-form input.button:hover,
#comment-form #submit:hover
{
background-color: #333;
}
All I am really interested in is the Javascript to remove/disable the above CSS
e.g. OnClientClick="getElementByID('ButtonName').blahblahblah;"
Working fiddle: https://jsfiddle.net/bm576q6j/17/
var elms = document.getElementsByClassName("test");
var n = elms.length;
function changeColor(color) {
for(var i = 0; i < n; i ++) {
elms[i].style.backgroundColor = color;
}
}
for(var i = 0; i < n; i ++) {
elms[i].onmouseover = function() {
changeColor("gray");
};
}
Edit: Sorry for not noticing last part of your question before I answered :)
There are a lot of solutions for solving your problem.
For example:
1- Using HTML disabled attribute.
OnClientClick="getElementByID('ButtonName').disabled=true;
2- Add a class which overrides the previous style.
.button:hover,
.content-form input.button:hover,
#comment-form #submit:hover
{
background-color: #333;
}
.button.submitted:hover
{
background-color: gray;
}
Js:
OnClientClick="getElementByID('ButtonName').className = "submitted";
and etc
In this case it removes the class attribute eliminating all defined classes, but then adds that should not be removed.
On jsfiddle
function disableHover(elem) {
elem.removeAttribute('class');
elem.setAttribute('class', 'another');
}
.button:hover {
background-color: #333;
}
.another {
background-color: lightgray;
}
<button class="button" onclick="disableHover(this);">hover</button>
But the best way of doing this is so, simple and works well.
function disableHover(elem) {
elem.classList.remove('button');
elem.classList.add('another');
}
.button:hover {
background-color: #333;
}
.another {
background-color: lightgray;
}
<button class="button" onclick="disableHover(this);">hover</button>
On jsfiddle
First of all your css is wrong. It should be:
.button:hover, .content-form input.button:hover, #comment-form, #submit:hover {
background-color: #333;
}
and you are adding css with id and class. You should not do that. Just add with class and use document.getElementById('submit').removeAttribute('class')
Im new to jQuery and have been researching and playing with it as much as possible my issue is im running out of time i need to get this project done asap. Anyways my question...
I have a link when clicked it calls a jquery ajax function which is al working properly... upon success i want the code to change the background colour of a div but this depends on its current colour cause it can be switched back and forth between two colours...
anyways heres what ive been playing with...
highlightColor = "#d8fe00"; //Updated to not cause confusion...
whiteColor = "#ffffff"; //Updated to not cause confusion...
$("input[value*='" + cId + "']").closest("div[class*='link-black']").attr("background-color", function(iPos, color) {
if(color != highlightColor) { return highlightColor; }
else { return whiteColor; }
}
Any help would be appreciated thanks in advance!!
Consider using .toggleClass instead:
CSS:
.highlight { background-color: 'yellow'; }
JS:
$("#selector").toggleClass("highlight");
How about not styling with javascript and taking advantage of good ol' CSS?
CSS
.white { background-color: white; }
.white.highlight { background-color: yellow; }
.red { background-color: red; }
.red.highlight { background-color: pink; }
JS
$("input[value*='" + cId + "']").closest("div[class*='link-black']").toggleClass('highlight');
.classOne { color: red; }
.classTwo { color: blue; }
.classThree { color: green; }
.classOne.highlighted { background-color: white; }
.classTwo.highlighted { background-color: black; }
.classThree.highlighted { background-color: purple; }
In the AJAX callback, all you have to do is add the "highlighted" class to your element. You can let the CSS figure out which color the text is and which color the background should be. The classes should obviously be more descriptive than classOne though.