How to focus one button by default? - javascript

I'm having trouble with 2 buttons that each toggles different "div" elements. I want to focus "button 1" by default. How do I do that? Autofocus is not working. Here's the HTML code
<div class="filter">
<button class="filter-btn active" data-target="#block-1" autofocus>1</button>
<button class="filter-btn" data-target="#block-2">2</button>
</div>
Here's the JS code
let $blocks = $(".block-card");
$(".filter-btn").on("click", (e) => {
let $btn = $(e.target).addClass("active");
$btn.siblings().removeClass("active");
let selector = $btn.data("target");
$blocks.removeClass("active").filter(selector).addClass("active");
});

If autofocus is not working due to browser behavior or styling of other elements, you can still use Javascript to set focus.
Example:
document.querySelector(".filter-btn.active").focus({focusVisible: true});
{focusVisible: true} is optional here and it forces browser to make the focus visible.
There is a jQuery equivalent, but it seems that it does not take the optional config.
Example:
$(".filter-btn.active").focus();
Some CSS can be added to making testing easier.
Example:
button:focus {
color: crimson;
}
button:focus-visible {
outline: 2px solid crimson;
border-radius: 3px;
}
When running the following example, note that the first button should be focused.
Full example: (run it in live with button below)
document.querySelector(".filter-btn.active").focus({focusVisible: true});
button:focus{ color: crimson }
button:focus-visible {
outline: 2px solid crimson;
border-radius: 3px;
}
<div class="filter">
<button class="filter-btn active" data-target="#block-1">1</button>
<button class="filter-btn" data-target="#block-2">2</button>
</div>
Hope this will help!

Related

Can i trigger browser to focus element in JS

