Hide/Show div and then hide all div - javascript

I am trying to make a "meet the staff" section that has hidden bios that display on click. Right now the div displays as it should, but only disappears when the original button is clicked again. I am needing some additional javascript to hide any opened divs when a different (or same) button is clicked. I don't know enough javascript to know what to try in order to make this happen. Thanks in advance!
HTML
<div id="lastname" class="toggle-div" style="display: none;">
<div><p>bio</p>
</div>
</div>
<button class="bio-button" onclick="myBiof()">Click for Bio</button>
Javascript
<script>
function myBiof() {
var y = document.getElementById("lastname");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
</script>

You will need to add some attributes to your HTML to keep track of which item is active, what item a button controls and which ones should be hidden from screen readers. aria-controls aria-expanded and aria-hidden do just that. Once a button is clicked... if it is currently open, just close it (remove active) and toggle the appropriate attributes. If it is not open, close all of them (remove active), open the one you clicked on (add active) and toggle the appropriate attributes. Here is a simple example:
const buttons = document.querySelectorAll("button");
const people = document.querySelectorAll(".person");
const handleClick = (event) => {
const clickedBtn = event.target;
if (clickedBtn.getAttribute("aria-expanded") === "true") {
let personId = clickedBtn.getAttribute("aria-controls");
let person = document.getElementById(personId);
person.classList.remove("active");
person.setAttribute("aria-hidden", "true");
clickedBtn.setAttribute("aria-expanded", "false");
} else if (clickedBtn.getAttribute("aria-expanded") === "false") {
people.forEach(person => {
person.classList.remove("active")
person.setAttribute("aria-hidden", "true");
});
buttons.forEach(button => button.setAttribute("aria-expanded", "false"));
let personId = clickedBtn.getAttribute("aria-controls");
let person = document.getElementById(personId);
person.classList.add("active");
person.setAttribute("aria-hidden", "false");
clickedBtn.setAttribute("aria-expanded", "true");
}
}
buttons.forEach(button => button.addEventListener("click", handleClick));
button {
display: block;
background: transparent;
border: none;
border-bottom: 1px solid #000;
width: 100%;
height: 2rem;
}
.person-container {
width: 400px;
margin: 0 auto;
}
.person {
display: none;
border-left: 1px solid #000;
border-right: 1px solid #000;
border-bottom: 1px solid #000;
padding: 1rem;
}
.person h2 {
margin-top: 0px;
}
.person p {
margin-bottom: 0px;
}
.active {
display: block;
}
<div class="person-container">
<button aria-controls="person-one" aria-expanded="false">Show Person One</button>
<div id="person-one" aria-hidden="true" class="person">
<h2>Name One</h2>
<p>Person One Bio</p>
</div>
<button aria-controls="person-two" aria-expanded="false">Show Person Two</button>
<div id="person-two" aria-hidden="true" class="person">
<h2>Name Two</h2>
<p>Person Two Bio</p>
</div>
<button aria-controls="person-three" aria-expanded="false">Show Person Three</button>
<div id="person-three" aria-hidden="true" class="person">
<h2>Name Three</h2>
<p>Person Three Bio</p>
</div>
</div>

/*
Function to add all the events to the buttons.
Checking if divs are hidden or not with [data-hidden] attribute.
This HMTML attributes can be named however you want but starting
with data-
Note that this code will only work if every button
is placed in the HTML after the bio div
*/
function addEventsAndListenToThem() {
const buttons = document.querySelectorAll('.bio-button')
buttons.forEach(btn => {
btn.onclick = (e) => {
const target = e.target.previousElementSibling
// If element is hided, show it changing
// attribute data-hidden value to false
target.getAttribute('data-hidden') === 'true' ?
target.setAttribute('data-hidden', 'false') :
target.setAttribute('data-hidden', 'true')
}
})
const hide_or_show_all = document.querySelector('.bio-button-all')
// Var to check wether .bio-button-all
// has been pressed or not
var showing = false
hide_or_show_all.onclick = () => {
// Get al divs with data-hidden property
const all_bios = document.querySelectorAll('div[data-hidden]')
showing === false ? (
() => {
// Show all divs
all_bios.forEach(bio => bio.setAttribute('data-hidden', 'false'))
showing = true
}
)() :
(
// Hide all divs
() => {
all_bios.forEach(bio => bio.setAttribute('data-hidden', 'true'))
showing = false
}
)()
}
}
addEventsAndListenToThem()
/*
Display none only to [data-hidden="true"] elements
*/
[data-hidden="true"] {
display: none;
}
.bio-button,
.bio-button-all {
display: block;
margin: 10px 0px;
}
<div id="lastname" class="toggle-div" data-hidden='true'>
<div>
<p>First bio</p>
</div>
</div>
<button class="bio-button">Click for first Bio</button>
<div id="lastname" class="toggle-div" data-hidden='true'>
<div>
<p>Second bio</p>
</div>
</div>
<button class="bio-button">Click for second Bio</button>
<div id="lastname" class="toggle-div" data-hidden='true'>
<div>
<p>Third bio</p>
</div>
</div>
<button class="bio-button">Click for third Bio</button>
<button class="bio-button-all">Show/Hide all</button>

Related

changing the content of a div

I would like to change the content of a div. I have three divs:
<div
class="box1"
style="height: 200px; width: 200px; background-color: red"
>
A
</div>
<br />
<div
class="box2"
style="height: 200px; width: 200px; background-color: blue"
>
<label for="">tex</label>
<input type="text" />
</div>
<br />
<div
class="box3"
style="height: 200px; width: 200px; background-color: yellow"
>
C
</div>
when the page is ready the 2 and 3rd box displays none:
function hideElementBoxOnLoad() {
let box1 = document.querySelector(".box1");
let box2 = document.querySelector(".box2");
let box3 = document.querySelector(".box3");
box2.style.display = "none";
box3.style.display = "none";
}
$(document).ready(hideElementBoxOnLoad);
I want a click that toggles the content of box2 and box3 into box1 and then back to box1 content:
function changeContent() {
let chang = true;
let box1 = document.querySelector(".box1");
let box2 = document.querySelector(".box2");
let box3 = document.querySelector(".box3");
let box2Content = box2.textContent;
let box3Content = box3.textContent;
if (chang) {
box1.textContent = box2Content;
chang = !chang;
if ((box1.textContent === box2Content)) {
box1.textContent = box3Content;
}
}
}
let btn = document.getElementById("btn");
btn.addEventListener("click", changeContent);
So far it worked but it does not display the content of box2 only box3. what did i do wrong and what better way can i toggle with a boolean.
See below
Instead of trying to swap content between each div just use JS to go through the array of them and swap an active class between them;
var boxes = document.getElementsByClassName('box');
var change = document.getElementById('change');
var counter = 0;
change.addEventListener('click', function(){
boxes[counter].classList.remove('active');
boxes[counter].nextElementSibling.classList.add('active');
counter++;
if(counter === boxes.length) {
counter = 0;
boxes[0].classList.add('active');
}
});
.box {
display: none;
width: 100px;
height: 100px;
background-color: gray;
}
.box.active {
display:block
}
<div class="box active">A</div>
<div class="box">B</div>
<div class="box">C</div>
<button id="change">Change Content</button>
im not completely sure if i understood ur question.
but below u can see and even test with the snippet button.
the button now add what ever content in in the yellow box, and whats in the input field of the blue box into the red box. listing them downwards.
if you want to replace the content completely.
just change the logic to box1.innerHTML += spacer+box3.innerHTML+spacer+input.value
this is the most simple way to do it thats easy to understand just by reading the code i think.
hope this helps!
function changeContent() {
//the button
const btn = document.getElementById("btn");
//the boxes
const box1 = document.getElementById("box1");
const box2 = document.getElementById("box2");
const box3 = document.getElementById("box3");
//a spacer
const spacer = "<br>";
//the input field
const input = document.getElementById("input");
//logic
box1.innerHTML += spacer+box3.innerHTML+spacer+input.value
}
div{
border-radius: 5px;
text-align: center;
font-family: sans-serif;
}
#box1{
min-height: 200px;
width: 200px;
padding: 5px;
background-color: rgb(255, 73, 73);
}
#box2 {
height: 200px;
width: 200px;
padding: 5px;
background-color: rgb(0, 195, 255);
}
#box3 {
height: 200px;
width: 200px;
padding: 5px;
background-color: yellow;
}
button{
padding: 3px;
margin-top: 10px;
}
<div id="box1">
<p>contetnt A</p>
</div>
<br />
<div id="box2" >
<label for="">tex</label>
<input id="input" type="text" />
<button id="btn" onclick="changeContent()">click me</button>
</div>
<br />
<div id="box3">
contetnt C
</div>
List of bugs :-
You had declared the var chang locally instead of globally, which make it true whenever you runs the function.
You are directly writing value from one tag to another, which causing the data loss, when you run your function second time.
For example :- When you click the button first time, the data is swapped, but for the second click, the data first div is lost and cannot be brought back...
Solution :- Store the data in an array in document.ready event handler and extract data from the array to update you html tags.
function hideElementBoxOnLoad() {
let box1 = document.querySelector(".box1");
let box2 = document.querySelector(".box2");
let box3 = document.querySelector(".box3");
box2.style.display = "none";
box3.style.display = "none";
content = [box1.textContent, box2.textContent, box3.textContent];
let btn = document.getElementById("btn");
btn.addEventListener("click", changeContent);
}
var content = [];
window.onload = (hideElementBoxOnLoad);
var index = 0;
function changeContent() {
let chang = true;
let box1 = document.querySelector(".box1");
/* let box2 = document.querySelector(".box2");
let box3 = document.querySelector(".box3");
let box2Content = box2.textContent;
let box3Content = box3.textContent;
if (chang) {
box1.textContent = box2Content;
chang = !chang;
if ((box1.textContent === box2Content)) {
box1.textContent = box3Content;
}
}
*/
function cycle(n, x = 0, y = content.length - 1, a = 1) {
n += a;
if (n > y) return x;
if (n < x) return y;
return n;
}
index = cycle(index);
box1.textContent = content[index];
}
<div class="box1" style="height: 200px; width: 200px; background-color: red">
A
</div>
<br />
<div class="box2" style="height: 200px; width: 200px; background-color: blue">
<label for="">tex</label>
<input type="text" />
</div>
<br />
<div class="box3" style="height: 200px; width: 200px; background-color: yellow">
C
</div>
<button id="btn"> CLICK ME </button>
Explaination
Here I first stored the tags textContent in a array content, in the starting of the code.
Then, inside the button click handler, a simple cycle function to cycle on the values stored inside the content array.

