I'm currently having some trouble automatically sorting buttons alphabetically. I can't figure out how to sort these buttons (jquery/javascript), but I want to do it automatically, when the page loads. Thanks for the help. Here's my code:
<style>
.games-button {
background-color: #383838;
color: #eeeeee;
text-align: middle;
text-decoration: none;
font-size: 14px;
cursor: pointer;
border-radius: 5px;
height:42px;
vertical-align: left;
display: inline-block;
letter-spacing: 0.5px;
float: left;
overflow:hidden;
margin-left:100px;
margin-bottom: 2px;
text-transform: uppercase;
}
.games-button:hover {
box-shadow: inset 0 0 100px 100px rgba(255, 255, 255, 0.1);
}
</style>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">A</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">Z</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">H</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">B</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">N</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">C</button>
Update:
This is a code I have that sorts the buttons on click of a button. How can I do this without a button?
<button onclick="sortList()">Sort</button>
<ul id="id01">
<button>z</button>
<button>a</button>
<button>b</button>
<button>l</button>
<button>b</button>
</ul>
<script>
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("id01");
switching = true;
while (switching) {
switching = false;
b = list.getElementsByTagName("button");
for (i = 0; i < (b.length - 1); i++) {
shouldSwitch = false;
if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
if (shouldSwitch) {
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}
</script>
It seems that you're getting into js development. Good luck with that.
In order to manipulate DOM elements, it's always easier if you put in some trails or hints to help your code find your elements.
In this case, all of your buttons are placed in the body element, so to make it easier to locate and replace the buttons, place them inside another element. Like so:
<div id="button-container">
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">A</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">Z</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">H</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">B</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">N</button>
<button class="games-button" style="width:240px;" onclick="window.open('/samplepage.html','_blank');">C</button>
</div>
Then locate them and sort them.
<script>
'use strict';
const buttonContainer = document.getElementById('button-container');
const sortedButtons = [... buttonContainer.children].sort((buttonA, buttonB) => {
const name1 = buttonA.innerText.toLowerCase();
const name2 = buttonB.innerText.toLowerCase();
if(name1 === name2){
return 0;
} else if(name1 < name2){
return -1;
} else {
return 0;
}
});
sortedButtons.forEach(button => buttonContainer.append(button));
</script>
That's it.
Related
I want to create a to do list that will add elements typed in <input type="text"> and delete when clicked on button with class .delete. When ever I push elements in an array. And innerHTML it in html page, the delete button stops working. The delete button works for elements that are written into Html code. If someone can help me I will be very thankful.
`
const itemsLIst = document.querySelector('.item-list'); // where we want to add our list
const addText = document.querySelector('.submit'); // add button
let deleteText = document.querySelectorAll('.delete'); // delete button
// const list = JSON.parse(localStorage.getItem('items')) || [];
let list = [];
function addItem(e) {
let text = document.querySelector('.input_bar').value; //text typed in input bar
if (text.length != 0) {
list.push(`<div>
<p>${text}</p>
<button class="delete" onclick='deleteItem'>🗴</button>
<button class="edit">Edit</button>
</div><hr>`);
itemsLIst.innerHTML = list.join('');
text = '0';
document.getElementById("myText").value = "";
} else {
return;
}
}
function deleteItem(e) {
this.parentElement.style.display = 'none';
}
for (var i = 0 ; i < deleteText.length; i++) {
deleteText[i].addEventListener('click', deleteItem);
}
addText.addEventListener('click', addItem);
<style>
body {
width: 100%;
height: 100vh;
background-color: rgb(115, 115, 197);
margin: 0;
padding: 0;
position: relative;
}
.container {
width:50%;
height:70%;
position: absolute;
background-color: rgb(241, 241, 241);
font-family: Arial, Helvetica, sans-serif;
border-bottom-left-radius: 25px;
border-bottom-right-radius: 25px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
overflow-y: scroll;
}
.heading {
width: 100%;
height: 122px;
background-color: #5B45B9;
display: flex;
align-items: center;
justify-content: center;
}
.heading h1 {
color: white;
font-size: 40px;
}
.item-list {
width: 100%;
padding: 0 0 30px 0;
}
.item-list div {
width: auto;
height: 60px;
}
p {
width: 60%;
float: left;
font-size: 25px;
padding-left: 30px;
margin-top: 12px ;
}
.item-list button {
width: 60px;
height: 60px;
font-size: 18px;
float: right;
}
.delete {
font-size: 30px;
color: red;
}
.input_form {
width: 100%;
padding: 30px 0 30px 0;
position: absolute;
bottom: 0;
text-align: center;
}
.input_form .input_bar {
width: 80%;
height: 50px;
font-size: 18px;
border: none;
}
.input_form button {
width: 10%;
height: 50px;
float: right;
margin-right: 30px;
}
</style>
<html>
<head>
</head>
<body>
<div class="container">
<div class="heading">
<h1>TO-DO LIST</h1>
</div>
<div class="item-list">
<div>
<p>TEEXT2</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT1</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT3</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT4</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
</div>
<div class="input_form">
<input type="text" class="input_bar" id="myText" placeholder="Add ITEM">
<button class="submit">+ADD ITEM</button>
</div>
</div>
</body>
</html>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT1</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT3</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
<div>
<p>TEEXT4</p>
<button class="delete">🗴</button>
<button class="edit">Edit</button>
</div>
</div>
<div class="input_form">
<input type="text" class="input_bar" id="myText" placeholder="Add ITEM">
<button class="submit">+ADD ITEM</button>
</div>
<script src="script.js"></script>
</div>
</body>
</html>`
You actually only trigger DOM "original" delete button (button loaded with your HTML code) with the line :
let deleteText = document.querySelectorAll('.delete'); // delete button
Your others .delete are loaded after the first DOM loading and are not even listed in "deleteText" array !
You have to refresh deleteText every time you add a new item. Something like :
const itemsLIst = document.querySelector('.item-list'); // where we want to add our list
const addText = document.querySelector('.submit'); // add button
let deleteText = document.querySelectorAll('.delete'); // delete button
// const list = JSON.parse(localStorage.getItem('items')) || [];
let list = [];
function addItem(e) {
let text = document.querySelector('.input_bar').value; //text typed in input bar
if (text.length != 0) {
list.push(`<div>
<p>${text}</p>
<button class="delete" onclick='deleteItem'>🗴</button>
<button class="edit">Edit</button>
</div><hr>`);
itemsLIst.innerHTML = list.join('');
text = '0';
document.getElementById("myText").value = "";
} else {
return;
}
}
function deleteItem(e) {
this.parentElement.style.display = 'none';
}
function triggerDeleteButton(){
deleteText = document.querySelectorAll('.delete'); // delete button
for (var i = 0 ; i < deleteText.length; i++) {
deleteText[i].addEventListener('click', deleteItem);
}
}
addText.addEventListener('click', function(){
addItem() ;
triggerDeleteButton() ;
}
);
Without refreshing, you can add and edit data by using local storage
For example, like below, you can try once!
<script>
let customerData = [];
// Inserting new customer record into local storage
function insert() {
let company = document.getElementById("company").value;
let obj = {company};
customerData.push(obj);
synData(customerData);
let customerDetails = JSON.parse(localStorage.getItem("customerString"));
clearFileds();
displayelements(customerDetails);
}
function displayelements(customerDetails) {
let html = "<table id='customer_data' border='1'><tr><th>Sl No</th><th>Company</th><th>Delete</th></tr>";
if(customerDetails == '') {
html+="<tr>No record found!</tr>";
} else {
customerDetails.map((values, index) => {
html+="<tr id='row_data'>";
html+="<td>"+index+"</td>";
html+="<td>"+values.company+"</td>";
html+="<td onclick='deleteRow(" + index + ")'>Delete</td>";
html+="</tr>";
} )
}
html+="</table>";
document.getElementById("display").innerHTML = html;
clearFileds();
}
// Delete the specific customer record from local storage
function deleteRow(deleteKey) {
let customerDetails = JSON.parse(localStorage.getItem("customerString"));
customerDetails.map((values, index) => {
if (index == deleteKey) {
customerDetails.splice(index, 1);
}
})
customerData = customerDetails;
synData(customerDetails);
displayelements(customerDetails);
}
// Clearing the form input field data
function clearFileds() {
document.getElementById("company").value = '';
}
// Updating local storage data
function synData(customerDetails) {
localStorage.setItem('customerString', JSON.stringify(customerDetails));
}
</script>
<html>
<head>
<title>Save</title>
</head>
<script ></script>
<body id="format_background">
<div id="customerAction" >
<h1>Customer data</h1>
<label>Company Name </label>
<input id="company" type="text" />
<button type="button" value="Save&Show" onclick="insert()" id="insert">Save</button>
</div>
<div id="display"></div>
</body>
</html>
I'm trying to make a portfolio with button filter to change images from b&w to original colours of the right category when click on button filter.
My images are correctly changed to b&w.
For now I managed to make the button change to the active state when I click on it but it's not staying with the active state after the click and I can't manage to remove the b&w on the images of the button category.
I'm not sure if I have done the code snippet right as it display an error.
var container = document.getElementById('filters-button-group');
container.addEventListener('click', event => {
var activeItem = container.querySelector('.button-selected');
if (activeItem !== null) {
activeItem.classList.remove('button-selected');
}
if (event.target === activeItem) {
return;
}
event.target.classList.add('button-selected');
$('#img').css('filter', 'none');
});
button {
/* BUTTON SET UP */
border: 4px solid green;
border-top: 0;
border-right: 0;
font-size: 10px;
text-decoration: none;
color: green;
display: block;
margin-bottom: 22px;
}
.button:active,
.button-selected {
/* SELECTED */
background: rgba(8, 140, 126, 50%);
border: 4px solid green;
}
#portfolio { /* POSITION TOTAL PORTFOLIO ZONE WITH BUTTONS */
text-align: center;
background: transparent;
position: absolute;
}
#portfolio img {
/* --- IMAGES BLACK AND WHITE --- */
filter: grayscale(100%) opacity(30%);
}
<section id="portfolio">
<div class="button-group filters-button-group">
<button class="button button-effect" data-filter=".A"><a href="#" class="opc-main-bg filter" >A</a></button>
<button class="button button-effect" data-filter=".B"><a href="#" class="opc-main-bg filter" >B</a></button>
<button class="button button-effect" data-filter=".C"><a href="#" class="opc-main-bg filter" >C</a></button>
<button class="button button-selected" data-filter="*">ALL</button>
</div>
<div
<div class="A"><img src="http://fakeimg.pl/365x365/ff0000/" width="50%" height="auto">
<div class="B"><img src="http://fakeimg.pl/365x365/ff0000/" width="50%" height="auto">
<div class="C"><img src="http://fakeimg.pl/365x365/ff0000/" width="50%" height="auto">
</section>
Use document.getElementsByClassName('filters-button-group') instead of document.getElementById('filters-button-group') because filters-button-group is a class not id. you can access its children as array
check this for reference:
https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
In this example, the first two photos are from group "A", the other photos are one in a group. When a button is clicked, it collects all img tags with the class filed in the "data-filter" attribute of the button and applies or removes a style.
var container = document.querySelectorAll('.filters-button-group .button');
for (let i = 0; i < container.length; i++) {
container[i].addEventListener('click', function () {
this.classList.toggle('button-selected');
var x = document.querySelectorAll(this.getAttribute('data-filter') + ' img');
var y = x[0].getAttribute('style');
if (y) {
for (var i = 0; i < x.length; i++) {
x[i].removeAttribute('style');
}
} else {
for (var i = 0; i < x.length; i++) {
x[i].setAttribute('style', 'filter:none');
}
}
});
}
// Button All -> add / remove effect on all images
var allFilterButt = document.querySelector('.filters-button-group .button-all');
var wrap = document.querySelector('#imgWrap');
var imgList = wrap.querySelectorAll('img');
allFilterButt.addEventListener('click', function () {
var x = wrap.getAttribute('data-eff');
if (x === 'off') {
for (var i = 0; i < imgList.length; i++) {
imgList[i].setAttribute('style', 'filter:none');
}
for (var i = 0; i < container.length; i++) {
container[i].classList.add('button-selected');
}
wrap.setAttribute('data-eff', 'on');
} else {
for (var i = 0; i < imgList.length; i++) {
imgList[i].removeAttribute('style');
}
for (var i = 0; i < container.length; i++) {
container[i].classList.remove('button-selected');
}
wrap.setAttribute('data-eff', 'off');
}
});
button {
/* BUTTON SET UP */
border: 4px solid green;
border-top: 0;
border-right: 0;
font-size: 10px;
text-decoration: none;
color: green;
display: block;
margin-bottom: 22px;
}
.button:active,
.button-selected {
/* SELECTED */
background: rgba(8, 140, 126, 50%);
border: 4px solid green;
}
#portfolio {
/* POSITION TOTAL PORTFOLIO ZONE WITH BUTTONS */
text-align: center;
background: transparent;
position: absolute;
}
#portfolio img {
/* --- IMAGES BLACK AND WHITE --- */
filter: grayscale(100%) opacity(30%);
}
<section id="portfolio">
<div class="button-group filters-button-group">
<button class="button button-effect opc-main-bg filter" data-filter=".A">A</button>
<button class="button button-effect opc-main-bg filter" data-filter=".B">B</button>
<button class="button button-effect opc-main-bg filter" data-filter=".C">C</button>
<button class="button button-effect opc-main-bg filter" data-filter=".D">D</button>
<button class="button button-effect opc-main-bg filter" data-filter=".E">E</button>
<button class="button-all button-selected opc-main-bg filter selected" data-filter="*">ALL</button>
</div>
<div id="imgWrap" data-eff="off">
<div class="A"><img
src="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_027_by_54ka.jpg"
width="50%" height="auto"></div>
<div class="A"><img
src="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_034_by_54ka.jpg"
width="50%" height="auto"></div>
<div class="B"><img
src="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_028_by_54ka.jpg"
width="50%" height="auto"></div>
<div class="C"><img
src="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_030_by_54ka.jpg"
width="50%" height="auto"></div>
<div class="D"><img
src="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_031_by_54ka.jpg"
width="50%" height="auto"></div>
<div class="E"><img
src="https://blog.54ka.org/wp-content/uploads/2020/08/horses-on-summer-meadow_032_by_54ka.jpg"
width="50%" height="auto"></div>
</div>
</section>
I am trying to create a text font colour drop down button where it gives you an option of multiple colour to pick from and then it would change the colour of the text. I am not sure on how to approach this and I am not meant to use jQuery. Any help would be appreciated. In the code below it shows other examples of other button where they change the user input entered into the contenteditable. I want the font colour button to do the same but just change the colour of the text
const TAB_KEY = 9;
const ENTER_KEY = 13;
const SHIFT_KEY = 16
const editor = document.querySelector('.editor');
editor.appendChild(document.createElement('li'));
editor.addEventListener('keydown', (e) => {
let code = e.keyCode || e.which;
if (code == TAB_KEY) {
e.preventDefault();
let parent = e.target;
let ul = document.createElement('ul');
let li = document.createElement('li');
ul.appendChild(li);
parent.appendChild(ul);
moveCursorToEnd(li);
} else if (code == ENTER_KEY) {
e.preventDefault();
let parent = e.target;
let li = document.createElement('li');
parent.appendChild(li);
moveCursorToEnd(li);
} else if (code == TAB_KEY * TAB_KEY){
e.preventDefault();
let parent = e.target;
let ol = document.createElement('ol');
let li = document.createElement('li');
ol.appendChild(li);
parent.appendChild(ol);
moveCursorToEnd(li);
}
});
function moveCursorToEnd(el) {
el.focus();
document.execCommand('selectAll', false, null);
document.getSelection().collapseToEnd();
}
/*editor.addEventListener('click', (x) => {
x = document.getElementById("b");
if(x.style.fontWeight == "bolder"){
x.style.fontWeight = "normal";
} else {
x.style.fontWeight = "bolder";
}
});*/
function bold(){
if(document.execCommand("bold")){
document.execCommand("normal");
}else{
document.execCommand("bold");
}
}
/*function underline(){
let x = document.getElementById("text");
if(x.style.textDecoration == "underline"){
x.style.textDecoration = "none";
}else{
x.style.textDecoration = "underline";
}
}*/
function underline(){
if(document.execCommand("underline")){
document.execCommand("none");
}else{
document.execCommand("underline");
}
}
/*Turns the font of the text to Italic*/
function italic(){
if(document.execCommand("italic")){
document.execCommand("normal");
}else{
document.execCommand("italic");
}
}
function highlighSelectedText(){
let sel = window.getSelection().getRangeAt(0);
let selText = sel.extractContents();
let span = document.createElement("span");
span.style.backgroundColor = "yellow";
span.appendChild(selText);
sel.insertNode(span);
}
/*function printPage(){
let printButton = document.getElementById("ul");
printButton.style.visibility = 'hidden';
window.print();
printButton.style.visibility = 'visible';
}*/
body{
margin-top:1em;
margin-bottom: 10em;
margin-right: 1em;
margin-left: 1em;
border: solid;
border-color: #0033cc;
background-color: #f6f6f6;
}
div button{
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
div input{
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
div{
list-style-type:square;
list-style-position: inside;
margin-left: 0.25em;
margin-bottom: 5em;
}
section {
padding: 1em 2em;
color: white;
background-color: #0000cc;
}
.editor {
font-weight: normal;
}
div contenteditable{
margin-bottom: 10em;
}
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<head>
<title>Outliner</title>
<link href="style.css" rel="stylesheet" title="Style">
<div>
<button id="b" onclick="bold()"> B </button>
<button onclick="underline()"> U </button>
<button onclick="italic()"> I </button>
<input type="button" onclick="highlighSelectedText()" value="Highlight"/>
<div id="text" class="editor" contenteditable="true" draggable="true"></div>
</div>
<section>
<input id="saveAs"></input>
<button onclick="saveTextFile()">Download</button>
<input type="file" id="load"/>
<button onclick="loadFile()">Load</button>
</section>
<section>
<button class="btn btn-primary" onclick="saveChanges()">Save Text</button>
<button class="btn btn-warning" onclick="clearStorage()">Reset</button>
</section>
</head>
<script type= "text/javascript" src='setting.js'></script>
</body>
First off we will use a CSS variable. Lets declare a value at :root
:root {
--font-color: #000;
}
Now we will use that value to style the font color of our P tags.
p {
color: var(--font-color);
}
Now when somebody clicks one of the color names, we want to change the value of --font-color. (Notice we are using the data- attribute model to store the color we want to change too).
document.documentElement.style.setProperty('--font-color', target.dataset.color);
And presto we can now change color easily. This works for other values also.
Here is a great article
document.addEventListener('click', ({ target }) => {
if(target.matches('p')) {
document.documentElement.style.setProperty('--font-color', target.dataset.color);
}
});
:root {
--font-color: #000;
}
p {
width: 30%;
border: 2px solid #00000030;
border-radius: 7px;
margin: 0.25rem;
padding: 0.25rem;
color: var(--font-color);
}
<h2>Click a color</h2>
<p data-color="#f00">Red</p>
<p data-color="#0f0">Green</p>
<p data-color="#00f">Blue</p>
<p data-color="#000">Reset</p>
You can manipulate the style variable:
<div id="text">
Choose a color
</div>
<input id="color" type="color">
<button onclick="document.getElementById('text').style.color = document.getElementById('color').value;">Change Color</button>
I have two buttons. When one is clicked, I want it to turn from gray to black and stay black unless the page is refreshed or the other button is clicked. If the other button is clicked, I would like it to turn black and for the first one to go back to gray. I assume JS is the best way for this, but I'm not sure how to do it.
Here is some of my code below:
HTML:
<a id="button"></a>
<a id="button"></a>
CSS:
#button {
display:inline-block;
height:10px;
width:10px;
border-radius:10px;
background-color:gray;
}
Many thanks in advance.
ID names should not be reused, change them to a class name instead, but they will still need an unique ID name each for us to apply Javascript logic to them.
html:
<a id="button1" class="button"></a>
<a id="button2" class="button"></a>
css:
.button
{
display:inline-block;
height:10px;
width:10px;
border-radius:10px;
}
Javascript:
document.getElementById("button1").style.backgroundColor ="gray";
document.getElementById("button2").style.backgroundColor ="gray";
document.getElementById("button1").onclick = function(){
this.style.backgroundColor ="black";
document.getElementById("button2").style.backgroundColor ="gray";
};
document.getElementById("button2").onclick = function(){
this.style.backgroundColor ="black";
document.getElementById("button1").style.backgroundColor ="gray";
};
Here's an example I whipped up with no JavaScript - instead I'm using two radio buttons that are styled depending on which one is "checked".
http://codepen.io/capitalq/pen/gLWLMK
.button {
-webkit-appearance: none;
appearance: none;
border: 0;
background: gray;
height: 50px;
width: 50px;
margin: 10px;
outline: none;
display: inline-block;
border-radius: 50%;
}
.button:checked {
background: black;
}
<input type="radio" class="button" name="buttons" id="button1" />
<input type="radio" class="button" name="buttons" id="button2" />
Use the jquery addClass function to add a class with a set background.
The class will remain until there is a page load.
CSS Only aproach is :active, but it will not work on buttons, because the active property fades away once you release the click button. Maybe using an tag disguised as button may work, but will fade away once it losses the active state.
With jQuery you can do it quite easily.
$('#buttons .item').on("click",function(){
$("#buttons .item.active").removeClass('active');
$(this).addClass("active");
});
button{
color: white;
}
.item{
background-color: gray;
}
.active{
background-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="buttons">
<button class="item">Button 1</button>
<button class="item">Button 2</button>
<button class="item">Button 3</button>
</div>
<style media="screen">
#buttonA, #buttonB {
display: inline-block;
height: 10px;
width: 10px;
border-radius: 10px;
background-color: gray;
}
</style>
<a id="buttonA"></a>
<a id="buttonB"></a>
<script type="text/javascript">
var buttonA = document.querySelector('#buttonA');
var buttonB = document.querySelector('#buttonB');
var changeColour = function (e) {
if (e.target === buttonA) {
buttonA.style.backgroundColor = 'black';
buttonB.style.backgroundColor = 'gray';
}
if (e.target === buttonB) {
buttonB.style.backgroundColor = 'black';
buttonA.style.backgroundColor = 'gray';
}
};
buttonA.addEventListener('click', changeColour, false);
buttonB.addEventListener('click', changeColour, false);
</script>
There is an HTML button element. So if you want to mark up a button on your page, you really ought to use:
<button type="button"></button>
Here is an approach using <button> and classList in javascript:
var buttons = document.getElementsByTagName('button');
function paintItBlack() {
for (var i = 0; i < buttons.length; i++) {
buttons[i].classList.remove('clicked');
}
this.classList.add('clicked');
}
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click',paintItBlack,false);
}
.clicked {
color: rgb(255,255,255);
background-color: rgb(0,0,0);
}
<button type="button">Button A</button>
<button type="button">Button B</button>
JavaScript is unnecessary at this time. Use this code in your .css file or in the "style" tag on the html file.. It will be black when the mouse is over it and after you click.
a:hover
{
background-color:black;
}
a:target
{
background-color:black;
}
i have a bunch of buttons with the id btn1, btn2 , btn3 etc. and i want to change the background when one button is clicked, for example if btn1 is pressed it gets black but when btn2 is pressed that gets black and btn1 goes back to its original state.
body {
background-color: #fff;
font-size: 62.5%;
}
#background-buttons { text-align: right; }
#background-buttons button {
background-color: #222;
font-family: Roboto Condensed;
color: #fff;
padding: 10px;
outline: none;
border: none;
width: 50px;
height: 50px;
border-radius: 50px;
}
#background-buttons #activated { background-color: #000; }
#background-buttons button:hover { background-color: #555; }
#background-buttons button:active { background-color: #333; }
<div id="background-buttons">
<button id="btn1" onclick="change()">1</button>
<button id="btn2" onclick="change()">2</button>
<button id="btn3" onclick="change()">3</button>
<button id="btn4" onclick="change()">4</button>
<button id="btn5" onclick="change()">5</button>
<button id="btn6" onclick="change()">6</button>
<button id="btn7" onclick="change()">7</button>
<button id="btn8" onclick="change()">8</button>
<button id="btn9" onclick="change()">9</button>
<button id="btn10" onclick="change()">10</button>
</div>
This code on JSFiddle
When a button is clicked loop through all buttons, set their backgroundColor to #222 and set the backgroundColor of the one that was clicked to something else.
Also, in the markup when you call the function change(), pass a parameter this,i.e, change(this).
Updated Fiddle
// el is the button that was clicked
function change(el) {
var all = document.getElementsByTagName('button');
// loop through all buttons
for (i = 0; i < all.length; i++) {
// if the current button is the one that was clicked change its color to 'plum', else '#222'
all[i].style.backgroundColor = all[i] == el ? 'plum' : '#222'
}
}
body {
background-color: #fff;
font-size: 62.5%;
}
#background-buttons {
text-align: right;
}
#background-buttons button {
background-color: #222;
font-family: Roboto Condensed;
color: #fff;
padding: 10px;
outline: none;
border: none;
width: 50px;
height: 50px;
border-radius: 50px;
}
#background-buttons button:hover {
background-color: #555 !important;
}
<div id="background-buttons">
<button id="btn1" onclick="change(this)">1</button>
<button id="btn2" onclick="change(this)">2</button>
<button id="btn3" onclick="change(this)">3</button>
<button id="btn4" onclick="change(this)">4</button>
<button id="btn5" onclick="change(this)">5</button>
<button id="btn6" onclick="change(this)">6</button>
<button id="btn7" onclick="change(this)">7</button>
<button id="btn8" onclick="change(this)">8</button>
<button id="btn9" onclick="change(this)">9</button>
<button id="btn10" onclick="change(this)">10</button>
</div>
Create a CSS class to style the selected button appropriately:
.selectedButton {
background-color: black;
}
Create some library functions to add and remove a class:
var util = {dom:{}};
util.dom.hasClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
return el && re.test(el.className);
}
util.dom.addClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
if (!util.dom.hasClassName(el, cName)) {
el.className = util.trim(el.className + ' ' + cName);
}
}
util.dom.removeClassName = function(el, cName) {
if (typeof el == 'string') el = document.getElementById(el);
if (util.dom.hasClassName(el, cName)) {
var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
el.className = util.trim(el.className.replace(re, ''));
}
}
/* Remove leading and trailing whitespace and reduce
** multiple intermediate whitespaces to a single space
*/
util.trim = function(s) {
return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
}
Change the listeners so they passes a reference to the clicked button:
<button id="btn1" onclick="change(this)">1</button>
Now when a button is clicked you can do:
function change(target) {
var el = document.querySelector('button.selectedButton');
if (el) util.dom.removeClassName(el, 'selectedButton');
util.dom.addClassName(target, 'selectedButton');
}
It would be better to put a single listener on a parent element and use the related event's target property to find the button that was clicked. Also, you can remember the last button that the class was added to so you don't have to search for it next time. But that won't work if you are setting a selected button at the server.