Toggle class of multiple ids (javascript) - javascript

I have 2 elements that each have different background colors and upon click, I'd like to make them change to a different color.
Here is code that works if the elements do not already have background-color:
html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style media="screen">
.buttons {
width: 150px;
height: 50px;
border: solid 2px #999;
text-align: center;
color: black;
cursor: pointer;
}
background-color: red;
}
</style>
</head>
<body>
<div id="buttonGallery">
<div id="button_1" class="buttons">
<p>button_1</p>
</div>
<div id="button_2" class="buttons">
<p>button_2</p>
</div>
</div>
<script type="text/javascript">
$("#button_1").click(function() {
$('#button_1').toggleClass('selected');
});
$("#button_2").click(function() {
$('#button_2').toggleClass('selected');
});
</script>
</body>
</html>
However, if I give each id a background-color, they do not change color upon click:
<style media="screen">
.buttons {
width: 150px;
height: 50px;
border: solid 2px #999;
text-align: center;
color: black;
cursor: pointer;
}
#button_1 {
background-color: blue;
}
#button_2 {
background-color: green;
}
.selected {
background-color: red;
}
Also is there a way to write one function that turns each element red upon click? (Rather than write a function for each button. I will eventually have 8 buttons.) Thank you! Any help would be really appreciated!

First of all the .selected the class will apply each time but due to the selector priority it will be overwritten by .button. So there are tones of ways to fix it.
You can use !important keyword (not recommended at all)
.selected {
background-color: red !important;
}
NOTE: You should avoid as much as you can from using !important keyboard, but in your particular case this is the best way to do it, but I highly recommend changing your styling method and use the pseudo-class selector for your main classes instead. just like this:
.buttons:first-of-type {
background-color: blue;
}
.buttons:nth-of-type(2) {
background-color: green;
}
/* and so on */
And use a specific method for your selected class something like this:
.buttons.selected {
background-color: red;
}
Or
You can use a straight forward but repetitive approach. So make your .selected class selector something like this:
#button_1.selected, #button_2.selected /* and so on */ {
background-color: red;
}
Also for simplifying your js code you can do as follows:
$('.buttons').click(function () {
$(this).toggleClass("selected"); // $(this) keyword will refer to the clicked button, each time attribute with class buttons got clicked.
});

I think your problem is CSS Specificity.
The ID selector (#) will have a higher specificity than the class selector (.)
Try changing
.selected {
background-color: red;
}
to
#button_1.selected, #button_2.selected {
background-color: red;
}

If you want add ".selected" class for each button So you can try this one
I hope this will help you a lot.
$("button").each(function(){
$(this).on("click", function(){
$(this).toggleClass('.selected');
});
});

Just add background-color: red !important;
EDIT
you can use this like one function as requested.
$('.buttons').click(function(e) {
e.stopPropagation();
$(this).toggleClass('selected');
});
$("#button_1").click(function() {
$('#button_1').toggleClass('selected');
});
$("#button_2").click(function() {
$('#button_2').toggleClass('selected');
});
.buttons {
width: 150px;
height: 50px;
border: solid 2px #999;
text-align: center;
color: black;
cursor: pointer;
}
#button_1 {
background-color: blue;
}
#button_2 {
background-color: green;
}
.selected {
background-color: red !important;
}
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style media="screen">
.buttons {
width: 150px;
height: 50px;
border: solid 2px #999;
text-align: center;
color: black;
cursor: pointer;
}
background-color: red;
}
</style>
</head>
<body>
<div id="buttonGallery">
<div id="button_1" class="buttons">
<p>button_1</p>
</div>
<div id="button_2" class="buttons">
<p>button_2</p>
</div>
</div>
</body>