How do I get the ViewButton to not copy the old note.value

//javascript, this is where I'm having the issue
const form = document.querySelector("#Form");
const note = document.querySelector("#Note");
const table = document.querySelector("#noteTable");
const count = 0;
form.addEventListener("submit", (e) => {
e.preventDefault();
if (note.value !== '') {
const btn = document.createElement("button");
btn.innerHTML = "View Details";
const row = table.insertRow();
const noteRow = row.insertCell();
const viewD = row.insertCell();
noteRow.innerHTML = note.value;
viewD.append(btn);
model.append(note.value);
note.value = "";
btn.addEventListener("click", () => {
model.classList.add("show");
});
const close = document.querySelector("#close");
close.addEventListener("click", () => {
model.classList.remove("show");
});
} else {
alert("Write a note!");
}
});
css button {
color: black;
background-color: green;
}
body {
background-color: rgb(182, 215, 227);
min-height: 100vh;
margin: 0;
}
.model-container {
background-color: rgba(245, 222, 179, 0.38);
position: fixed;
display: flex;
justify-content: center;
align-items: center;
top: 0;
left: 0;
height: 100vh;
width: 100vh;
opacity: 0;
pointer-events: none;
}
.model {
background-color: white;
}
.model-container.show {
pointer-events: auto;
opacity: 1;
}
.open:hover {
cursor: pointer;
color: white;
}
td {
display: block;
}
<h2>NOTE TAKER</h2>
<h6>Add A New Note:</h6>
<form id="Form" action="#">
<label class="ntag" for="note">Note:</label>
<input class="ntag" name="note" id="Note" type="text" placeholder="Write a note">
<button id="Add">Add Note</button>
</form>
<div class="theTable">
<table id="noteTable">
<tr id="Headers" class="headers">
<th></th>
</tr>
</table>
</div>
<div class="model-container" id="model">
<div class="model">
<button class="close" id="close">Close Me</button>
</div>
</div>
I'm not sure why but the notes repeat in the model-container, after you make another note the first one is still there with the second one right after it.
I thought that it could be the placement, so i put it in the btn function, but it duplicated as well; also sorry for how ugly this is, I'm just focused on the JavaScript
If you inspect the source after adding a few notes, you'll notice that it looks like this, assuming I added notes "one", "two" and "three":
It's putting it there because of this line of javascript:
model.append(note.value);
The .append() method doesn't wipe out anything in the <div id="model">, it just adds on to whatever is in there by dumping it after the button or dumping after any existing text.
To avoid erasing the "Close Me" button you'll probably want another div specifically for the text so that instead of using .append() you can just set the .textContent of the element each time. This would be destructive in a way that you wouldn't want to do this on the parent element, because it would wipe out the button. .append() is what is retaining the previous stuff when you click "View Detail."
<div class="model-container" id="model">
<div class="model">
<button class="close" id="close">Close Me</button>
</div>
<div id="txtDetails"><div>
</div>
So instead of using .append() just set the text of <div id="txtDetails"> to what you want it to say by setting the .textContent.
I also added a "data-text" attribute to the button on creation so it would be easier to fish out the text instead of navigating the parent elements and across elements.
Finally, on the click listener event I made it take whatever is stored in the "data-text" attribute and place that into <div id="txtDetails"> so that each "View Details" click would only show what is relevant for that particular note. This method is destructive in that it wipes out and replaces anything in <div id="txtDetails"> with each click but leaves the button in the modal alone.
const form = document.querySelector("#Form");
const note = document.querySelector("#Note");
const table = document.querySelector("#noteTable");
const count = 0;
form.addEventListener("submit", (e) => {
e.preventDefault();
if(note.value !== '')
{
const btn = document.createElement("button");
btn.innerHTML = "View Details";
btn.setAttribute('data-text', note.value);
const row = table.insertRow();
const noteRow = row.insertCell();
const viewD = row.insertCell();
noteRow.innerHTML = note.value;
viewD.append(btn);
note.value = "";
btn.addEventListener("click", () => {
document.getElementById('txtDetails').textContent = btn.getAttribute('data-text');
model.classList.add("show");
});
const close = document.querySelector("#close");
close.addEventListener("click", () => {
model.classList.remove("show");
});
}
else{
alert("Write a note!");
}
});
https://jsfiddle.net/tnqp8L0x/

