opens a box within page when link is clicked - javascript

I don't know where to start and what to search. I have two links in my HTML file. I want a box within the page to appear below the link when the link above is clicked and when I clicked the second link, the first box will disappear and the other box below the second link will appear. It is like a sliding box as the link is clicked. What is the code/post for this? Thank you so much!

May be called a content switcher or a tabs widget. Here's a simple way of doing it in CSS.
.box {
display: none;
}
.box:target {
display: block;
}
one two
<div id="one" class="box">box one</div>
<div id="two" class="box">box two</div>
And here's a way to do it in JS
var links = document.getElementsByTagName('a'),
boxes = document.getElementsByClassName('box');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click',function(e) {
e.preventDefault();
var url = this.getAttribute('href').replace('#','');
for (var j = 0; j < boxes.length; j++) {
boxes[j].classList.remove('active');
}
document.getElementById(url).classList.add('active');
})
}
.box {
display: none;
}
.active {
display: block;
}
one two
<div id="one" class="box">box one</div>
<div id="two" class="box">box two</div>

I dont understand you but i guess you want some thing like this :
function myFunction() {
var x = document.getElementById('myDIV');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.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()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>

Related

How to hide navigation bar on link click?

I have 3 buttons and a responsive hamburger menu. Everything works as expected, but I can't think of a way to make a navigation bar go away as soon as I click on a button.
The program is supposed to work like this: clicking hamburger menu activates 3 buttons, whenever user clicks on any of those 3 buttons it hides the buttons and only leaves the button that was clicked.
This is the wanted outcome:
This is my code so far.
html:
<div class="selectSection">
<button type="button" data-number="1" class="active">1</button>
<button type="button" data-number="2">2</button>
<button type="button" data-number="3">3</button>
</div>
<div class="hamburger">
<div class="line"></div>
<div class="line"></div>
<div class="line"></div>
</div>
<div>
<div class="content" data-number="1">
<p>1st page</p>
</div>
<div class="content" data-number="2">
<p>2nd page</p>
</div>
<div class="content" data-number="3">
<p>3rd page</p>
</div>
</div>
css
.content:not(:first-child) {
display: none;
}
.active {
color: orange !important;
}
.hamburger {
display: none;
}
#media all and (max-width: 800px) {
.hamburger {
display: inline-block;
cursor: pointer;
z-index: 7;
}
.hamburger .line {
width: 30px;
height: 3px;
background: black;
margin: 6px 0px;
}
.selectSection {
display: none;
overflow: hidden;
}
.selectSection.active {
display: block;
}
}
js
// change active class, show the clicked element only and hide the others
// grab all the buttons
let Buttons = document.querySelectorAll(".selectSection button");
// loop through the buttons using for..of
for (let button of Buttons) {
// listen for a click event
button.addEventListener("click", (e) => {
// et = event target
const et = e.target;
// slect active class
const active = document.querySelector(".active");
// check for the button that has active class and remove it
if (active) {
active.classList.remove("active");
}
// add active class to the clicked element
et.classList.add("active");
// select all classes with the name content
let allContent = document.querySelectorAll(".content");
// loop through all content classes
for (let content of allContent) {
// display the content if the class has the same data-attribute as the button
if (
content.getAttribute("data-number") ===
button.getAttribute("data-number")
) {
content.style.display = "block";
}
// if it's not equal then hide it.
else {
content.style.display = "none";
}
}
});
}
hamburger = document.querySelector(".hamburger");
hamburger.onclick = function () {
navBar = document.querySelector(".selectSection");
navBar.classList.toggle("activate");
};
This is the demo:
https://codepen.io/f4kermak3r/pen/ExRPKzJ
you are using the wrong css class in your js file. At line 44, you must change navBar.classList.toggle("activate") to navBar.classList.toggle("active"). That should work.

Show/hide div in JS

