show/hide elements and switch between them js - javascript

I have two elements that are hidden. When button a is clicked, I would like div a to show. When button b is clicked, I would like div a to close and div b to show.
However, if button a is clicked a second time after being shown, I would like it to hide the div again. Same with button b.
Update:
I was able to get the buttons to toggle properly.
However, upon initial loading, I want them to be hidden, or not visible until the button is clicked.
The following is my current javascript
function openFamily(evt, famName) {
var i, x, y, tablinks;
x = document.getElementsByClassName("family");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
tablinks = document.getElementsByClassName("familytablink");
for (i = 0; i < x.length; i++)
document.getElementById(famName).style.display = "block";
}
I have a CSS element:
.container{
display: none;
}
HTML:
<div>
<div>
<button class="familytablink" onclick="openFamily(event,'zep')">Zephaniah</button>
<button class="familytablink" onclick="openFamily(event,'anna')">Anna</button>
</div>
<div id="zep" class="container mainp-2 family">
filler text
</div>
<div id="anna" class="container mainp-2 family">
filler text
</div>
</div>

Here's an exemple of how you can achieve that
var toggleDivById = function (id) {
var div = document.getElementById(id);
if (div.classList.contains('active')) {
return div.classList.remove('active');
}
div.classList.add('active');
}
var handleToggleClick = function (event) {
var targetId = event.target.dataset.target;
toggleDivById(targetId);
}
document.querySelectorAll('.toggle')
.forEach(function(toggle) {
toggle.addEventListener('click', handleToggleClick)
})
.toggable {
width: 50px;
height: 50px;
background-color: crimson;
border: 2px solid tomato;
visibility: hidden;
transition: all 100ms ease-out;
border-radius: 5px;
box-shadow: 1px 1px 2px indianred;
}
.toggable.active {
visibility: visible
}
<button data-target="a" class="toggle">A</button>
<button data-target="b" class="toggle">B</button>
<hr/>
<div id="a" class="toggable">A</div>
<div id="b" class="toggable">B</div>

In jQuery:
<script type="application/javascript">
$(document).ready(function(){
$("#button1").click(function(){
$("diva").show();
});
$("#button2").click(function(){
$("diva").hide();
$("divb").show();
});
});
</script>
In JS:
<script type="application/javascript">
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>

You can use hide and show function in Jquery and use it when a button is clicked something like this :
like
$("selector").click(function(){
$("divid").hide();
$("divid").show();
})

Related

JavaScript Function

Hello everybody I have this code that I have made alone.
function appearafter() {
document.getElementById("buttonappear").style.display = "block";
document.getElementById("button").style.display = "block";
document.getElementById("hinzufuegen").style.display = "none";
function myFunction() {
var itm = document.getElementById("myList2").lastChild;
var cln = itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
function allFunction() {
myFunction();
appearafter();
}
#button {
display: none;
}
#buttonappear {
display: none;
}
#test {
width: 300px;
height: 300px;
background-color: red;
}
<!DOCTYPE html>
<html>
<body>
<button id="hinzufuegen" onclick="allFunction()">ADD</button>
<div id="myList1">
<button id="button" onclick="">DELETE</button>
<div id="myList2">
<div id="test">
</div>
</div>
</div>
<button onclick="allFunction()" id="buttonappear">ADD</button>
</body>
</html>
What I want to make is that the red square whenever you are clicking on the ADD button it will be a clone and when you click on the DELETED button that the clone is deleted. Can somebody help me, please?
In addition to missing } as was mentioned in the comments, there was a not-so-obvious problem with finding the <div> to clone. The lastChild was actually a text node containing the \n (newline), after the <div>. It's better to search for <div> by tag:
var itm = document
.getElementById('myList2')
.getElementsByTagName('div')[0];
Since there's only one <div> we can use the zero index to find this first and only one.
And for delete function you can use a similar approach and get the last <div> and remove it.
function appearafter() {
document.getElementById("buttonappear").style.display = "block";
document.getElementById("button").style.display = "block";
document.getElementById("hinzufuegen").style.display = "none";
}
function myFunction() {
var itm = document.getElementById("myList2").getElementsByTagName("div")[0];
var cln = itm.cloneNode(true);
document.getElementById("myList1").appendChild(cln);
}
function deleteFunction() {
var list1 = document.getElementById("myList1");
var divs = Array.from(list1.getElementsByTagName("div"));
// If the number of divs is 3, it means we're removing the last
// cloned div, hide the delete button.
if (divs.length === 3) {
document.getElementById("button").style.display = "none";
}
var lastDivToDelete = divs[divs.length - 1];
list1.removeChild(lastDivToDelete);
}
function allFunction() {
myFunction();
appearafter();
}
#button {
display: none;
}
#buttonappear {
display: none;
}
#test {
/* make it smaller so it's easier to show in a snippet */
width: 30px;
height: 30px;
background-color: red;
}
<button id="hinzufuegen" onclick="allFunction()">ADD</button>
<div id="myList1">
<button id="button" onclick="deleteFunction()">DELETE</button>
<div id="myList2">
<div id="test"></div>
</div>
</div>
<button onclick="allFunction()" id="buttonappear">ADD</button>