Two Column Accordion with Separate Full Width Divs

The intension is to have a two column accordion, without limiting the "expand" field to the left or right column. The catch is that there will be multiple on one page. This is already created, but only button 1 is working. With the way my JS is going, it will get very very repetitive - I am looking for assistance with re-writing the JS to be multiple click friendly. Fiddle: https://codepen.io/ttattini/pen/abLzaaY
EDIT: It would also be perfect if one dropdown would close as the next is opened
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="row">
<div id="column">
<button id="button">I am Button #1</button>
<button id="button">I am Button #3</button>
</div>
<div id="column">
<button id="button">I am Button #2</button>
<button id="button">I am Button #4</button>
</div>
</div>
<div id="hidden">
<p id="content"> So here I am #1</p>
</div>
<div id="hidden">
<p id="content"> So here I am #2</p>
</div>
<div id="hidden">
<p id="content"> So here I am #3</p>
</div>
<div id="hidden">
<p id="content"> So here I am #4</p>
</div>
CSS
#hidden {
background: #ccc;
margin-top: 2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
#button {
padding: 10px;
margin-top: 5px;
width:50%;
margin-left: 10%;
cursor: pointer;
}
#row {
display: flex;
}
#column {
flex: 50%;
}
JS
$(function() {
var b = $("#button");
var w = $("#hidden");
var l = $("#content");
b.click(function() {
if (w.hasClass('open')) {
w.removeClass('open');
w.height(0);
} else {
w.addClass('open');
w.height(l.outerHeight(true));
}
});
});
The biggest issue is that you're using IDs when you should be using classes. IDs must be unique to each element in a page. When you repeat an ID, JS will only target the first element using that ID. That's why only the first one is working.
The second issue is that, because of the way the script is written, it will only target a single element. What you need to do is get all the elements you want to target by something like their class name and then loop through them, applying the event listener to each one and its appropriate children.
EDIT: Here is an example from some code I wrote for a page with multiple accordions a few weeks ago in vanilla JS
//Below I establish a counting variable and find all the accordions on the page
const acc = document.getElementsByClassName( 'accordion' );
let i;
//Looping through each accordion
for ( i = 1; i <= acc.length; i++ ) {
//Identify target for the event listener. In this case, a heading for each accordion, which I've numbered e.g. "title-1"
const title = 'title-' + i;
const label = document.getElementById( title );
//Identify target content, in this case a list that has a unique ID e.g. "list-1"
const listNum = 'list-' + i;
const list = document.getElementById( listNum );
//Add event listener to heading that toggles the active classes
label.addEventListener( 'click', function() {
label.classList.toggle( 'accordion--active' );
});
}
Of course, there's more than one way to skin a cat, but this is a working example.
I have tracked the clicked event of each button and showed the corresponding hidden content with the use of data- attribute.
I have used vanilla JavaScipt instead of jQuery.
const buttons = document.querySelectorAll('.button');
const hiddens = document.querySelectorAll('.hidden');
buttons.forEach((btn) => {
btn.addEventListener('click', btnClicked)
function btnClicked(e) {
hiddens.forEach((hidden) => {
if(e.target.dataset.btn == hidden.dataset.content) {
hidden.classList.toggle('height')
} else {
hidden.classList.remove('height')
}
})
}
})
.hidden {
background: #ccc;
margin-top: 2%;
padding-left:2%;
overflow: hidden;
transition: height 200ms;
height: 0; /* <-- set this */
}
.hidden.height {
height: 50px;
}
.button {
padding: 10px;
color: white;
background-color: #2da6b5;
border: none;
margin-top: 5px;
width:90%;
margin-left: 5%;
cursor: pointer;
}
.button:hover {
filter: brightness(.9);
}
#row {
display: flex;
}
.column {
flex: 50%;
}
<div id="row">
<div class="column">
<button class="button" data-btn="one">I am Button #1</button>
<button class="button" data-btn="three">I am Button #3</button>
</div>
<div class="column">
<button class="button" data-btn="two">I am Button #2</button>
<button class="button" data-btn="four">I am Button #4</button>
</div>
</div>
<div class="hidden" data-content="one">
<p class="content"> So here I am #1</p>
</div>
<div class="hidden" data-content="two">
<p class="content"> So here I am #2</p>
</div>
<div class="hidden" data-content="three">
<p class="content"> So here I am #3</p>
</div>
<div class="hidden" data-content="four">
<p class="content"> So here I am #4</p>
</div>
Also, please do not use the same ID at multiple elements.