I'm pretty fresh to JS.
For n amount of bar divs I have n amount foo divs. By clicking on bar[1], I want foo[1] to show or hide. The same goes for bar[2]/foo[2], bar[5]/foo[5], bar[3]/foo[3],...bar[n]/foo[n] in no exact order.
With this code I am able to show and hide, but only all of the divs at the same time. What should I change, so that I am able to hide or show only one of the divs?
function getContent() {
var x = document.getElementsByClassName("foo");
for (var i = 0; i < x.length; i++) {
if (x[i].style.display === "none") {
x[i].style.display = "block";
} else {
x[i].style.display = "none";
}
}
}
document.querySelector(".bar").addEventListener("click", getContent);
.foo {
display: none;
}
.bar {
padding: 5px;
display: block;
}
<div>
<div class="bar" onclick="getContent()">bar</div>
</div>
<div class="foo">foo</div>
No need to use JS here, HTML is more powerful than you think: if you want to show-or-hide information, the <details> element's got you covered.
.all-or-nothing summary {
display: inline-block;
cursor: pointer;
}
<details class="all-or-nothing">
<summary>Toggle all divs</summary>
<div>
The first div
</div>
<div>
The second div
</div>
<div>
The third div
</div>
</details>
Use a variable to hold the index of the current DIV to show, rather than looping over all the DIVs.
let fooIndex = 0;
let allFoo = document.querySelectorAll(".foo");
function getContent() {
if (fooIndex < allFoo.length) {
allFoo[fooIndex].classList.toggle("foo");
allFoo[fooIndex].classList.toggle("bar");
fooIndex++;
}
}
document.querySelector(".bar").addEventListener("click", getContent);
.foo {
display: none;
}
.bar {
padding: 5px;
display: block;
}
<div>
<div class="bar">bar</div>
</div>
<div class="foo">foo1</div>
<div class="foo">foo2</div>
<div class="foo">foo3</div>
<div class="foo">foo4</div>
//let fooIndex = 0;
function getContent() {
var x = $(".card");
x.append('<div class="foo" onclick="hideContent(this)">foo1</div>');
//$(this).addClass('bar');
}
function hideContent(a) {
$(a).removeClass('foo');
$(a).addClass('bar');
}
.foo {
display: none;
}
.bar {
padding: 5px;
display: block;
}
<div class="card">
<div onclick="getContent();" class="bar">bar</div>
</div>

JS: How to make sure only child div is toggled on click

