how to make Active Buttons once it is selected - javascript

I have this code where I link few flies in an IFrame, i want the color of the selected button to change and remain different until another button is pressed.
<style>
.myButton:active
{
position:relative;
top:1px;
}
</style>
<a class="myButton " href="" target="someFrame">Button1</a>
<a class="myButton " href="" target="someFrame" >Button 02</a>
<a class="myButton " href="" target="someFrame">Button 03</a>
<a class="myButton " href="" target="someFrame">Button 04</a>
<a class="myButton " " target="someFrame" >Button 05</a>

What you could do is have a JS/jQuery function that is called when the button is pressed. That function would be something like the pseudo code below:
function(){
removeClassFromOtherButtons('activeClass');
this.addClass('activeClass');
}
Then in your CSS, have .activeClass have a different colored background.

If you'd prefer a solution without JavaScript, you can achieve that with some hidden radiobutton trickery:
input[type="radio"][name="toggleRadio"] {
display: none;
}
input[type="radio"][name="toggleRadio"] + a label {
cursor: pointer;
}
input[type="radio"][name="toggleRadio"]:checked + a {
color: #000;
text-decoration: none;
}
<input type="radio" name="toggleRadio" id="toggleRadio1"><label class="myButton" for="toggleRadio1">Button1</label>
<input type="radio" name="toggleRadio" id="toggleRadio2"><label class="myButton" for="toggleRadio2">Button2</label>
<input type="radio" name="toggleRadio" id="toggleRadio3"><label class="myButton" for="toggleRadio3">Button3</label>
<input type="radio" name="toggleRadio" id="toggleRadio4"><label class="myButton" for="toggleRadio4">Button4</label>
<input type="radio" name="toggleRadio" id="toggleRadio5" checked><label class="myButton" for="toggleRadio5">Button5</label>

On your css file create an .active class that will be added to a button when pressed and removed from the others.
var buttons = document.querySelectorAll('.myButton');
buttons.forEach(function(button) {
button.addEventListener('click', function() {
toggleClass(buttons, this);
});
});
function toggleClass(buttons, buttonToActivate) {
buttons.forEach(function(btn) {
btn.classList.remove('active');
});
buttonToActivate.classList.add('active');
}

So, the :active is a :pseudo-class that is used when the button or anchor is being pressed.
If you want to your button to have a active state you need mark it with another class.
var buttons = document.querySelectorAll('.myButton');
var activeClassName = 'active';
function activeState(items, activeName) {
for(var i = 0; i < items.length; i++) {
if(items[i].classList.contains(activeName)) {
items[i].classList.remove(activeName);
}
}
}
for(var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function(e){
activeState(buttons, activeClassName);
e.target.classList.add(activeClassName);
});
}
.myButton {
position:relative;
top:1px;
}
.myButton.active {
background: #f00;
color: #fff;
border-color: #f00;
}
<button class="myButton">Test 1</button>
<button class="myButton">Test 2</button>
<button class="myButton">Test 3</button>
<button class="myButton">Test 4</button>
<button class="myButton">Test 5</button>
<button class="myButton">Test 6</button>
I used here vanilla javascript but this code can be re-written using ES6 or Jquery and it will be much more simple.
Here some reference links for you:
https://www.w3schools.com/css/css_pseudo_classes.asp
https://developer.mozilla.org/docs/Web/API/Element/classList
https://developer.mozilla.org/docs/Web/API/Element/addEventListener