How to separete div blocks with the same class but diffent features

Good day!
I have a pop-up section. There are 2 div blocks in it with identical structure. The idea is to have 2 buttons (one is to edit a profile the other is to create a new card with some info) that will call this pop-up, but i need to track which one is called. The popup itself has a darker background compare to main page and a form. I have thought of a modifier popup__container_type_(edit/create) that has a display: none command so when i toggle it it the popup would appear with the right form. Most likely my logic was mistaken. I dont know how to distiguish them (div blocks) correctly.
Another problem is that closebutton seems to work for one form only.
Any help would be great!
HTML:
<section class="popup">
<div class="popup__container popup__container_type_edit">
<button type="button" class="popup__cancelbutton"></button>
<form class="popup-form" name="form">
<h2 class="popup-form__title">Header 1</h2>
<input type="text" class="popup-form__input popup-form__input_type_name" name="name">
<input type="text" class="popup-form__input popup-form__input_type_job" name="job">
<button type="submit" class="popup-form__savebutton">Save</button>
</form>
</div>
<div class="popup__container popup__container_type_create">
<button type="button" class="popup__cancelbutton"></button>
<form class="popup-form" name="form">
<h2 class="popup-form__title">Header 2</h2>
<input type="text" class="popup-form__input popup-form__input_type_place" placeholder="Name of the place" name="place">
<input type="text" class="popup-form__input popup-form__input_type_imagelink" placeholder="Image link" name="imagelink">
<button type="submit" class="popup-form__savebutton">Create</button>
</form>
</div>
</section>
JS:
let popUpSection = document.querySelector(`.popup`);
let cancelButton = popUpSection.querySelector(`.popup__cancelbutton`);
let popUpContainer = popUpSection.querySelector(`.popup__container`);
let formElement = popUpSection.querySelector(`.popup-form`);
let newInputName = popUpSection.querySelector(`.popup-form__input_type_name`);
let newInputJob = popUpSection.querySelector(`.popup-form__input_type_job`);
let inputName = document.querySelector(`.profile-info__title`);
let inputJob = document.querySelector(`.profile-info__text`);
let editButton = document.querySelector(`.profile-info__editbutton`);
let createButton = document.querySelector(`.profile__addbutton`);
//Open / close popup section
let formTogglePopUp = () => {
if (!popUpSection.classList.contains(`popup_acitve`)){
//Autofill
newInputName.value = inputName.textContent;
newInputJob.value = inputJob.textContent;
}
popUpSection.classList.toggle(`popup_active`);
}
//Save input changes
function popUpFormSaved (event) {
event.preventDefault();
inputName.textContent = newInputName.value;
inputJob.textContent = newInputJob.value;
formTogglePopUp();
}
formElement.addEventListener('submit', popUpFormSaved);
cancelButton.addEventListener('click', formTogglePopUp);
editButton.addEventListener('click', formTogglePopUp);
createButton.addEventListener(`click`, formTogglePopUp);
CSS:
.popup__container
{
display: block; *by default*
}
.popup__container_type_(edit/create)
{
display: none;
}
.popup
{
display:none;
}
.popup__active
{
display: flex;
}
You can do it with js, set ids and use them instead of class, it's more easy.
function popUpEdit() {
document.getElementById("popUp").style.display = "block";
document.getElementById("popUpEdit").style.display = "block";
}
function popUpCreate() {
document.getElementById("popUp").style.display = "block";
document.getElementById("popUpCreate").style.display = "block";
}
#popUp, #popUpEdit, #popUpCreate {
display: none;
}
<div class="smt">
Hello
<button onclick="popUpEdit()">Edit</button>
</div>
<div class="smt">Hello
<button onclick="popUpCreate()">Create</button>
</div>
<section id="popUp">
<div>popUp</div>
<div id="popUpEdit">Edit-popup</div>
<div id="popUpCreate">Create-popup</div>
</section>
Generaly, I do that this way:
const SectionPopUp = document.querySelector('section.popup')
function show(elm)
{
SectionPopUp.classList.toggle('Create','Create'===elm)
SectionPopUp.classList.toggle('Edit','Edit'===elm)
}
section.popup,
section.popup.Edit > div:not(.popup__container_type_edit),
section.popup.Create > div:not(.popup__container_type_create) {
display:none;
}
section.popup.Edit,
section.popup.Create {
display:block;
}
/* cosmetic part, just for testing here */
section.popup > div {
border : 1px solid aqua;
padding : .6em;
margin : 1em;
width : 15em;
}
div.popup__container_type_create {
border-color: orange !important;
}
<button onclick="show('Edit')"> show Edit </button>
<button onclick="show('Create')"> show Create </button>
<button onclick="show('')"> show none </button>
<section class="popup">
<div class="popup__container popup__container_type_edit">
pop-up edit content
</div>
<div class="popup__container popup__container_type_create">
pop-up create content
</div>
</section>