Given example is working fine but red color is showing under Box2 only.
How to make sure if box1 is clicked then red should show below Box1,
if Box2 is clicked box should show below box 2.
CODEPEN
function hideshowmenu() {
var element = document.getElementsByClassName("box");
element[0].classList.toggle("bg-red");
}
.bg-red {
margin-top: 10px;
background-color: red;
height: 20px;
}
<div class="mainmenu " onclick="hideshowmenu()">BOX1</div>
<div id="box" class="box"></div>
<div class="mainmenu " onclick="hideshowmenu()">BOX2</div>
<div id="box" class="box"></div>
only one red should show at one time.
First, the box-id is duplicated, not allowed in HTML. Next, using Event Delegation makes your life easier. If you want the class of div.box after a clicked div.mainmenu element to be bg-red, the next snippet may be an idea (note: creates 100 div.mainmenu elements after the handler is assigned).
document.addEventListener(`click`, handle);
createSomeBoxes();
function handle(evt) {
if (evt.target.classList.contains(`mainmenu`)) {
//^ act only on div.mainmenu
const currentBox = document.querySelector(`.bg-red`);
currentBox && currentBox.classList.remove(`bg-red`);
return currentBox && currentBox.previousElementSibling === evt.target
? true : evt.target.nextElementSibling.classList.add(`bg-red`);
}
}
// for demo
function createSomeBoxes() {
let nBoxes = 0;
while(nBoxes++ < 100) {
document.body.insertAdjacentHTML(`beforeend`,
`<div class="mainmenu">BOX ${nBoxes}</div>
<div class="box"></div>`);
}
}
body {
margin: 2rem;
font: 12px/15px verdana, arial;
}
.mainmenu {
cursor: pointer;
}
.bg-red {
margin-top: 2px;
background-color: red;
height: 20px;
width: 20vw;
}
You only trigger [0]
I would delegate
I also removed ID since IDs need to be unique
const container = document.getElementById("container");
const boxes = container.querySelectorAll(".box")
container.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("mainmenu")) {
const thisBox = tgt.nextElementSibling;
boxes.forEach(box => {
if (box != thisBox) box.classList.remove("bg-red");
})
thisBox.classList.toggle("bg-red");
}
})
.bg-red {
margin-top: 10px;
background-color: red;
height: 20px;
}
<div id="container">
<div class="mainmenu">BOX1</div>
<div class="box"></div>
<div class="mainmenu">BOX2</div>
<div class="box"></div>
</div>
First remove the id's, you dont need them (and theyre not unique so they arent valid anyways).
Then youll need to iterate trough all your .mainmenu items and bin a click to hide all boxes and open the one right besides the item you clicked.
document.querySelectorAll(".mainmenu").forEach(function(menuElement) {
menuElement.addEventListener("click", function() {
document.querySelectorAll(".box").forEach(function(boxElement) {
boxElement.classList.remove("bg-red");
});
this.nextElementSibling.classList.toggle("bg-red");
});
});
.bg-red {
margin-top: 10px;
background-color: red;
height: 20px;
}
<div class="mainmenu">BOX1</div>
<div class="box"></div>
<div class="mainmenu">BOX2</div>
<div class="box"></div>
<div class="mainmenu">BOX3</div>
<div class="box"></div>
<div class="mainmenu">BOX4</div>
<div class="box"></div>
<div class="mainmenu">BOX5</div>
<div class="box"></div>
<div class="mainmenu">BOX6</div>
<div class="box"></div>
<div class="mainmenu">BOX7</div>
<div class="box"></div>
You should use event object to get a target node, and then append div with the class after it. The after function will move the div each time.
<div class="mainmenu" onClick="hideshowmenu(event)">BOX1</div>
<div class="mainmenu" onClick="hideshowmenu(event)">BOX2</div>
const redBox = document.createElement('div');
redBox.classList.add('bg-red');
function hideshowmenu(event) {
const elem = event.target;
elem.after(redBox)
}
https://jsfiddle.net/hj0rgkfp/

Problems with Tabs

I need help with tabs. When is selected first button background color is gray and text in first button is white that okay, but on my second button background color is gray-white and text is white. I want to add grey text color to that second button?
HTML:
<button class="tablink" id="defaultOpen" onclick="openPage('Home', this, '#6D6E70')">First Button</button>
<button class="tablink" onclick="openPage('News', this, '#6D6E70')">Second Button</button>
<div id="Home" class="tabcontent">
<h3>Home</h3>
<p>Home is where the heart is..</p>
</div>
<div id="News" class="tabcontent">
<h3>News</h3>
<p>Some news this fine day!</p>
</div>
CSS:
.tablink {
display: inline-block;
min-width: 128px;
font-size: 16px;
padding: 8px;
color: #fff;
font-weight: 500;
text-decoration: none;
background-color: #F2F2F2;
}
.tablink:hover {
background-color: #777;
}
/* Style the tab content (and add height:100% for full page content) */
.tabcontent {
color: white;
display: none;
padding: 100px 20px;
height: 100%;
}
Java Script:
<script>
function openPage(pageName,elmnt,color) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
document.getElementById(pageName).style.display = "block";
elmnt.style.backgroundColor = color;
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>
I try add to java script code in document.getElementsByClassName("tablink")
tablinks[i].style.color = "#fff";
But not working
If you want to change second button text color after clicking on it, you can simply add this line:
if (pageName === 'News') {
elmnt.style.color = 'black';
}
Here's JSfiddle.
However you'd be better off using CSS to properly style those elements the way you want.
Let me know if you need further assistance with that.
EDIT:
Since it has been cleared out what you're trying to achieve, the best way to tackle your problem would be to do it by toggling classes. Here's JSfiddle.
Basically, I've added two extra classes .selected, and .visible, one for buttons, other for divs, like so:
HTML:
<button class="tablink selected" onclick="openPage('Home', this)">First Button</button>
/* ... */
<div id="Home" class="tabcontent visible">
<h3>Home</h3>
<p>Home is where the heart is..</p>
</div>
CSS:
.tablink.selected {
color: #fff;
background-color: #6D6E70;
}
.tabcontent.visible {
display: block;
}
And shortened your JS code:
function openPage(pageName, elmnt) {
document.querySelector('.tablink.selected').classList.remove('selected');
elmnt.classList.add('selected');
document.querySelector('.tabcontent.visible').classList.remove('visible');
document.getElementById(pageName).classList.add('visible');
}
So whenever you click, it looks for a selected/visible element, removes those extra classes, and adds them back to the button that has been pressed and div that corresponds to it.