Make same active button after reload

Right now, I have two buttons that each button have different views.
<div style="margin-top:-25px;margin-left:105px;">
<p style="color:black;"><b>View In : </b></p>
<div class="btnContainer" id="btnContainer">
<button class="lists active" onclick="gridView()"> Grid</button>
<button class="lists" onclick="listView()" style="margin-left:-4px;"> List</button>
</div>
</div>
<div class="row" id="pading1">
<!------------- Card Position 1 ----------------->
</div>
<div class="row" id="pading2">
<!------------- Card Position 2 ----------------->
</div>
Here's the css script to styling the button
/* Style the buttons grid */
.lists {
border: none;
outline: none;
padding: 5px 10px;
background-color: #ffffff;
cursor: pointer;
width: 100px;
}
.lists:hover{
background-color: #ddd;
}
.lists.active {
background-color: #01b1ea;
color: white;
}
.btnContainer{
background-color:transparent;
width:200px;
margin-top:-35px;
margin-left:70px;
}
Here's js script to switch the view every page
<!------------------- Switch Padding Button Grid Maps ------------------->
<script>
function listView(){
$("#pading1").hide();
$("#pading2").show();
$(".search-container").hide();
}
function gridView(){
$("#pading1").show();
$("#pading2").hide();
}
var container = document.getElementById("btnContainer");
var btns = container.getElementsByClassName("lists");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
</script>
Right now, every I reload the page it still going to grid view as I set grid view is the default.
I want to ask, when I in list view and I refresh the web, how to make the button active is still in the list view ?
Thank you
You can do this either by setting a sessionStorage / localStorage or a cookie. This is a working example using sessionStorage:
// Check what type of view we have setup
if(sessionStorage.view == 'list') {
listView();
}
else {
gridView();
}
function listView(){
$("#pading1").hide();
$("#pading2").show();
$(".search-container").hide();
sessionStorage.view = "list";
}
function gridView(){
$("#pading1").show();
$("#pading2").hide();
sessionStorage.view = "grid";
}
var container = document.getElementById("btnContainer");
var btns = container.getElementsByClassName("lists");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}

How to Hide and then Show on Click Multiple Content Items by Default?