When i want to focus on some element I use focus() function which gave me :focus from css. The thing is that when i am focusing with TAB keyboard button i get that styling from css but also some blue styling around element which is probably some browser focus. Can I trigger that blue browser focus somehow too with js?
You can override this with the focus-visible CSS. Adding sample working example below for reference
button {
background: #F0FF00;
border: 1px solid #ccc;
font-size: 18px;
}
.clear-focus {
background: #00FF00;
}
.clear-focus:focus-visible, .clear-focus:focus {
outline: none;
box-shadow: 0px 1px 6px 0px #000;
}
<input placeholder="click to focus here manually" type="text" />
<p>Now press tab</p>
<button >Button without focus override / default focuss css</button>
<p>Now press tab agian</p>
<button class="clear-focus">Override focuss css / with custom css</button>
isible` CSS class. Sample code below:
we can use outline: none;,it hides outline
:not(.focusable){
outline: none;
}
<input placeholder="You can't focus me*" type="text" />
<p>press tab</p>
<button class="focusable">You can focus me</button>
<button >You can't focus me*</button>
<p>again repeat</p>
<input placeholder="You can't focus me*" type="text" />
<p>press tab</p>
<button class="focusable">You can focus me</button>
<button >You can't focus me*</button>
<p>*Focus is possible to all element,but border is only hided,as per OP's question</p>

Jquery selector - how can I ensure this works?

I have some buttons, labelled logo1 - logo15 respectively.
There is another button called 'lets-go' that fires a function based on these buttons being selected - when you click a logo the class 'active'.
When there is no logo selected, I would like this button to not be in the DOM - and be hidden. At the moment, the 'active' class for the button brings it's opacity to 1.
I have this jquery statement at the moment.
if (!$('.logo1, .logo2, .logo3, .logo4, .logo5, .logo6, .logo7, .logo8, .logo9, .logo10, .logo11, .logo12, .logo13, .logo14, .logo15').hasClass("active")) {
$('#lets-go').removeClass('active')};
But it's not working.
This is an example of one of my logoX buttons:
$('.logo15').on('click', function(e) {
$('.logo15').toggleClass("active");
$('#b15').toggleClass('alive');
$('#b15').toggleClass('zoomTarget');
$('#b15').toggleClass('dead');
$('#lets-go').addClass('active');
$('#popoutLetsGo').addClass('expand');
$('.instructions-arrow-2').addClass('hide')
});
On click, they apply the class of 'active' to let's go. But it doesn't remove it, ever. Just if you click any of the 15 buttons a new button appears, but if you deselect the button it's still there - and then the next screen is blank.
Can you see why it's not?
I am basically looking for: If none of these classes have the class of active, then make sure this id doesn't have the class of active either.
Consider the following:
if (!$("[class*='logo']").hasClass("active")) {
$('#lets-go').removeClass('active')};
}
This looks at the Class attribute for a item starting with "logo", so .logo3 would be one of those elements. But you may want to test each one.
$("[class*='logo']").each(function(i, el){
if(!$(el).hasClass("active")){
$('#lets-go').removeClass('active')};
}
});
See More:
https://api.jquery.com/attribute-contains-selector/
https://api.jquery.com/each/#each-function
You can also use simplified classes to help group selectors. Consider the following.
$(function() {
$(".logo").click(function() {
$(".logo.active").removeClass("active");
$(this).addClass("active");
$("#letsgo").prop("disabled", false);
});
$("#letsgo").prop("disabled", true);
})
.logo {
padding: .4em;
border: 1px solid black;
border-radius: 3px;
margin: 3px;
background: #eee;
color: #999;
}
.active {
background: white;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Make a Selection</p>
<div class="logo item-1">Logo 1</div>
<div class="logo item-2">Logo 2</div>
<div class="logo item-3">Logo 3</div>
<div class="logo item-4">Logo 4</div>
<div class="logo item-5">Logo 5</div>
<button id="letsgo">Let's Go!</button>

classList.toggle() for multiple divs

I have 3 divs as colors to choose from and 3 blank divs. I want to let the user be able to:
(1) click a colored div and then a blank div, then the blank div is colored as the color the user choose. And the code seems to work.
(2) I want the user to be able to click the colored blank div again and it becomes white. And the code seems to work.
The problem is, if the blank div is colored and the user choose another color and click the colored blank div again, a newer color class will be added to the div, and things become unpredictable. You can open the console and track the messy change of the class of the blank div.
How can I solve this problem? I only want the blank divs to toggle between two classes.
var chosenColor;
function pickColor(arg){
chosenColor=arg.id;
}
function draw(id){
document.getElementById(id).classList.toggle("white");
document.getElementById(id).classList.toggle(chosenColor);
}
.box{
width: 100px;
height: 100px;
border: 1px solid black;
display: inline-block;
}
.red{background: red}
.blue{background: blue;}
.yellow{background: yellow;}
.white{background: white;}
<html>
<body>
<div class="box red" id="red" onclick="pickColor(this)">1</div>
<div class="box blue" id="blue" onclick="pickColor(this)">2</div>
<div class="box yellow" id="yellow" onclick="pickColor(this)">3</div>
<br><br>
<div class="box white" id="4" onclick="draw(4)">4</div>
<div class="box white" id="5" onclick="draw(5)">5</div>
<div class="box white" id="6" onclick="draw(6)">6</div>
</body>
</html>
Instead of using classes and running into the issue of assigning multiple nested classes or having to use complicated white logic...
I'd use data-* attribute:
var chosenColor;
function pick(el) {
chosenColor = el.dataset.color;
}
function draw(el) {
el.dataset.color = el.dataset.color ? "" : chosenColor;
}
body { background: #eee; }
.box {
width: 100px;
height: 100px;
border: 1px solid black;
display: inline-block;
background: white; /* BY DEFAULT !!! */
}
[data-color=red] { background: red; }
[data-color=blue] { background: blue; }
[data-color=yellow] { background: yellow; }
<div class="box" onclick="pick(this)" data-color="red">1</div>
<div class="box" onclick="pick(this)" data-color="blue">2</div>
<div class="box" onclick="pick(this)" data-color="yellow">3</div>
<br><br>
<div class="box" onclick="draw(this)">4</div>
<div class="box" onclick="draw(this)">5</div>
<div class="box" onclick="draw(this)">6</div>
What the ternary el.dataset.color = el.dataset.color ? "" : chosenColor; does is:
if the element has already any data-color set data-color to "" (nothing)
otherwise set data-color to the preselected chosenColor
Check to see if the element's classname is white. If not, set its class name to white - else, set it to the chosen color. You can put the boxes in a container and use .container > div selector, removing the need to give the boxes the .box class. Also, in a listener, this will refer to the clicked element - there's no need to use getElementById when you already have a reference to the element.
var chosenColor;
function pickColor(arg) {
chosenColor = arg.id;
}
function draw(element, id) {
if (element.className !== 'white') element.className = 'white';
else element.className = chosenColor;
}
.container > div {
width: 100px;
height: 100px;
border: 1px solid black;
display: inline-block;
}
.red {
background: red
}
.blue {
background: blue;
}
.yellow {
background: yellow;
}
.white {
background: white;
}
<div class="container">
<div class="red" id="red" onclick="pickColor(this)">1</div>
<div class="blue" id="blue" onclick="pickColor(this)">2</div>
<div class="yellow" id="yellow" onclick="pickColor(this)">3</div>
<br><br>
<div class="white" id="4" onclick="draw(this, 4)">4</div>
<div class="white" id="5" onclick="draw(this, 5)">5</div>
<div class="white" id="6" onclick="draw(this, 6)">6</div>
</div>
Answer
See - https://codepen.io/stephanieschellin/pen/xyYxrj/ (commented code)
or ...
var activeColor
function setPickerColor(event) {
activeColor = event.target.dataset.boxColorIs
}
function setThisBoxColor(event) {
let element = event.target
let the_existing_color_of_this_box = element.dataset.boxColorIs
if (the_existing_color_of_this_box == activeColor) {
delete element.dataset.boxColorIs
} else {
element.dataset.boxColorIs = activeColor
}
}
.box {
width: 100px;
height: 100px;
border: 1px solid black;
display: inline-block;
background: white;
}
[data-box-color-is="red"] {
background: red
}
[data-box-color-is="blue"] {
background: blue;
}
[data-box-color-is="yellow"] {
background: yellow;
}
<html>
<body>
<div id="box-1" class="box" data-box-color-is="red" onclick="setPickerColor(event)">1</div>
<div id="box-2" class="box" data-box-color-is="blue" onclick="setPickerColor(event)">2</div>
<div id="box-3" class="box" data-box-color-is="yellow" onclick="setPickerColor(event)">3</div>
<br>
<br>
<div id="box-4" class="box" onclick="setThisBoxColor(event)">4</div>
<div id="box-5" class="box" onclick="setThisBoxColor(event)">5</div>
<div id="box-6" class="box" onclick="setThisBoxColor(event)">6</div>
</body>
</html>
Using data- attributes you are able to decouple the JavaScript functional concerns form the CSS classes. This simplifies your logic but most importantly it allows folks styling your app to work independently from the folks adding JS functionality. This decoupling becomes really important when your team is using BEM or an OOCSS pattern.
Ideally instead of attaching styles to the data- attribute you would maintain the 'state' using data- and have another function that sets the classList based on the data- state. Allowing you to be 100% sure style changes you make will never effect JS functionality (QA will love you). But that's an evolution beyond this post.
With this setup we are not using the id's but I left them in because its an important best practice. Most likely this code would evolve into a component with listeners instead of inline onClick calls. JavaScript selectors should always be attached to id's or data- variables, never classes. Also, the id's should always be there for the QA team to utilize in their scripts. You risk some one changing a class name or removing it to adjust the styles and inadvertently breaking your JS listener.
I switched the arguments to pass the 'event' instead of the 'this' which is the element. Anyone using your JS event functions is going to expect the event object as the first parameter. You can pass 'this' as the second parameter if you like, but event.target will give you the same thing.
One other thing to note is the syntax change between declaring the data- variable and calling it from the JS.
HTML <div data-box-color-is="red">1</div>
JS event.target.dataset.boxColorIs
Regardless of how you format you data- attribute name it will always be parsed into camelCase when referencing it in JS ... data-box_color--IS would still become ... dataset.boxColorIs
Also as an evolution to your code you could remove the global JS var and store the value on the <body> or some other element on the page using data-. This will give you a single source of truth or 'state' that multiple features/components can reference without cluttering the global space.
Further Reading
https://css-tricks.com/bem-101/
https://en.bem.info/
https://philipwalton.com/articles/side-effects-in-css/
https://csswizardry.com/2015/03/more-transparent-ui-code-with-namespaces/
https://philipwalton.com/articles/decoupling-html-css-and-javascript/

Remove class from <a> button after pressing another <a> button

I'm trying to create a site, on which you can download a file by pressing an button. The thing is, that I want people to click another button first to subscribe to a youtube channel and THEN to be able to download the file. So, I have to get rid of the disabled class on the download button after pressing the subscribe button. Here below is my code, what am I doing wrong?
EDIT: Tried all the answers now, none did work. I'm getting this error, what does that mean?
Uncaught ReferenceError: $ is not defined
at index.html:23
Line 23 is
$('#sub').on('click',function(event){
$('#sub').on('click',function()){
$('#dl').removeClass('disabled');
});
.disabled {opacity: 0.8; cursor: not-allowed;}
.size-3 {font-size: 16px;}
.btn {
font: 100%/1.1 "Quicksand", sans-serif;
background-color: rgba(0,0,0,0.3);
border: 2.2px solid #ecf0f1;
color: #ffffff;
padding: 12px 62px;
text-align: center;
text-decoration: none;
display: inline-block;
text-transform: none;
font-size: 20px;
margin: 3px 6.9px;
cursor: pointer;
transition-duration: 0.4s;
}
<a id="sub" href="#" class="btn size-3">Subscribe to ZERO</a>
<a id="dl" href="#" class="btn size-3 disabled">Download Exyther</a>
jsFiddle: https://jsfiddle.net/qrc3qm2e/
I have added extra code to check if the button shouldn't be clickable, if you need a jQuery answer please follow this link https://jsfiddle.net/qrc3qm2e/1/
Javascript
var subElement = document.getElementById("sub");
var dlElement = document.getElementById("dl");
subElement.onclick = function(event)
{
dlElement.classList.remove('disabled');
dlElement.removeAttribute('disabled');
};
dlElement.onclick = function(event)
{
if(dlElement.className.indexOf('disabled') > -1)
{
event.preventDefault();
return;
}
};
HTML
<a id="sub" href="#" target="blank" class="btn size-3">Subscribe to ZERO</a>
<a id="dl" href="#" target="blank" class="btn size-3 disabled" disabled="disabled">Download Exyther</a>
This makes your code an error: function()) << double close
correct JS
$('#sub').on('click',function(event){
event.preventDefault();
$('#dl').removeClass('disabled');
});
https://codepen.io/jacobweyer/pen/JNzgJE?editors=1111
Here's a codepen of the issue
$('#sub').on('click', function(event){
if (event.preventDefault) {
event.preventDefault();
}
$('#dl').removeClass('disabled');
});
You didn't close the function, but also you can add event into the function. This will pass the click event into your jquery.
With the click event you can actually prevent the page from jumping moving as well by preventing the default action on the a tag.
You can help by keeping your example really really simple. We don't need to know about your font for example. : )
You probably want to use a disabled property - or that AND style that a bit with CSS. here's how to do that. - if you want to use a link - then the download will be its default behaviour - so you shouldn't have to prevent it - but see #JacobW 's about that. You'd likely not want the URL in the markup - if you are really trying to dissuade them from getting the file until subscribing. If you can't switch out the button for the link - and see the concept, I'm sure you will at some later date. : ) Good Luck!
JavaScript - and disabled property
https://jsfiddle.net/sheriffderek/3t0pn6gv/
markup
<button class='one'>one</button>
<button class='two' disabled>two</button>
style
button:disabled {
opacity: .3;
}
script (not jQuery for #Canvas)
var signupButton = document.querySelector('button.one');
var downloadButton = document.querySelector('button.two');
signupButton.addEventListener('click', function() {
downloadButton.disabled = false;
});
with jQuery and CSS class - (not actually disabled... but looks so)
https://jsfiddle.net/sheriffderek/wyx1od9g/
markup
<button class='one'>one</button>
<button class='two disabled'>two</button>
style
.disabled{
opacity: .2;
}
script
$('button.one').on('click', function() {
$('button.two').removeClass('disabled');
});

How to use JavaScript to Alter CSS for Multiple Elements

I am trying to use JavaScript to change the background color of an element after being selected, and also to make sure that only one element at a time has the particular background color. Once the user selects on a different element I would like the previous element that was selected to be replaced by a different background color. Currently I am only able to toggle individual elements by selecting on EACH element. I need to be able to select on an element and apply the new background color, then have JavaScript change the background color of the previously active element to a different color (one less click).
What I am trying to do is very similar to modern navbars or list items where only one element at a time is “active” and has a background color that is different than the other elements in the same div, row, etc.
Notes about my work I am utilizing bootstrap and have no desire to use jQuery for this particular project.
CSS:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
h4 {
border: 1px solid black;
border-radius: 8px;
padding: 10px 2px 10px 2px;
margin: 20px 20px 0px 20px;
background-color: #F0F0F0;
border-color: #F8F8F8;
color: #505050;
cursor: pointer;
}
.active {
background-color: #99E6FF;
}
</style>
</head>
</html>
HTML:
<div id="pTwoRowOne">
<div class="row">
<div class="col-md-4 row row-centered">
<h4 id="techBio" class="test">Biology</h4>
</div>
<div class="col-md-4 row row-centered">
<h4 id="techCart" class="test">Cartography</h4>
</div>
<div class="col-md-4 row row-centered">
<h4 id="techChem" class="test">Chemistry</h4>
</div>
</div>
</div>
JavaScript:
document.getElementById("techBio").onclick=function() {
document.getElementById("techBio").classList.toggle('active');
}
document.getElementById("techCart").onclick=function() {
document.getElementById("techCart").classList.toggle('active');
}
document.getElementById("techChem").onclick=function() {
document.getElementById("techChem").classList.toggle('active');
}
An example can be seen here: http://jsbin.com/fugogarove/1/edit?html,css,js,output
If clarification is needed let me know.
Yup, pretty straightforward.
Assumptions
You're not trying to support IE8, since you're using classList
You're okay with housing your elements as variables as opposed to repeatedly querying the DOM.
Example
JSBin
Code
I rewrote your JavaScript to make it a little bit cleaner and to DRY it up a bit:
var techs = [].slice.call(document.querySelectorAll('#pTwoRowOne h4'));
function set_active(event) {
techs.forEach(function(tech){
if (event.target == tech) { return; }
tech.classList.remove('active');
});
event.target.classList.toggle('active');
}
techs.forEach(function(item) {
item.addEventListener('click', set_active);
});
Some explanation
[].slice.call(document.querySelectorAll('#pTwoRowOne h4')); – We're using this to change the output from a NodeList to an Array. This allows us to use forEach later. querySelectorAll returns a NodeList that contains all elements matching the CSS selector. You can probably replace that with a better CSS selector depending on your environment.
addEventListener is a much nicer way than the iterative add via onclick += to bind an event listener. It's also the recommended way (as far as I know) in ECMA5 and later.
By setting the element queries as variables, you'll be able to keep the reference in memory instead of polling the DOM every time to alter elements. That'll make your JavaScript marginally faster, and it's again just a nicer, cleaner version of the code which it produces.
updates
I reworked the JS to make more sense.
Assuming you only ever have one active element, you can find it using document.querySelector() - if you can have multiples you can use document.querySelectorAll() and iterate through them.
Simple case:
function activate(event) {
var active=document.querySelector('.active');
// activate the clicked element (even if it was already active)
event.target.classList.add('active');
// deactivate the previously-active element (even if it was the clicked one => toggle)
if (active) active.classList.remove('active');
}
document.getElementById("techBio").addEventListener("click",activate);
document.getElementById("techCart").addEventListener("click",activate);
document.getElementById("techChem").addEventListener("click",activate);
h4 {
border: 1px solid black;
border-radius: 8px;
padding: 10px 2px 10px 2px;
margin: 20px 20px 0px 20px;
background-color: #F0F0F0;
border-color: #F8F8F8;
color: #505050;
cursor: pointer;
}
.active {
background-color: #99E6FF;
}
<div id="pTwoRowOne">
<div class="row">
<div class="col-md-4 row row-centered">
<h4 id="techBio" class="test">Biology</h4>
</div>
<div class="col-md-4 row row-centered">
<h4 id="techCart" class="test">Cartography</h4>
</div>
<div class="col-md-4 row row-centered">
<h4 id="techChem" class="test">Chemistry</h4>
</div>
</div>
</div>
Another similar yet simpler way to do it: jsBin ;)
var H4 = document.getElementsByClassName("test"), act;
[].forEach.call(H4, function(el){
el.addEventListener("click", function(){
if(act) act.classList.remove("active");
return (this.classList.toggle("active"), act=this);
});
});
You can do something like this:
[].slice.call(document.querySelectorAll(".test")).forEach(function(element) {
element.addEventListener('click', function(event) {
if (activeElement = document.querySelector(".test.active")) {
activeElement.classList.remove("active");
};
event.target.classList.add('active');
});
});
Basically, first we remove the active class from the active element, then we add it to the target.
JSBin

Categories

Resources