How to unclick other button using 1 button

I have 15 buttons, each button has content, but when I clicked button1 and followed by button 2, the button 1 is still open. How can I close the button 1 if I click button2?
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
div.panel {
position: absolute;
max-width: 0;
overflow: hidden;
opacity: 0;
}
div.panel.show {
opacity: 1;
max-width: 900px;
}
<button class="accordion">The Ball</button>
<div class="panel">
<h1>The Ball</h1>
</div>
<button class="accordion">The Cat</button>
<div class="panel">
<h1>The Cat</h1>
</div>
<button class="accordion">The Dog</button>
<div class="panel">
<h1>The Dog</h1>
</div>
You need to remove active and show classes from previous div before adding them to clicked div.
Your JS Code will be:
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
var previous = document.querySelector(".active"); //select previous button
if (previous) { // check because when first time no button has active class
previous.classList.remove("active");
previous.nextElementSibling.classList.remove("show");
}
this.classList.add("active");
this.nextElementSibling.classList.add("show");
};
}
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
var previous = document.querySelector(".active");
if (previous) {
previous.classList.remove("active");
previous.nextElementSibling.classList.remove("show");
}
this.classList.add("active");
this.nextElementSibling.classList.add("show");
};
}
div.panel {
position: absolute;
max-width: 0;
overflow: hidden;
opacity: 0;
}
div.panel.show {
opacity: 1;
max-width: 900px;
}
<button class="accordion">The Ball</button>
<div class="panel">
<h1>The Ball</h1>
</div>
<button class="accordion">The dog</button>
<div class="panel">
<h1>The dog</h1>
</div>
<button class="accordion">The cat</button>
<div class="panel">
<h1>The cat</h1>
</div>
So select the active one. If it is active remove it. If the current one is not the active class add it.
// select all the buttons
var btns = document.querySelectorAll('.accordion')
// loop over
btns.forEach(function (btn) {
// bind the click
btn.addEventListener('click', function (evt) {
// stop button click
evt.preventDefault()
// find the active one
var active = document.querySelector('.accordion.active')
// see if active button is the clicked button
var isSame = active == btn
// if we have an active button, remove the class
if (active) active.classList.remove('active')
// if the current button was not the active one add the class
if (!isSame) btn.classList.add('active')
})
})
button {
display: block;
}
button + div {
max-height: 0;
transition: max-height 0.25s ease-out;
overflow: hidden;
}
button.active {
background-color: green;
}
button.active + div {
max-height: 500px;
transition: max-height 0.5s ease-in;
}
<button class="accordion">The Ball 1</button>
<div><p>Ball 1</p><p>bounce bounce poounce</p></div>
<button class="accordion">The Ball 2</button>
<div><p>Ball 2</p><p> bounce pop</p></div>
<button class="accordion">The Ball 3</button>
<div><p>Ball 3</p><p>bounce bounce over the fence</p></div>
An alternative using JQuery.
I have changed the CSS to remove max-width and opacity and have set .panel elements to be display: none; initially:
div.panel {
position: absolute;
display: none;
}
And using JQuery, whenever we click an .accordion element, we hide the .panel elements (in case any others are showing), and then show the one that relates to the specifically clicked .accordion element.
// register clicks on accordion elements
$('.accordion').click(function() {
// hide each .panel related to every .accordion element
$('.accordion').next().hide();
// show the .panel next to our clicked .accordion element
$(this).next().show();
})

Categories