Here is the pure JS method.
You'll want to use querySelectorAll('.buttons').
const buttons = document.querySelectorAll('.buttons')
This will make a node list of all objects with the class .buttons.
Then you'll want to apply an event listener to each button by using forEach.
buttons.forEach(button=>{
button.addEventListener('click', ()=>{})
Then you can write a function for when a button is clicked.
const buttons = document.querySelectorAll('.buttons');
buttons.forEach(button=>{
button.addEventListener('click', ()=>{
button.classList.toggle('selected')
})
})
This will update automatically as you add elements with a class of buttons.
And then as others mentioned, add !important to the .selected class background-color property.

Related

How do I change the contents of a CSS element after a :hover pseudo-element activates using JavaScript?

I currently have 2 boxes, one box that is red, and when my mouse hover overs it the box turns red. The other box is blue, and when my mouse hovers over the box it turns blue.
What I want to have happen is that when my mouse hovers over box 1 the box turns blue AND box 2 turns red. (Same idea with Box 2 but switch the colors
Here is the code that I tried already, I know that the issue is with the JavaScript but I don't understand why the JavaScript isn't working
const outlineOne = document.querySelector('.outlineOne');
const outlineOneHover = window.getComputedStyle(outlineOne, ':hover');
const outlineTwo = document.getElementsByClassName('outlineTwo')
if (outlineOneHover.style.background = blue) {
outlineTwo[0].style.backgroundColor = 'red';
};
body {
background: #2F2F2F
}
.outlineOne,
.outlineTwo {
display: inline-block;
background: #2F2F2F;
width: 100px;
height: 100px;
border: 2px solid black;
margin: 20px 20px;
}
.outlineTwo {
background: blue;
}
.outlineOne {
background: red;
}
.outlineOne:hover {
background: blue;
}
.outlineTwo:hover {
background: red;
}
<div class='parent'>
<div class="outlineOne"></div>
<div class="outlineTwo"></div>
</div>
You can toggle a single class on both objects on mouseover and mouseout.
const outlineOne = document.querySelector('.outlineOne');
const outlineTwo = document.querySelector('.outlineTwo');
function changeBG(){
outlineOne.classList.toggle("active");
outlineTwo.classList.toggle("active");
}
outlineOne.addEventListener("mouseover",changeBG);
outlineTwo.addEventListener("mouseover",changeBG);
outlineOne.addEventListener("mouseout",changeBG);
outlineTwo.addEventListener("mouseout",changeBG);
body {
background: #2F2F2F
}
.outlineOne,
.outlineTwo {
display: inline-block;
background: #2F2F2F;
width: 100px;
height: 100px;
border: 2px solid black;
margin: 20px 20px;
}
.outlineTwo {
background: blue;
}
.outlineOne {
background: red;
}
.outlineOne.active {
background: blue;
}
.outlineTwo.active {
background: red;
}
<div class='parent'>
<div class="outlineOne"></div>
<div class="outlineTwo"></div>
</div>
You have two options here:
Have a div that wraps both outlineOne and outlineTwo and have a :hover selector on that, and then no JavaScript is needed (like your parent div in your example)
.parent:hover .outlineOne {
background: blue;
}
.parent:hover .outlineTwo {
background: red;
}
Add a CSS class instead of adding :hover via JavaScript (so like .outlineOne.addedClass { background: blue; }, and listen for a mouseover event in JavaScript.
Technically you're not supposed to manually add a :hover to an element manually because it's a trusted event that should be user-activated.

Javascript set button active

I have a table of buttons and once it is populated, I am using
document.getElementById("btn0").click();
to click the first button. The button is doing what it should do, but the background color of the button is not changing the same way it does when I am clicking it manually.
As you can see when its running, the background-color of the div is changing, but the button is not set to active.
Code Snippet:
var myfunc = function(){
document.getElementById("test").style.backgroundColor="red";
};
document.getElementById("btn0").click();
.btn{
border: none;
color: white;
width: 100%;
padding: 5px 5px 5px 5px;
height: 50px;
cursor: pointer;
font-size: 12px;
background-color: #343a40;
}
.btn:active .btn.active{
background-color:green;
outline: none;
}
.btn:focus{
background-color:green;
outline: none;
}
#test{
background-color: green;
width: 600px;
height: 400px;
}
<button class="btn" onclick="myfunc()" id="btn0"> Cool button</button>
<div id="test">
Hello
</div>
Here is a link to a jsfiddle I created:
https://jsfiddle.net/58hrwcgo/3/
There's a difference between click and focus.
click() clicks on the element and then unfocuses, unlike a real mouse click, which clicks and then focuses.
I would recommend simulating a real click by doing both:
document.getElementById("btn0").click();
document.getElementById("btn0").focus();
js
const btn = document.getElementById("btn0")
var myfunc = function(){
document.getElementById("test").style.backgroundColor="red";
btn.focus();
};
btn.click();
css
...
.btn:active, .btn.active{
background-color:green;
outline: none;
}
...
When clicking manually a focus state ist triggered first. That's why the appearance changes according to your class .btn:focus.
document.getElementById("btn0").focus();
document.getElementById("btn0").click();
will lead to the desired behavior.
Furthermore you're missing a colon in your CSS-Example within the :active state:
.btn:active, .btn.active { ... }
You can try the HTML DOM focus() method.
document.getElementById("btn0").focus();
You can read more about this in here.
Method 1:
You can use querySelector function to select the button, then add "active" to its class list.
You also need to change the css selection of active button
var myfunc = function(){
document.getElementById("test").style.backgroundColor="red";
// add the following changes
const btn = document.querySelector(".btn")
btn.classList.add('active');
};
document.getElementById("btn0").click();
/* ....
/* change the btn active to the following */
.btn.active{
background-color:green;
outline: none;
}
/* .....
Method 2: Use addEventListener (preferred)
You can do the whole process in JavaScript without a need to use "onclick" in HTML
const test = document.querySelector("#test")
const btn = document.querySelector(".btn")
btn.addEventListener('click', ()=>{
test.style.backgroundColor="red";
btn.classList.add('active');
});
document.getElementById("btn0").click();
.btn{
border: none;
color: white;
width: 100%;
padding: 5px 5px 5px 5px;
height: 50px;
cursor: pointer;
font-size: 12px;
background-color: #343a40;
}
/* change the btn active to the following */
.btn.active{
background-color:green;
outline: none;
}
.btn:focus{
background-color:green;
outline: none;
}
#test{
background-color: green;
width: 600px;
height: 400px;
}
<button class="btn" id="btn0"> Cool button</button>
<div id="test">
Hello
</div>

Changing background color with addClass in jQuery

I am learning jQuery, and I've written a simple script that is intended to add (or remove) a class when a mouse enters (or leaves) a div. The new class adds a different height and is also supposed to change the background color and opacity of the entered div.
Here's the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Testing jQuery</title>
<style type="text/css">
div {
width: 400px;
height: 300px;
margin: 20px;
float: left;
}
#one {
background-color: red;
}
#two {
background-color: green;
}
#three {
background-color: blue;
}
.change {
height: 150px;
background-color: rgba(0,0,0,0.4);
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<script type="text/javascript">
$(document).ready(function () {
$("div").mouseenter(function () {
$(this).addClass("change");
});
$("div").mouseleave(function () {
$(this).removeClass("change");
});
});
</script>
</body>
</html>
While the height changes, there's no effect on the background-color property. Why is that so?
I've checked out the .mouseenter(), .mouseleave() and the .addClass() API documentation, but couldn't find anything specific to this problem.
Your javaScript code is 100% fine. The problem is in CSS You have written. Selection by id #one is more important than classname .one, so when you apply some #rules and .rules to the emenet at the same time, browser will chose the first ones as more important. If You can, try not to use #id selectors at all in css and leave it for javaScript usage.
css:
.one {
background-color: red;
}
.two {
background-color: green;
}
.three {
background-color: blue;
}
html:
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
demo: https://jsfiddle.net/cz8v1gy4/
Edited answer after a re-read:
You're running in to CSS specificity issues. IDs are more specific than classes, which means that your background color is going to stay the color of the ID and not the class. This is one reason why it's (often) recommended to not use IDs in CSS.
If you change everything over to classes it will work how you're expecting:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Testing jQuery</title>
<style type="text/css">
div {
width: 400px;
height: 300px;
margin: 20px;
float: left;
}
.one {
background-color: red;
}
.two {
background-color: green;
}
.three {
background-color: blue;
}
.change {
height: 150px;
background-color: rgba(0,0,0,0.4);
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<script type="text/javascript">
$(document).ready(function () {
$("div").mouseenter(function () {
$(this).addClass("change");
});
$("div").mouseleave(function () {
$(this).removeClass("change");
});
});
</script>
</body>
</html>
Try utilizing css selectors #one:hover, #two:hover, #three:hover , :hover pseudo-class, transition . See also Specificity
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Testing jQuery</title>
<style type="text/css">
div {
width: 400px;
height: 300px;
margin: 20px;
float: left;
}
#one {
background-color: red;
}
#two {
background-color: green;
}
#three {
background-color: blue;
}
#one:hover, #two:hover, #three:hover {
height: 150px;
background-color:rgba(0,0,0,0.4);
transition: height 1000ms, background-color 1000ms;
}
</style>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</body>
</html>
There are some good answers here and explanations why it's not working, but it looks like no one has answered how to do what it seems like your intent was.
Which was to add the two background colors together to get a darker color on hover. You can get around it changing it to a grey by adding something else in.
For example:
.change {
height: 150px;
background-image: linear-gradient(to right, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0.4) 100%)!important;
}
This puts a solid color gradient in as the background image which layers on top of the background color.
Like This JSFiddle
When you hover over div#one it becomes div#one.changed. Now with regard to background color you have two competing values:
#one {
background-color: red;
}
And:
.change {
background-color: rgba(0,0,0,0.4);
}
The first one wins, because it is more specific.
To get around this use
.change {
height: 150px;
background-color: rgba(0,0,0,0.4)!important;
}