Once you click the button call onclick function
Use common class name to remove active class from all buttons then add active class to specific button
In css give color which you want selected button to be
.active{
background:red;}
Onclick function
$(".mybutton").on("click",function(event){ addclassactive(event.target);
}
function addclassactive (caller){
$(".mybutton").removeClass("active");
$(caller).addClass("active"):
}

Related

How to change background color of button while clicking on it

I have a input box which consists of many buttons. i want it to behave like when clicking on a button i want that button row's background to be changed and revert it when clicking on other button.
I tried many approach but nothing works.
Can anyone help me in this scenario?
Here is my code:
var buttons = document.querySelectorAll(".green");
for (button in buttons) {
buttons[button].onclick = function() {
console.log('test') var yellowButton = document.querySelectorAll(".yellow")[0];
if (this.className == "green") {
if (yellowButton) yellowButton.className = "green";
this.className = "yellow";
}
}
}
Are you trying to do some sort of toggling like this?
function myFunc(btn) {
//get the current active button
var activeBtn = document.querySelector('button.active-btn');
if (activeBtn) {
activeBtn.classList.remove('active-btn'); //remove the .active-btn class
}
btn.classList.add('active-btn'); //add .active-btn class to the button clicked
}
.active-btn.green {
background-color: green;
}
.active-btn.yellow {
background-color: yellow;
}
.active-btn.red {
background-color: red;
}
.active-btn.blue {
background-color: blue;
}
button {
color: orange
}
<div>
<button type="button" class="red" onclick="myFunc(this)">Red</button>
<button type="button" class="blue" onclick="myFunc(this)">Blue</button>
<button type="button" class="green" onclick="myFunc(this)">Green</button>
<button type="button" class="yellow" onclick="myFunc(this)">Yellow</button>
</div>
You can also try adding a default "active-btn" class to the button you want and also adding a disable/enable effect like so:
function myFunc(btn) {
//remove .active-btn class if button is currently active
if (btn.className.indexOf('active-btn') !== -1) {
btn.classList.remove('active-btn');
} else {
//get the current active button
var activeBtn = document.querySelector('button.active-btn');
if (activeBtn) {
activeBtn.classList.remove('active-btn'); //remove the .active-btn class on currently active button
}
btn.classList.add('active-btn'); //add .active-btn class to the button clicked if not active
}
}
.active-btn.green {
background-color: green;
}
.active-btn.yellow {
background-color: yellow;
}
.active-btn.red {
background-color: red;
}
.active-btn.blue {
background-color: blue;
}
button {
color: orange
}
<div>
<button type="button" class="active-btn red" onclick="myFunc(this)">Red</button>
<button type="button" class="blue" onclick="myFunc(this)">Blue</button>
<button type="button" class="green" onclick="myFunc(this)">Green</button>
<button type="button" class="yellow" onclick="myFunc(this)">Yellow</button>
</div>

How to add class to buttons on click

Sorry for silly question , but I can't add class to button on click. I have list of buttons and on click I need to change background of active button . I dont know how to get index of element on click inside list and add class. I need to make it on pure javascript. Only need to leave $(document).ready(function() . Here is my fiddle https://jsfiddle.net/armakarma/ns5tfcL0/15/
HTML
<div class="content-itinerary__buttons-wrapper">
<button class="content-itinerary__buttons description-text ">Day 2</button>
<button class="content-itinerary__buttons description-text">Day 3</button>
<button class="content-itinerary__buttons description-text">Day 4</button>
</div>
JS
$(document).ready(function() {
let myBtns=document.querySelector('.content-itinerary__buttons-wrapper')
myBtns.addEventListener('click', ()=>{
console.log('test')
})
});
Only need to leave $(document).ready(function()
I am not sure why do you need to leave that when you have the equivalent JavaScript (DOMContentLoaded).
Loop through all the buttons, inside the event handler function first remove the class from all the buttons then add the class only to the clicked button:
document.addEventListener('DOMContentLoaded', () => {
let myBtns=document.querySelectorAll('.content-itinerary__buttons');
myBtns.forEach(function(btn) {
btn.addEventListener('click', () => {
myBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
});
});
});
.active {
color: #fff;
background-color: #4CAF50;
}
<div class="content-itinerary__buttons-wrapper">
<button class="content-itinerary__buttons description-text ">Day 2</button>
<button class="content-itinerary__buttons description-text">Day 3</button>
<button class="content-itinerary__buttons description-text">Day 4</button>
</div>
You just need to use event object in click event
$(document).ready(function() {
let myBtns=document.querySelectorAll('.content-itinerary__buttons-wrapper')[0];
myBtns.addEventListener('click', (e)=> {
if (e.target.className.indexOf('clicked') === -1) {
e.target.className += ' clicked';
} else {
e.target.className = e.target.className.replace(' clicked', '');
}
})
});
This is your solution
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("content-itinerary__buttons");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
.content-itinerary__buttons-wrapper {
display: flex;
margin-top: 20px;
}
.content-itinerary__buttons {
flex-grow: 1;
padding: 21px 15px 15px 15px;
box-sizing: border-box;
border: 1px solid #D7D7D7;
outline: none;
&:not(:last-child) {
border-right: 0;
}
}
.active, .btn:hover {
background-color: red;
color: white;
}
<div class="content-itinerary__buttons-wrapper" id="myDIV">
<button class="content-itinerary__buttons description-text active ">Day 2</button>
<button class="content-itinerary__buttons description-text">Day 3</button>
<button class="content-itinerary__buttons description-text ">Day 4</button>
<button class="content-itinerary__buttons description-text">Day 5</button>
<button class="content-itinerary__buttons description-text">Day 6</button>
<button class="content-itinerary__buttons description-text">Day 7</button>
<button class="content-itinerary__buttons description-text">Day 8</button>
<button class="content-itinerary__buttons description-text">Day 9</button>
<button class="content-itinerary__buttons description-text">Day 10</button>
</div>
See Code link
I would definitely use Element.classList API for adding/removing classes to/from elements.
Why?
Adding/removing classes won't affect other classes already set to the element
Updating the className of the element will replace all existing classes
It comes with handy functions like "toggle" and "replace
Your code will look something like this:
$(document).ready(function() {
let myBtns=document.querySelectorAll('.content-itinerary__buttons-wrapper')
myBtns
.forEach(btn => btn
.addEventListener('click', (e)=>{
// Check if the classList already exists on the element clicked
// If so, remove it
// Else, add it
e.classList.contains('clicked')
? e.classList.add('clicked')
: e.classList.remove('clicked');
})
);
});
Onclick of the button you can set class name to the button
function a(e)
{
e.setAttribute("class","active");
}
.active
{
color:red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content-itinerary__buttons-wrapper">
<button class="content-itinerary__buttons description-text" onclick="a(this)">Day </button>
<button class="content-itinerary__buttons description-text" onclick="a(this)">Day </button>
<button class="content-itinerary__buttons description-text" onclick="a(this)">Day </button>
</div>
If you going to get rid of jQuery replace wrapper function to use listen for DOMContentLoaded event. It's the same as jQuery documentReady.
In your click handler use event object, ev.target in my example is a button which fired the event. Then use classList property to add your class.
document.addEventListener('DOMContentLoaded', function(){
let myBtns=document.querySelector('.content-itinerary__buttons-wrapper')
myBtns.addEventListener('click', (ev)=>{
let btn = ev.target;
btn.classList.add('red');
});
});
Just use forEach loop :)
$(document).ready(function() {
let myBtns=document.querySelectorAll('.content-itinerary__buttons-wrapper')
let myAllButtons = myBtns.querySelectorAll('.content-itinerary__buttons')
myAllButtons.forEach(function(element) {
element.onclick = () => element.classList.add('some-class')
})
});

Toggle changed button class

I want to create a toggle button where will change button class from class="fa fa-toggle-off" to class="fa fa-toggle-on" when clicked.
<button class="btn btn-default" id="btn" name="btn"><i id="change" class="fa fa-toggle-off"></i></button>
I create the javascript below, however it changed the button style="display:none" instead change its class.
$(function() {
$('#btn').click(function(e) {
e.preventDefault();
var display = true,
image = 'details_close.png';
if ($('.td1:visible').length == $('.td1').length) {
display = false;
image = 'details_open.png';
}
$('.td1').toggle(display);
$("#change").toggle(function()
{
$('#change').removeClass("fa-toggle-off").addClass("fa-toggle-on");
}, function() {
$('#change').removeClass("fa-toggle-on").addClass("fa-toggle-off");
});
});
});
There you go, I used toggleClass (http://api.jquery.com/toggleclass/) function to toggle the class when you click your button, it'll disabled this class fa-toggle-off and activate this class fa-toggle-on on click
(https://api.jquery.com/click/) and vice versa.
$(document).ready(function(){
$("#btn").click(function() {
$("#change").toggleClass("fa-toggle-off fa-toggle-on");
});
});
.fa-toggle-off {
background-color: #F00;
}
.fa-toggle-on {
background-color: #0F0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn btn-default" id="btn" name="btn">
Button <i id="change" class="fa fa-toggle-off">AAA</i>
</button>
Beware, in your code you're checking if #change is clicked, the button got #btn ID attribute.
Wish I helped you.
You can use .toggleClass to add or remove class alternatively
$(document).ready(function() {
$("#btn").click(function() {
$("#change").toggleClass("fa-toggle-on");
});
});
.fa-toggle-off {
color: red;
}
.fa-toggle-on {
color: blue;
}
.btn-default {
display: block;
width: 200px;
height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn btn-default" id="btn" name="btn"><i id="change" class="fa fa-toggle-off">Hello my button</i></button>
You can check if on/off class exist and then can remove existing class & add new class as below code:
$(function() {
$('#btn').click(function(e) {
e.preventDefault();
var display = true,
image = 'details_close.png';
if ($('.td1:visible').length == $('.td1').length) {
display = false;
image = 'details_open.png';
}
$('.td1').toggle(display);
if ($("#change").hasClass("fa-toggle-off"))
{
$('#change').removeClass("fa-toggle-off").addClass("fa-toggle-on");
} else {
$('#change').removeClass("fa-toggle-on").addClass("fa-toggle-off");
});
});
});
Hope it helps you.

How to apply javascript to multiple button groups

I have css and js on a button group so that when you click a button from the group it shows as active, and when you click a different button, that button becomes active and the rest are cleared. I have to have 22 of these button groups (I only put 2 here for the sake of space) on my page, when I have just one the code works, but when I add the others everything comes crumbling down, can anyone help! How do use the script multiple times, where the script is applied to every group and doesn't intervene with the others.
function codeAddress() {
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
}
window.onload = codeAddress;
.btn {
background-color: white;
border: 3px solid #0099ff;
color: #0099ff;
cursor: pointer;
float: left;
padding: 10px 16px;
font-size: 18px;
}
.active,
.btn:hover {
background-color: #0099ff;
color: white;
border: 3px solid #0099ff;
cursor: pointer;
}
<div id="myDIV">
<button class="btn active">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
<div id="myDIV">
<button class="btn active">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
Here give this ago. I believe this is the intended response you expect when clicking button from different groups. Something like radio buttons. As already mentioned an ID can only represent one element not several. Use class instead. So i have changed your id to a class btn-group.
function codeAddress() {
const btnClick = function () {
this.parentNode.getElementsByClassName("active")[0].classList.remove("active");
this.classList.add("active");
};
document.querySelectorAll(".btn-group .btn").forEach(btn => btn.addEventListener('click', btnClick));
// This is the same as above just another way of doing it. use which ever you like
// var btns = document.querySelectorAll(".btn-group .btn");
// for (var i = 0; i < btns.length; i++) {
// btns[i].addEventListener("click", function () {
// this.parentNode.getElementsByClassName("active")[0].classList.remove("active");
// this.classList.add("active");
// });
// }
}
window.onload = codeAddress;
.btn {
background-color: white;
border: 3px solid #0099ff;
color: #0099ff;
cursor: pointer;
float: left;
padding: 10px 16px;
font-size: 18px;
}
.active,
.btn:hover {
background-color: #0099ff;
color: white;
border: 3px solid #0099ff;
cursor: pointer;
}
<div class="btn-group">
<button class="btn active">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
<br style="clear:both">
<div class="btn-group">
<button class="btn active">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
Here the example what you need https://jsbin.com/bomegabiqo/1/edit?html,js,output
First of all, I want to say that you don't need to have two div with the same id
The second point is that you need to attach eventListener to the parent element, due to best-practice and performance optimization (you can read about it somewhere)
So here is updated version of HTML:
<div id="myGroupButtonsWrapper">
<div id="myDIV">
<button class="btn active">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
<div id="myDIVV">
<button class="btn">GQL</button>
<button class="btn">PSV</button>
<button class="btn">WT2</button>
<button class="btn">NBV</button>
<button class="btn">MBD</button>
</div>
</div>
And JavaScript:
function codeAddress() {
function myClickCallback(e) {
if (e.target.className === 'btn') {
var allButtons = document.querySelectorAll("#myGroupButtonsWrapper .btn");
allButtons.forEach((elem) => {
elem.className = elem.className.replace(" active", "");
});
e.target.className += ' active';
} else {
return;
}
}
var header = document.getElementById("myGroupButtonsWrapper");
header.addEventListener("click", myClickCallback);
}
window.onload = codeAddress;
It's not working because you have multiple IDs:
<div id="myDIV">...</div>
<div id="myDIV">...</div>
You can't do this - first, it's invalid HTML, and second, it'll do one of two things with the JS: cause an error, which you can see in the console, or it'll treat header as a NodeList, which is a collection of nodes that match the query selection, which means that it won't work. If you make them all have different IDs (e.g. div1, div2, div3, etc), it'll work if you modify your code to take multiple divs.
The other option is to make a class (e.g. myDIV) and modify your existing JavaScript code to use a class.
Instead of individual buttons, I would recommend using radio buttons for something like this. It already has functionality built in to group together for a selection similar to what you're going for. Then you just have to use built in commands to set the active button or check the values.
https://www.w3schools.com/jsref/prop_radio_checked.asp
https://www.w3schools.com/html/html_forms.asp
it is fairly simple to accomplish this using just 3 steps.
// First step is to create a onBtnClick handler function:
// The btn which was clicked can be accessed from event.target
// And then we can use the build in function classList.toggle to toggle the active class on that btn
const onBtnClickHandler = function (ev){ev.target.classList.toggle("active")};
// Next step is to find all btns, this can be done using the build in querySelectorAll function
const btns = document.querySelectorAll('.btn'); //returns NodeList array
// Last step is to add the eventListener callback function to each btn
btns.forEach(btn => btn.addEventListener('click', onBtnClickHandler));
Hope this helps.

Change CSS of div when clicking on a button

Is it possible to change the background image of a div when a button outside of the div is selected?
e.g.
HTML
<div id="change"></div>
<div id="buttons">
<button class="button1">this</button>
<button class="button2">that</button>
<button class="button3">there</button>
<button class="button4">then</button>
</div>
CSS
#change{
background-image: url("this.jpg")
}
Desired effect when clicking button 2 (same for each button; 3 = there.jpg, 4 = then.jpg)
#change{
background-image: url("that.jpg")
}
Using javascript you can set the backgroundImage. Using jQuery you'd use $.css('background-image');
You could also use JS/jQuery to add a class to the element, and you can set the background-image in CSS for that class.
document.getElementById('button').addEventListener('click',function() {
document.getElementById('change').style.backgroundImage = 'url(https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg)';
})
#change {
background: #eee;
width: 600px;
height: 375px;
}
<button id="button">button</button>
<div id="change"></div>
document.getElementById('button').addEventListener('click',function() {
document.getElementById('change').classList.add('bg');
})
#change {
background: #eee;
width: 600px;
height: 375px;
}
#change.bg {
background-image: url(https://futurism.com/wp-content/uploads/2015/11/neildegrassetyson.jpg)
}
<button id="button">button</button>
<div id="change"></div>
You can do this but it will require JavaScript:
Your HTML:
<div id="buttons">
<button class="button1" onclick="changeBG('image1.jpg')">this</button>
<button class="button2" onclick="changeBG('image2.jpg')">that</button>
<button class="button3" onclick="changeBG('image3.jpg')">there</button>
<button class="button4" onclick="changeBG('image4.jpg')">then</button>
</div>
<script>
function changeBG(image) {
var urlString = "url(" + image + ")";
document.getElementById('change').style.backgroundImage = urlString;
}
</script>
This is not the prettiest way to do this but it should accomplish getting you started.
This is what you need in jQuery :D
$('#buttons button').on('click',function() {
var val = $(this).text();
$('#change').css('background-image','url('+val+'.jpg)');
});
put the script inside $(document).ready(function() {

Categories

Resources