Prevent focus on Expand More button after content is inserted in React

I need to list out a long name list inside my page while showing all names at first is not desirable.
So I try to add an expand more button on it.
However, using a button will keep the browser focus on that button after it's pressed, left the button position unchanged on the screen while the name was inserted before that button.
On the other hand, using any, not focusable element (eg. div with onclick function) will do the desired behavior but lost the accessibility at all. Making the "button" only clickable but not focusable.
How do I make the button flushed to list bottom like the snippet div block does? Or is there a better choice to expand the existing list?
const myArray = [
'Alex',
'Bob',
'Charlie',
'Dennis',
'Evan',
'Floron',
'Gorgious',
'Harris',
'Ivan',
'Jennis',
'Kurber',
'Lowrance',
]
const ExpandList = (props) => {
const [idx, setIdx] = React.useState(8)
const handleExpand = e => {
setIdx(idx + 1)
}
return <div className='demo'>
<h1>Name List</h1>
{myArray.slice(0,idx).map(
name => <p key={name}>{name}</p>
)}
<div>
<button onClick={handleExpand} children='Button Expand' className='pointer' />
<div onClick={handleExpand} className='pointer'>Div Expand</div>
</div>
</div>
}
ReactDOM.render(<ExpandList/>, document.getElementById('root'))
.demo>p {
display: block;
padding: 20px;
color: #666;
background: #3331;
}
.demo>div>div {
display: flex;
padding: 15px;
margin-left: auto;
color: #666;
background: #3331;
}
.pointer {
cursor: pointer;
}
.pointer:hover {
background-color: #6663;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id='root' class='demo'>hello</div>
Removing focus from the button in the click handler is probably the most elegant approach: e.target.blur(). It will work on any HTML element, whether it is focusable or not (as with the div in your case).
const myArray = [
'Alex',
'Bob',
'Charlie',
'Dennis',
'Evan',
'Floron',
'Gorgious',
'Harris',
'Ivan',
'Jennis',
'Kurber',
'Lowrance',
]
const ExpandList = (props) => {
const [idx, setIdx] = React.useState(8)
const handleExpand = e => {
e.target.blur()
setIdx(idx + 1)
}
return <div className='demo'>
<h1>Name List</h1>
{myArray.slice(0,idx).map(
name => <p key={name}>{name}</p>
)}
<div>
<button onClick={handleExpand} children='Button Expand' className='pointer' />
<div onClick={handleExpand} className='pointer'>Div Expand</div>
</div>
</div>
}
ReactDOM.render(<ExpandList/>, document.getElementById('root'))
.demo>p {
display: block;
padding: 20px;
color: #666;
background: #3331;
}
.demo>div>div {
display: flex;
padding: 15px;
margin-left: auto;
color: #666;
background: #3331;
}
.pointer {
cursor: pointer;
}
.pointer:hover {
background-color: #6663;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.14.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.14.0/umd/react-dom.production.min.js"></script>
<div id='root' class='demo'>hello</div>
Inspired by #MiKo, temporally unmount the button after click and set a timeout to add it back seems to do the work. Since browser lose the focus on original expand button, this will keep content flush down without focusing the original button:
const ExpandList = (props) => {
const [idx, setIdx] = React.useState(8)
const [showBtn, setShowBtn] = React.useState(true)
const handleExpand = e => {
setShowBtn(false)
setIdx(idx + 1)
setTimeout(() => setShowBtn(true), 10)
}
return <div className='demo'>
<h1>Name List</h1>
{myArray.slice(0,idx).map(
name => <p key={name}>{name}</p>
)}
{showBtn?
<div>
<button onClick={handleExpand} children='Button Expand' className='pointer' />
<div onClick={handleExpand} className='pointer'>Div Expand</div>
</div> :
<div></div>
}
</div>
}
But I'm still looking a method that doesn't need to 'unmount' a thing which should be there all time.

Categories