Use JQuery to make color fade away, but keep boxes in place? [duplicate]

This question already has answers here:
How do you fade in/out a background color using jquery?
(9 answers)
Closed 7 years ago.
I've created a 16x16 grid. If you hover your mouse over a box, the box will turn pink. When you leave the box, the entire box disappears. I would like to make it so when you leave the box, the entire box stays intact, except the pink color fades away and is replaced with the original gray color after a second or so.
HTML:
<head>
<title>SketchPad</title>
<link rel="stylesheet" type="text/css" href="style.css" >
</head>
<body>
<h1> SketchPad </h1>
<div id="container">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="jquery.js"></script>
</body>
</html>
CSS:
h1 {
text-align: center;
color: black;
}
tr, td, table {
border-style: solid;
border-width: 1px;
background-color: gray;
margin: auto;
height: 25px;
width: 525px;
}
JS:
var rows=16;
var cols=16;
document.write("<table>");
for (i=0; i<rows; i++) {
document.write("<tr>");
for (j=0; j<cols; j++) {
document.write("<td>"+"</td>");
}
document.write("</tr>");
}
document.write("</table>");
$( "td").css("color", "red");
$("td").hover(function() {
$(this).css("background-color", "pink");
}, function () {
$(this).fadeOut("slow", function(){
});
});
In order to have a cross-browser supported solution you could use animation trough javascript. Problem is that most of the properties that are not numeric can't be animated using plain jQuery (and background-color is one of those)
One of the options is to use jquery-color plugin
Example:
$("#go").click(function(){
$("#block").animate({
backgroundColor: "#abcdef"
}, 1500 );
});
$("#sat").click(function(){
$("#block").animate({
backgroundColor: $.Color({ saturation: 0 })
}, 1500 );
});
OTOH, transitions support is quite good on modern browsers so you'll be quite safe if you use a css only solution (IE9 and below doesn't support it)
You could actually accomplish this all with css.
h1 {
text-align: center;
color: black;
}
tr, td, table {
border-style: solid;
border-width: 1px;
background-color: gray;
margin: auto;
height: 25px;
width: 525px;
}
td {
transition: 1s background-color;
}
td:hover {
background-color: pink;
}
Working demo: http://jsfiddle.net/5xvehb8o/
.grid {
height : 16px;
width : 16px;
border : solid 1px grey;
background-color : grey;
transition : 0.5s;
}
.grid:hover {
background-color : pink;
}
<div class="grid"></div>
<br />
<div class="grid"></div>
Full CSS solution, with transition that can be modified in property transition.

