I have this script but need to have the class to be changed to "go" or "stop". currently I can turn both to change to the class but it should change to one or the other
Code
var form = document.querySelector("form");
form.addEventListener("click", function(event) {
event.preventDefault();
const classId = event.target.id;
if (classId == "go") {
event.target.className = "go";
} else if (classId == "stop") {
event.target.className = "stop";
}
});
.go {
background: green;
color: white;
}
.stop {
background: red;
color: white;
}
<form action="">
<button id="go">GO!</button>
<button id="stop">STOP!</button>
</form>
You're adding the class to the clicked button, but never removing the class from the other button.
var form = document.querySelector("form");
const goButton = document.querySelector("#go");
const stopButton = document.querySelector("#stop");
form.addEventListener("click", function(event) {
event.preventDefault();
if (event.target == goButton) {
goButton.classList.add("go");
stopButton.classList.remove("stop");
} else if (event.target == stopButton) {
stopButton.classList.add("stop");
goButton.classList.remove("go");
}
});
.go {
background: green;
color: white;
}
.stop {
background: red;
color: white;
}
<form action="">
<button id="go">GO!</button>
<button id="stop">STOP!</button>
</form>
Related
I have to toggle classes of buttons and parent element (cards)
let btns = document.querySelectorAll('.btn-primary');
btns.forEach(btn => {
btn.addEventListener('click', function(e){
e.target.parentElement.classList.toggle('red');
e.target.classList.toggle('green');
});
});
But, actually, the card and button does not change the class at the same time. Card gets red color but button gets green after I click another button.
You can extend click function a bit and decide if all buttons should also contain green class
let btns = document.querySelectorAll('.btn-primary');
btns.forEach(btn => {
btn.addEventListener('click', function(e) {
const parentElement = e.target.parentElement;
const element = e.target;
for (let button of document.querySelectorAll('.btn-primary')) {
if(button === element){
continue
}
if (button.classList.contains('green')) {
button.classList.toggle('green');
}
}
element.classList.toggle('green');
if([...document.querySelectorAll('.btn-primary')].some(element => element.classList.contains('green'))) {
parentElement.classList.add('red');
}
else {
parentElement.classList.remove('red');
}
});
});
.parent {
padding: 1rem;
border: 1px solid black;
}
.parent.red {
border-color: red;
}
.green {
color: green;
}
.red {
color: red;
}
<div class="parent">
<button class="btn-primary">Test</button>
<button class="btn-primary">Test</button>
</div>
This jQuery toggle() function is working great. What is good practice for doing the same in vanilla javascript (ES6 preferred)?
$("#sign_up_btn").click(function(e) {
$(signUpForm).toggle("hide");
$(loginForm).toggle("hide");
});
$("#login_btn").click(function(e) {
$(signUpForm).toggle("hide");
$(loginForm).toggle("hide");
});
Native Toggle
Class can be toggled natively via Element.classList.toggle:
const button = document.querySelector('#sign_up_btn');
button.addEventListener('click', e => {
document.querySelector('.content').classList.toggle('hide')
})
.hide {
display: none;
}
<button id="sign_up_btn">toggle</button>
<div class="content">Toggle this content</div>
You can do something like this:
Note: the CSS is just so we can test here.
document.getElementById('sign_up_btn').addEventListener('click', () => {
var signUpForm = document.getElementById('signUpForm');
var loginForm = document.getElementById('loginForm');
if(window.getComputedStyle(signUpForm).display === "block") {
signUpForm.style.display = "none";
loginForm.style.display = "block";
} else {
signUpForm.style.display = "block";
loginForm.style.display = "none";
}
});
#signUpForm {
position: relative;
float: left;
background-color: #09f;
width: 100px;
height: 100px;
display: block;
margin-right: 20px;
}
#loginForm {
position: relative;
float: left;
background-color: #f00;
width: 100px;
height: 100px;
display: none;
}
#sign_up_btn {
position: relative;
float: left;
margin-right: 20px;
}
<input type="button" id="sign_up_btn" value="Sign up" />
<div id="signUpForm">Sign up form</div>
<div id="loginForm">Log in form</div>
You can do this way.
var show = function (elem) {
elem.style.display = 'block';
};
var hide = function (elem) {
elem.style.display = 'none';
};
var toggle = function (elem) {
// If the element is visible, hide it
if (window.getComputedStyle(elem).display === 'block') {
hide(elem);
return;
}
// Otherwise, show it
show(elem);
};
// Listen for click events
document.addEventListener('click', function (event) {
// Make sure clicked element is our toggle
if (!event.target.classList.contains('toggle')) return;
// Prevent default link behavior
event.preventDefault();
// Get the content
var content = document.querySelector(event.target.hash);
if (!content) return;
// Toggle the content
toggle(content);
}, false);
<p>
<a class="toggle" href="#example">Toggle Div</a>
</p>
<div class="toggle-content" id="example">
Here's some text we want to toggle visibility of. Let's do it!
</div>
If signUpForm and loginForm are ids then you can try the following:
document.getElementById('sign_up_btn').addEventListener('click', function(){
elToggle();
});
document.getElementById('login_btn').addEventListener('click', function(){
elToggle();
});
function elToggle(){
var s = document.getElementById('signUpForm');
if (s.style.display == "none") {
s.style.display = "block";
} else {
s.style.display = "none";
}
var l = document.getElementById('loginForm');
if (l.style.display == "none") {
l.style.display = "block";
} else {
l.style.display = "none";
}
}
how can you disable to enter key to click a button. So when a button is focused, and the enter key pressed you wont click the button.
I made a Aim Trainer code, but there is a cheat: you can press the enter button to click instead of clicking with your mouse (or finger on mobile).
You can see what I mean here https://aimtrainer.netlify.com/clickbased.html
If you click the enter button there should happen nothing, but now you will trigger some sort of click event.
I tried this: but that wouldnt work
$('html').bind('keypress', function(e){
if(e.keyCode == 13)
{
return false;
}
});
Did you tried with e.preventDefault()?
$(document).on('keypress',function(e) {
if(e.which == 13) {
e.preventDefault()
}
});
You need preventDefault() and blur
Other good ideas: tabindex="-1" type="button"
let score = 0;
const addScore = function(val) {
score += val;
$("#score").html('score: ' + score);
}
const newRandomPosition = function() {
$("#button").css({
'left': ranNum(90) + 'vw',
'top': ranNum(90) + 'vh',
'opacity': 1
})
}
const ranNum = function(max) {
return Math.random() * max
}
$(function() {
$(document).on('keypress', function(e) {
if (e.target && e.target.id === "button" && e.which == 13) {
e.preventDefault()
}
});
$("#button")
.on("click", function(e) {
e.preventDefault();
// openFullscreen()
$(this).css("opacity", 0)
addScore(100)
newRandomPosition()
})
.on("focus", function() {
this.blur()
})
});
.button {
position: relative;
background-color: #FB6107;
border: none;
color: white;
padding: 20px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button tabindex="-1" type="button" id="button" class="button button5"></button>
<h1 id="score" class="scoreText">Score: 0</h1>
Set tabindex as -1 to avoid focus using tab key
<button id="button" class="button button5" onclick="hidebtn(this)" tabindex="-1"></button>
Manually focusout the button using blur()
function newRandomPostion(){
$("#button").css({left:ranNum(90)+'vw',top:ranNum(90)+'vh'});
$("#button").css('opacity', 1);
$("#button").blur();
}
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 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.