I have the following code. By default it shows, but I want to hide it by default.
Also, I'm unable to control both of the divs, only 1 of the show/hide toggles work, I want for them (but have been unsuccessful) both to work.
How can I hide by default and expand on click?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<br><br>
<button onclick="myFunction()">Try it 2</button>
<div id="myDIV2">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
var x = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
var x = document.getElementById("myDIV");
var x = document.getElementById("myDIV2");
You are overwriting your x variable.
Assign myDIV2 to another variable like y and repeat the process.
Better would be to just assign the same class instead of id to the elements you want to hide and just toggle the class instead of trying to get each element by id.
https://ultimatecourses.com/blog/javascript-hasclass-addclass-removeclass-toggleclass
Just separate the function on the first and scond button
function myFunction_1() {
var x = document.getElementById("myDIV");
var y = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function myFunction_2() {
var y = document.getElementById("myDIV2");
if (y.style.display === "none") {
y.style.display = "block";
} else {
y.style.display = "none";
}
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction_1()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<br><br>
<button onclick="myFunction_2()">Try it 2</button>
<div id="myDIV2">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

Javascript To Toggle Multiple Buttons

I have some Javascript code that targets multiple buttons. When clicked, the content should appear, which it does. However, i'm struggling to create the code that when the buttons are clicked again, the content is hidden.
I've included the Javascript, content and css for the elements i want to be toggled. Cheers.
Note: Code has to be in Javascript
function openTab(click, openTab) {
var i, content, link;
content = document.getElementsByClassName("content");
for (i = 0; i < content.length; i++) {
content[i].style.display = "none";
}
links = document.getElementsByClassName("links");
for (i = 0; i < links.length; i++) {
links[i].className = links[i].className.replace(" active", "");
}
document.getElementById(openTab).style.display = "block";
click.currentTarget.className += " active";
}
.content {
font-family: 'Lato';
max-width: 100%;
font-size: 20px;
letter-spacing: 4px;
color: #e8eaed;
display: none;
border-top: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<section class = "Container">
<div class="tabs">
<button class="link" onclick="openTab(event, 'About')">About</button>
<button class="link" onclick="openTab(event, 'Hire')">Why You Should Hire Me</button>
<button class="link" onclick="openTab(event, 'Contact')">Contact</button>
</div>
</section>
<section class="Container2">
<div id="About" class="content">About</div>
<div id="Hire" class="content">Hire</div>
<div id="Contact" class="content">Contact</div>
</section>
Declare a variable which represents whether the elements are hidden or not. Also, you could try to use classList to add/remove classes from elements with multiple class names, rather than className string manipulation, if at all possible.
You can use classList.toggle to easily switch classes:
let hidden = false;
function openTab(click, openTabId) {
document.querySelectorAll('.content').forEach(
content => content.style.display = hidden ? 'block' : 'none'
);
document.querySelectorAll('.links').forEach(
link => link.classList.toggle('active')
);
document.getElementById(openTabId).style.display = "block";
click.currentTarget.classList.toggle('active');
hidden = !hidden;
}
Better yet, encapsulate the hidden variable in openTab, since it's not useful in the outer scope:
const openTab = (() => {
let hidden = false;
return (click, openTabId) => {
document.querySelectorAll('.content').forEach(
content => content.style.display = hidden ? 'block' : 'none'
);
document.querySelectorAll('.links').forEach(link => {
if (hidden) link.classList.add('active');
else link.classList.remove('active');
});
document.getElementById(openTabId).style.display = "block";
click.currentTarget.classList.toggle('active');
hidden = !hidden;
}
})();

Highlight the text in textarea with delay

I am trying to highlight the single line of text in <textarea> with time delay. And I am wondering if I can choose a different color? The thing I wanted is when I click on the first <button>, the first line is highlighted into blue, click on the second <button>, 1 second later, the second line is highlighted into blue, lastly click on the third <button>, 2 second later, the third line is highlighted into yellow. I noticed I have a bug that I clicked on the button 3 times then the highlight doesn't work, but it is okay for me, I just want to know how to make the time delay and highlight with a different color. Thank you very much.
$( document ).ready(function() {
var str = 'line 1\nline 2\nline 3\n';
var textNumChar = str.length;
$('#str').val(str);
startPosition = 0;
$(".lines").click(function() {
var tarea = document.getElementById('str');
for(i=startPosition;i<textNumChar;i++)
{
if(str[i]=='\n') {
endposition = i;
break;
}
}
tarea.selectionStart = startPosition;
tarea.selectionEnd = endposition;
startPosition = endposition+1;
});
});
#container {
float: left;
}
button {
width: 50px;height: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
<button class="lines" id="line1">line 1</button>
<br>
<button class="lines" id="line2">line 2</button>
<br>
<button class="lines" id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>
You can use setTimeout() to set the delay in highlighting the text based on button id.
And ::selection css selector to style the portion of an element that is selected.
$( document ).ready(function() {
var str = 'line 1\nline 2\nline 3\n';
var textNumChar = str.length;
$('#str').val(str);
startPosition = 0;
$(".lines").click(function(e) {
var tarea = document.getElementById('str');
for(i=startPosition;i<textNumChar;i++)
{
if(str[i]=='\n') {
endposition = i;
break;
}
}
var time = 0;
var tar_id = e.target.id;
var colors;
if(tar_id == 'line1' ) { colors = 'red'; }
else if(tar_id == 'line2' ) { time = 1000; colors = 'blue'; }
else if(tar_id == 'line3' ) { time = 2000; colors = 'green'; }
setTimeout(function(){
tarea.selectionStart = startPosition;
tarea.selectionEnd = endposition;
startPosition = endposition+1;
$('body').addClass(colors);
}, time);
});
});
#container {
float: left;
}
button {
width: 50px;height: 30px;
}
.red ::selection {
color: red;
background: yellow;
}
.blue ::selection {
color: blue;
background: red;
}
.green ::selection {
color: green;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
<button class="lines" id="line1">line 1</button>
<br>
<button class="lines" id="line2">line 2</button>
<br>
<button class="lines" id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>

Categories