Hide/Show Div- Wordpress Category Pages

I have been looking for over 3 hours trying to figure this out so my apologies if you think this has been answered.
I am fully aware how to add a show/hide div to a page but I am struggling to add it to a category page in WP.
My site: http://www.ticketyoda.co.uk/6-nations-tickets
What I require is to be able to have a DIV under each category that can be shown when a button is selected. At present when I select a toggle it hides and then shows all divs on the page.
You're targeting all divs with the class "flip". You can remedy this by adding this to specify that you're only interested in the clicked-on element:
$(document).ready(function() {
$(".flip").click(function() {
var target= $(this).next(".panel");
$(target).toggle();
});
});
Have some more info.
See here..
http://www.ticketyoda.co.uk/professor-green
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".flip").click(function() {
$(".panel").slideToggle("");
});
});
</script>
html
<style type="text/css">
div.panel {
margin-top:10px;
margin-left:0px;
margin-bottom:120px;
padding: 0px;
background: #fff;
border: solid 1px #fff;
}
p.flip {
margin-top:0px;
margin-left:540px;
margin-bottom:0px;
padding: 0px;
margin-top:-32px;
background: #fff;
border: solid 1px #fff;
}
div.panel {
widht: 50%;
height: 60px;
display: none;
}
</style>
<p class="flip"><img src="http://www.ticketyoda.co.uk/wp-content/uploads/2013/03/ticketview.png" /></p>

Categories

Resources