Hide and show DIV with javascript parameter - javascript

I am trying to do an event for hide and show with pure Javascript string parameters. I want to hide the other div once one of them is displayed (Let's say there are multiple div).
I tried to do it my own but I only managed to display once clicked. I had no idea how to hide the rest and only show that specified div.
Below is my code:
function show(id) {
if (document.getElementById('div_'+id).style.display == 'none') {
document.getElementById('div_'+id).style.display = 'block';
}
return false;
}
.title {
border:1px solid red;
display: inline-block;
font-size: 16px;
}
.content {
border: 1px solid blue;
display: inline-block;
font-size: 16px;
width: 300px;
}
<div class="title" onclick="show('first');">Title 1</div>
<div class="content" id="div_first" style="display:none;">Content 1
</div>
<div class="title" onclick="show('sec');">Title 2</div>
<div class="content" id="div_sec" style="display:none;">Content 2
</div>

You can use data-* attribute to store the target selector.
Don't use inline on* handlers. Keep your JS in one place.
Use CSS .is-active to manipulate the visibility state like display: block;
const showBtn = document.querySelectorAll('[data-show]');
const content = document.querySelectorAll('.content');
function show(ev) {
const selector = ev.currentTarget.getAttribute('data-show');
const elToShow = document.querySelectorAll(selector);
content.forEach(el => el.classList.remove('is-active'));
elToShow.forEach(el => el.classList.add('is-active'));
}
showBtn.forEach(el => el.addEventListener('click', show));
.title {
border:1px solid red;
display: inline-block;
font-size: 16px;
}
.content {
border: 1px solid blue;
display: inline-block;
font-size: 16px;
width: 300px;
display: none; /* ADD THIS */
}
.content.is-active{ /* ADD THIS */
display: block;
}
<div class="title" data-show="#content-1">Title 1</div>
<div class="title" data-show="#content-2">Title 2</div>
<div class="content" id="content-1">Content 1</div>
<div class="content" id="content-2">Content 2</div>

Just keep track of the id or element that is being displayed so that you can hide it if another one is selected. There's no need to iterate over them to hide them all, as you will know which one is being displayed, or to query the DOM each time to get the current one, as you can just keep a reference to it the first time.
I have updated the logic to toggle them if you click the same one twice and removed the inline event listeners, which I've moved to JS.
Note I have also replaced the <div>s for the .title elements with <button>s, as they will work better with keyboard navigation, mouse events and screen readers. You could also use <a>s instead.
let currentContentTab = null;
function show(e) {
// Using e.target you can get a reference to the clicked button:
const contentTab = document.getElementById(`div${ e.target.id.substring(3) }`);
const isHidden = contentTab.style.display === 'none';
// Toggle the panel we have just clicked (assuming you want to allow closing all of them again):
contentTab.style.display = isHidden ? 'block' : 'none';
// Hide the previous one, if any:
if (currentContentTab) {
currentContentTab.style.display = 'none';
}
// Keep track of the one we are currently displaying:
currentContentTab = isHidden ? contentTab : null;
}
// No need to have inline JS, you can bind the event listeners from JS:
for (const button of document.querySelectorAll('.title')) button.onclick = show;
body {
font-family: monospace;
font-size: 16px;
}
.title {
font-family: monospace;
font-size: 16px;
border: 1px solid red;
background: transparent;
padding: 8px;
outline: none;
}
.content {
border: 1px solid blue;
width: 300px;
padding: 8px;
margin-top: 8px;
}
<button class="title" id="tab1">Title 1</button>
<button class="title" id="tab2">Title 2</button>
<button class="title" id="tab3">Title 3</button>
<button class="title" id="tab4">Title 4</button>
<div class="content" id="div1" style="display:none; ">
Content 1...
</div>
<div class="content" id="div2" style="display:none; ">
Content 2...
</div>
<div class="content" id="div3" style="display:none; ">
Content 3...
</div>
<div class="content" id="div4" style="display:none; ">
Content 4...
</div>
If accessibility is important for you, you might want to add some ARIA attributes and the HTML hidden attribute:
let currentTab = null;
let currentPanel = null;
function show(e) {
const tab = e.target;
const id = tab.getAttribute('aria-controls');
const panel = document.getElementById(id);
// Toggle the panel we have just clicked:
tab.toggleAttribute('aria-selected');
panel.toggleAttribute('hidden');
// Hide the previous one, if any:
if (currentTab) {
currentTab.removeAttribute('aria-selected');
currentPanel.setAttribute('hidden', true);
}
// Keep track of the one we are currently displaying:
if (currentTab === tab) {
currentTab = null;
currentPanel = null;
} else {
currentTab = tab;
currentPanel = panel;
}
}
for (const button of document.querySelectorAll('.title')) button.onclick = show;
body {
font-family: monospace;
font-size: 16px;
}
.title {
font-family: monospace;
font-size: 16px;
border: 1px solid red;
background: transparent;
padding: 8px;
outline: none;
}
.content {
border: 1px solid blue;
width: 300px;
padding: 8px;
margin-top: 8px;
}
<button class="title" role="tab" aria-selected="true" aria-controls="div1" id="tab1">Title 1</button>
<button class="title" role="tab" aria-selected="true" aria-controls="div2" id="tab2">Title 2</button>
<button class="title" role="tab" aria-selected="true" aria-controls="div3" id="tab3">Title 3</button>
<button class="title" role="tab" aria-selected="true" aria-controls="div4" id="tab4">Title 4</button>
<div class="content" id="div1" role="tabpanel" aria-labelby aria-labelledby="tab1" hidden>
Content 1...
</div>
<div class="content" id="div2"role="tabpanel" aria-labelby aria-labelledby="tab2" hidden>
Content 2...
</div>
<div class="content" id="div3"role="tabpanel" aria-labelby aria-labelledby="tab3" hidden>
Content 3...
</div>
<div class="content" id="div4"role="tabpanel" aria-labelby aria-labelledby="tab4" hidden>
Content 4...
</div>

This JS code will grab all .content divs and will hide them unless it's the one we clicked.
function show(id) {
const el = document.getElementById('div' + id);
if (el.style.display == 'none') {
el.style.display = 'block';
}
const otherEls = document.querySelectorAll('.content');
otherEls.forEach(function (elItem) {
if (el !== elItem) {
elItem.style.display = 'none';
}
});
return false;
}

My solution as the following:
function show(id)
{
var divs=document.getElementsByClassName("content");
for (i=0;i<divs.length;i++)
{
divs[i].style.display='none';
}
document.getElementById('div_'+id).style.display = 'block';
}
.title {
border:1px solid red;
display: inline-block;
font-size: 16px;
}
.content {
border: 1px solid blue;
display: inline-block;
font-size: 16px;
width: 300px;
}
<div class="title" onclick="show('first');">Title 1</div>
<div class="content" id="div_first" style="display:none;">Content 1
</div>
<div class="title" onclick="show('sec');">Title 2</div>
<div class="content" id="div_sec" style="display:none;">Content 2
</div>

Related

Hide & show content with javaScript

So, on my example I have 2 div-buttons (named btn1 and btn2) and 2 div elements (named content1 and content2).
What I would want, is that when you click the btn1, content1 shows. If you click btn2, content2 should show.
Content1 and content2 elements are currently placed in the same position, and by default, none of the content elements shouldn't be open before you have clicked anything. I would like to achieve this with pure javaSript.
Here is the example code:
var btn1 = document.getElementById("btn1");
var content1 = document.getElementById("content1");
content1.style.opacity = "0";
btn1.addEventListener("mouseover", showContent1);
function showContent1(){
if(content1.style.opacity === "0") {
content1.style.opacity = "1";
} else {content1.style.opacity = "0";}
}
var btn2 = document.getElementById("btn2");
var content2 = document.getElementById("content2");
content2.style.opacity = "0";
btn2.addEventListener("mouseover", showContent2);
function showContent2(){
if(content2.style.opacity === "0") {
content2.style.opacity = "1";
} else {content2.style.opacity = "0";}
}
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;height:200px;border: 2px solid black;
}
#content1, #content2 {
width: 200px;height:200px;position:absolute;background:lightblue;
}
<div id="btn1">show1</div>
<div id="btn2">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
You can add click event to the buttons and based on the button clicked you can show or hide the respective div.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<style>
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;
height:200px;
border: 2px solid black;
}
#content1, #content2 {
width: 200px;
height:200px;
position:absolute;
background:lightblue;
display:none;
}
</style>
</head>
<body>
<script>
function showDiv(div){
if(div == 'btn1'){
document.getElementById('content1').style.display = 'block';
document.getElementById('content2').style.display = 'none';
}else{
document.getElementById('content1').style.display = 'none';
document.getElementById('content2').style.display = 'block';
}
}
</script>
<div id="btn1" onclick="showDiv('btn1')">show1</div>
<div id="btn2" onclick="showDiv('btn2')">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
</body>
Plunker For the same: https://plnkr.co/edit/brxoF2ClW2TeJOVMxn8d?p=preview
Check this, i've made it dynamic so you can create unlimited buttons and contents.
function toogleContent(id){
var toogleContent = document.getElementsByClassName('toogleContent');
var i = toogleContent.length;
while (i--) toogleContent[i].style.display = "none";
document.getElementById(id).style.display = "block";
}
#btn1, #btn2 {
width:100px;
height:20px;
text-align:center;
background:grey;
cursor:pointer;
margin:10px 0px;
}
#contents {
width: 200px;
height:200px;
border: 2px solid black;
}
#content1, #content2 {
width: 200px;
height:200px;
position:absolute;
background:lightblue;
display:none;
}
<div id="btn1" class="toogleBtn" onclick="toogleContent('content1')">show1</div>
<div id="btn2" class="toogleBtn" onclick="toogleContent('content2')">show2</div>
<div id="contents">
<div id="content1" class="toogleContent">content 1</div>
<div id="content2" class="toogleContent">content 2</div>
</div>
Whilst the above answers are all correct insofar as they will get you from A to B (based on the code you have provided), there are also a few 'best practice' changes you should use in your code, to avoid common pitfalls (and allow better maintainability and code reuse).
Firstly, you should avoid using IDs for styling. Whilst using an ID to apply styles is perfectly valid to do (and won't break anything) it is discouraged. An ID for a page must always be unique within a document, so using it to style potentially multiple similar elements means that you will very quickly have either broken HTML (by reusing an ID) or unwieldy and non-maintainable stylesheets (by having multiple identical selectors). You should prefer using classes to add styles to elements, as you can reuse classes, and even extend or use multiple classes per element.
In my snippet, I have also used a dataset with a number in it to help identify which element is being 'selected'. Datasets are intended to store custom data, and are extremely useful for storing and retrieving data in JavaScript. By using a dataset to store an ID that is independent of the ID or class of an element, you can infinitely add/remove tabs without having to change your CSS or JavaScript to fit. After all, I can add in a dataset for an ID of 3 (e.g. <div class="button" data-id="3">) and the button styling won't be affected.
Other good practices include using separate class names or selectors for JavaScript compared to those used to style an element (again so that you can change the name of a JavaScript selector without affecting the look of an element - you can also prepend a JavaScript selector with js- as I have done, so that it is more obvious that the selector is used by JavaScript, and not used to style an element).
I have also used a BEM styleguide to name my classes (though this is a preference thing - in short though, it is good practice to pick and then use some sort of naming convention or style guide for naming/styling elements).
A final recommendation (not shown) <button> element instead of a <div> for buttons. This will improve your disability access for a website, as screen reader technology can then distinguish between what is a button and what is merely a block of content (after all, a screen reader might not pick up that the <div> has a click event handler added, and so a disabled user might not be aware they can click on the 'button' to switch tabs).
// Select all buttons using querySelectorAll
let buttons = document.querySelectorAll('.js-toggle');
// Loop through each button and add an event listener
Array.from(buttons).forEach(button => {
// Click event listener
button.addEventListener('click', function() {
// Select all elements to hide/show
let tab_contents = document.querySelectorAll('.js-content');
// Hide all elements
hideElems(tab_contents);
// Get ID of button
let id = this.dataset.id;
// Select relevant tab using the ID above
document.querySelector(`.js-content-${id}`).style.display = 'block';
});
});
// Function for hiding all elements
let hideElems = (elems) => {
Array.from(elems).forEach(elem => elem.style.display = 'none');
}
.button {
width: 100px;
height: 20px;
text-align: center;
background: grey;
cursor: pointer;
margin: 10px 0;
}
.tabs {
width: 200px;
height: 200px;
border: 2px solid black;
}
.tabs__content {
width: 200px;
height: 200px;
background: lightblue;
display: none;
}
<div class="button js-toggle" data-id="1">show1</div>
<div class="button js-toggle" data-id="2">show2</div>
<div class="tabs">
<div class="tabs__content js-content js-content-1">content 1</div>
<div class="tabs__content js-content js-content-2">content 2</div>
</div>
document.getElementById('btn1').addEventListener('click', ()=>{
document.getElementById('content2').style.display = "none";
document.getElementById('content1').style.display = "block";
});
document.getElementById('btn2').addEventListener('click', ()=>{
document.getElementById('content1').style.display = "none";
document.getElementById('content2').style.display = "block";
});
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;height:200px;border: 2px solid black;
}
#content1, #content2 {
width: 200px;height:200px;position:absolute;background:lightblue;display:none;
}
<div id="btn1">show1</div>
<div id="btn2">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
You need onClick event and 2 conditions. Please check this,
function showContent(content_id) {
if (content_id == 'content1') {
document.getElementById('content1').style.display = 'block';
document.getElementById('content2').style.display = 'none';
} else if (content_id == 'content2') {
document.getElementById('content1').style.display = 'none';
document.getElementById('content2').style.display = 'block';
}
}
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;height:200px;border: 2px solid black;
}
#content1, #content2 {
width: 200px;height:200px;position:absolute;background:lightblue; display:none;
}
<div id="btn1" onClick='showContent("content1")'>show1</div>
<div id="btn2" onClick='showContent("content2")'>show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
This is a simple way to do it with vanilla javascript, just add a method that hides/shows the element based on which button you click
function toogle(showelem, hideelem) {
document.getElementById(showelem).style.display = "block";
document.getElementById(hideelem).style.display = "none";
}
#btn1, #btn2 {
width:100px;height:20px;text-align:center;background:grey;cursor:pointer;margin:10px 0px;
}
#contents {
width: 200px;height:200px;border: 2px solid black;
}
#content1, #content2 {
width: 200px;height:200px;position:absolute;background:lightblue;
}
<div id="btn1" onClick="toogle('content1','content2');">show1</div>
<div id="btn2" onClick="toogle('content2','content1');">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.remove("displayblock");
}
function myFunctionShow(){
var element = document.getElementById("myDIV");
element.classList.add("displayblock");
}
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
display:none;
}
.displayblock{
display:block;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Click the "Try it" button to remove the "mystyle" class from the DIV element:</p>
<button onclick="myFunction()">Hide</button>
<button onclick="myFunctionShow()">Show</button>
<div id="myDIV" class="mystyle displayblock">
This is a DIV element.
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#btn1,
#btn2 {
width: 100px;
height: 20px;
text-align: center;
background: grey;
cursor: pointer;
margin: 10px 0px;
}
#contents {
width: 200px;
height: 200px;
border: 2px solid black;
}
#content1,
#content2 {
width: 200px;
height: 200px;
position: absolute;
background: lightblue;
}
</style>
</head>
<body>
<div id="btn1" onclick="showdiv1()">show1</div>
<div id="btn2" onclick="showdiv2()">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
</body>
<script>
function showdiv1(){
console.log( document.getElementById('content1'))
document.getElementById('content1').style.display='block';
document.getElementById('content2').style.display='none';
}
function showdiv2(){
document.getElementById('content1').style.display='none';
document.getElementById('content2').style.display='block';
}
</script>
</html>
Here We Go
You can you this for any element to hide and show
element.style.display = 'none'; // Hide
element.style.display = 'block'; // Show
element.style.display = 'inline'; // Show
element.style.display = 'inline-block'; // Show
If I understand you right, you should set "display: none" by default and then handle click on button to toggle "open" class. See example below.
const btn1 = document.getElementById("btn1"),
btn2 = document.getElementById("btn2"),
content1 = document.getElementById("content1"),
content2 = document.getElementById("content2");
const map = new Map()
.set(btn1, content1)
.set(btn2, content2);
const closeMapContent = _ =>
map.forEach((value, key) => value.classList.remove("open"));
map.forEach((value, key) => {
key.addEventListener("click", event => {
closeMapContent();
value.classList.add("open");
})
});
#btn1, #btn2 {
width: 100px;
height: 20px;
text-align: center;
background: grey;
cursor: pointer;
margin: 10px 0px;
}
#contents {
width: 200px;
height: 200px;
border: 2px solid black;
}
#content1, #content2 {
width: 200px;
height: 200px;
position: absolute;
background: lightblue;
display: none;
}
.open {
display: block !important;
}
<div id="btn1">show1</div>
<div id="btn2">show2</div>
<div id="contents">
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
function show() {
const h = document.getElementById('hidden1');
h.style.display = 'block' ;
const s =document.getElementById('showed');
s.style.display = 'none';
}
function hide() {
const h = document.getElementById('hidden1');
h.style.display = 'none' ;
const s =document.getElementById('showed');
s.style.display = 'block';
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div >
<button id="showed" onclick="show()" >click to show</button>
<div id="hidden1" style="display: none">
<button onclick="hide()" >click to close</button>
<h1 >Content1</h1>
</div>
</div>
</body>
</html>
see with snippet
Another way to approach this is to use data-* attribute with little bit of styling. You can change the attribute of the parent div then the changes are reflected on children using CSS.
Also, you don't need to loops through elements if know the number of children elements.
See this example:
function toogleContent(target) {
document.querySelector("#contents").setAttribute("data-show", target);
}
#btn1,
#btn2 {
width: 100px;
height: 20px;
text-align: center;
background: grey;
cursor: pointer;
margin: 10px 0px;
}
#contents {
width: 200px;
height: 200px;
border: 2px solid black;
}
#content1,
#content2 {
width: 200px;
height: 200px;
position: absolute;
background: lightblue;
opacity: 0;
}
#contents[data-show='1']>#content1 {
opacity: 1;
}
#contents[data-show='2']>#content2 {
opacity: 1;
}
<div id="btn1" onclick="toogleContent(1)">show1</div>
<div id="btn2" onclick="toogleContent(2)">show2</div>
<div id="contents" data-show=''>
<div id="content1">content 1</div>
<div id="content2">content 2</div>
</div>
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
(function() {
const buttons = document.querySelectorAll('.button');
const content = document.querySelector('.content__wrapper');
hideAll();
setUpClickHandlers();
function hide(element) {
element.classList.add('hide');
}
function show(element) {
element.classList.remove('hide')
}
function hideAll() {
Array.from(content.children).forEach(hide);
}
function toggle(element) {
hideAll();
show(element)
}
function onClick(content) {
return () => toggle(content)
}
function setUpClickHandlers() {
const handler = element => {
const show = content.querySelector(`.${element.dataset.for}`);
element.addEventListener('click', onClick(show));
};
Array.from(buttons).forEach(handler);
}
})()
.hide {
display: none
}
.button {
height: 30px;
line-height: 30px;
border-radius: 5px;
border: 1px solid grey;
padding: 0 10px;
display: inline-block;
margin: 10px 0;
cursor: pointer;
}
.content__wrapper {
background-color: aqua;
padding: 16px;
}
<button class="button" data-for="content_1">content 1</button>
<button class="button" data-for="content_2">content 2</button>
<button class="button" data-for="content_3">content 3</button>
<button class="button" data-for="content_4">content 4</button>
<div class="content__wrapper">
<div class="content content_1">Content 1</div>
<div class="content content_2">Content 2</div>
<div class="content content_3">Content 3</div>
<div class="content content_4">Content 4</div>
</div>

Store the currently selected tab and load it after a page refresh

I have the following code for the tabs:
(function() {
$(function() {
var toggle;
return toggle = new Toggle('.toggle');
});
this.Toggle = (function() {
Toggle.prototype.el = null;
Toggle.prototype.tabs = null;
Toggle.prototype.panels = null;
function Toggle(toggleClass) {
this.el = $(toggleClass);
this.tabs = this.el.find(".tab");
this.panels = this.el.find(".panel");
this.bind();
}
Toggle.prototype.show = function(index) {
var activePanel, activeTab;
this.tabs.removeClass('active');
activeTab = this.tabs.get(index);
$(activeTab).addClass('active');
this.panels.hide();
activePanel = this.panels.get(index);
return $(activePanel).show();
};
Toggle.prototype.bind = function() {
var _this = this;
return this.tabs.unbind('click').bind('click', function(e) {
return _this.show($(e.currentTarget).index());
});
};
return Toggle;
})();
}).call(this);
.toggle {
font-family: arial, sans-serif;
}
.toggle .tabs {
border-bottom: 1px solid grey;
width: 100%;
overflow: hidden;
height: 36px;
line-height: 36px;
}
.toggle .tabs .tab {
float: left;
background: white;
color: #777777;
height: 31px;
margin: 2px 8px 0;
padding: 0 8px;
cursor: pointer;
}
.toggle .tabs .tab.active {
color: #dd4b39;
border-bottom: 3px solid #dd4b39;
}
.toggle .panels .panel {
padding: 20px 10px;
display: none;
}
.toggle .panels .panel:first-child {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='toggle'>
<div class='tabs'>
<div class='tab active'>Tab 1</div>
<div class='tab'>Tab 2</div>
<div class='tab'>Tab 3</div>
<div class='tab'>Tab 4</div>
</div>
<div class='panels'>
<div class='panel'>Panel 1</div>
<div class='panel'>Panel 2</div>
<div class='panel'>Panel 3</div>
<div class='panel'>Panel 4</div>
</div>
</div>
As you can see the above code works just fine.... The only thing I want to add is the ability to store the current selected tab and if a user refreshes/reloads the page I want the same tab containt to appear and not the first tab as it is doing currently.
What do I need to add to the above code in order to achieve this?
There are a number of ways to "save" information between visits to a page.
The old-school (and therefore more broadly browser-supported) way is to use a cookie! I'm sure you've heard of them :-)
The second, more modern, way is to use local storage. There are a number of libraries that can help you manage local storage (search for localForage for one) or you can roll up your own, of course.

Rewrite Show/Hide Multiple Divs form JQ to clear JS

I wrote script in JQuery but I want to write in clear JS.
I can fix my problem if I m going to use onclick event in HTML code for example:
var divs = ["Div1", "Div2", "Div3", "Div4"];
var visibleDivId = null;
function divVisibility(divId) {
if(visibleDivId === divId) {
visibleDivId = null;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for(i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
.buttons a {
font-size: 16px;
}
.buttons a:hover {
cursor:pointer;
font-s
<div class="main_div">
<div class="buttons">
Div1 |
Div2 |
Div3 |
Div4
</div>
<div class="inner_div">
<div id="Div1">I'm Div One</div>
<div id="Div2" style="display: none;">I'm Div Two</div>
<div id="Div3" style="display: none;">I'm Div Three</div>
<div id="Div4" style="display: none;">I'm Div Four</div>
</div>
</div>
But I don't want to mix HTML with JS, and I want to use addEventListener.
My JQ Code below
jQuery(function(){
$('.targetDiv').hide();
jQuery('#showall').click(function(){
jQuery('.targetDiv').toggle();
});
jQuery('.showSingle').click(function(){
jQuery('#div'+$(this).attr('target')).toggle();
});
});
.showSingle{
padding: .9em;
margin: .2em;
border: 1px solid black;
float: left;
}
#showall{
padding: .9em;
margin: .2em;
border: 1px solid black;
float: left;
}
.cnt{
margin-top: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
<a id="showall">All</a>
<a class="showSingle" target="1">Div 1</a>
<a class="showSingle" target="2">Div 2</a>
<a class="showSingle" target="3">Div 3</a>
<a class="showSingle" target="4">Div 4</a>
</div>
<section class="cnt">
<div id="div1" class="targetDiv">Content 1</div>
<div id="div2" class="targetDiv">Content 2</div>
<div id="div3" class="targetDiv">Content 3</div>
<div id="div4" class="targetDiv">Content 4</div>
</section>
I was trying make problem but every solution was failed, I will very thankful for help
So, all the HTML event attributes (onclick) come out and are replaced by DOM object references that hook up event callbacks with .addEventListener().
Since you have dedicated <a> elements in their own parent that show one of a set of dedicated <div> elements within their own parent. We can simply use the index of the clicked <a> as the index of the <div> that needs to be shown.
As for CSS, you should also not use individual styles, but rather just apply or remove a class. This is much simpler and more flexible.
// Get all the <a> elements that will trigger the show/hide code
var anchors = document.querySelectorAll(".buttons > a.showSingle");
// Convert anchors to a proper Array (so .forEach() and other Array methods work)
var anchorsArray = Array.prototype.slice.call(anchors);
// Set up each anchor with a click event handler
anchorsArray.forEach(function(a){
a.addEventListener("click", showHideDiv);
});
// Get reference to the "show all" anchor
var showAll = document.getElementById("showall");
// Set up click event handler for that single anchor
showAll.addEventListener("click", showAllDivs);
// Get all the <div> elements that will need to be shown or hidden
var divs = document.querySelectorAll(".inner_div > div[id^='div']");
// Convert divs to proper array (so .forEach() and other Array methods work)
var divArray = Array.prototype.slice.call(divs);
function showHideDiv(evt) {
// Cancel the link's native click behavior
evt.preventDefault();
evt.stopPropagation();
// Hide all the divs
divArray.forEach(function(d){
// No need to mess with individual style properties. Just apply a pre-existing class
d.classList.add("hidden");
});
// Show the div that was clicked using the index of the anchor
// By removing the "hide" class, the element's style goes back to
// whatever it was without that class.
divs[anchorsArray.indexOf(evt.target)].classList.remove("hidden");
}
function showAllDivs(){
// Show all the divs
divArray.forEach(function(d){
// No need to mess with individual style properties. Just apply a pre-existing class
d.classList.remove("hidden");
});
}
.buttons a {
font-size: 16px;
background-color:#aaf;
transition: .5s;
}
.buttons a:hover {
cursor:pointer;
background-color:#66f;
font-size: 18px;
}
/* This class will either be applied or not to take care of the visibility */
.hidden {
display:none;
}
.showSingle{
padding: .9em;
margin: .2em;
border: 1px solid black;
float: left;
}
#showall{
padding: .9em;
margin: .2em;
border: 1px solid black;
float: left;
}
.cnt{
margin-top: 2em;
}
<div class="main_div">
<div class="buttons">
<a id="showall">All</a>
<a class="showSingle">Div 1</a>
<a class="showSingle">Div 2</a>
<a class="showSingle">Div 3</a>
<a class="showSingle">Div 4</a>
</div>
<section class="cnt">
<div class="inner_div">
<div id="div1">I'm Div One</div>
<div id="div2" class="hidden">I'm Div Two</div>
<div id="div3" class="hidden">I'm Div Three</div>
<div id="div4" class="hidden">I'm Div Four</div>
</div>
</section>
</div>

Adding div dynamically using button click in JavaScript / jQuery

How do I dynamically add div on button click in JavaScript/jQuery?
I want all the formatting of div having class "listing listing_ad job".
This is my code which I tried out, using jQuery.
$('#btnAddtoList').click(function(){
var newDiv = $('<div class="listing listing_ad job"><h4><a>Some text</a></h4> </div>');
//newDiv.style.background = "#000";
document.body.appendChild(newDiv);
});
.listing {
border-bottom: 1px solid #ddd;
float: left;
padding: 0 0 5px;
position: relative;
width: 559px;
}
.listing:hover {
background: #f5f5f5 none repeat scroll 0 0;
border-bottom: 1px solid #ddd;
cursor: wait;
}
a:hover {
color: #ff5050;
}
.subtitle {
width: 430px;
font-weight: normal;
font-size: 12px;
font-family: Arial;
color: #7f7f7f;
}
.info {
float: left;
margin: 10px 15px 5px;
min-width: 500px;
clear: both;
color: #7f7f7f;
margin: 15px 44px 15px 0;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAddtoList">
Add to list
</button>
<div class="listing listing_ad job">
<h4>
<a>
Excellent Opportunity For Internship at Diamond
</a>
</h4>
<div class="subtitle">
Lahore, Punjab
</div>
<div class="info">
This is Info / Description.
</div>
</div>
<!-- ************************ -->
<div class="listing listing_ad job">
<h4>
<!-- Src: http://jobs.mitula.pk/internship-program-lahore-jobs -->
<a>
Excellent Opportunity For Internship at Diamond
</a>
</h4>
<div class="subtitle">
Lahore, Punjab
</div>
<div class="info">
This is Info / Description.
</div>
</div>
Jsfiddle: http://jsfiddle.net/mr4rngbL/3/
Yes, you can - by added jQuery to the script of the document, and wrpping the code in document.ready
$(function() {
$('#btnAddtoList').click(function(){
var newDiv = $('<div class="listing listing_ad job"><h4><a>Some text</a></h4> </div>');
//newDiv.style.background = "#000";
$('body').append(newDiv);
});
});
Example http://jsfiddle.net/mr4rngbL/5/
Example for what you've asked in the comment: http://jsfiddle.net/mr4rngbL/6/
And LAST example based on your request in the comment: http://jsfiddle.net/mr4rngbL/7/
Here Pure JavaScript Solution
function addDiv(parent_div, content, attrs) {
var div = document.createElement('div');
var parent = document.getElementById(parent_div);
for (var key in attrs) {
if (attrs.hasOwnProperty(key)) {
div.setAttribute(key, attrs[key]);
}
}
div.innerHTML = content;
if (parent) {
parent.appendChild(div);
}
}
var button = document.getElementsByTagName('button')[0];
if (button) {
button.addEventListener('click', function() {
// change dynamically your new div
addDiv('parent', 'hi', {
'class': 'someclass someclass',
'data-attr': 'attr'
});
});
}
<button>Add Div</button>
<div id="parent">
</div>
Yes, you can easily add a div on button click in jQuery. First, set up the click listener:
$('button').on('click', addDiv);
Then, create the function to add the div (here, the div is being added to the element with the class of container):
function addDiv() {
$('.container').append('<div>').addClass('listing listing_ad job');
}
I hope this is helpful.

Toggle visibility of 2 divs with 2 buttons

I am having issues with my code
I am trying to show 1 div (show_1) by default and then hide it and show a second div (show_2) when button 2 is clicked. And then when button 1 is clicked hide show_2 and show show_1 again
https://jsfiddle.net/mgzurjgL/4/
It is not working though, nothing happens when I click either buttons.
function switch_div(show_1, show_2) {
var a = document.getElementById(show_1);
var a2 = document.getElementById(show_2);
if (a.style.display == 'block') {
a.style.display = 'block';
a2.style.display = 'none';
} else {
a.style.display = 'none';
a2.style.display = 'block';
}
}
.button {
width: 100px;
height: 30px;
display: inline-block;
background-color: black;
margin: 0 10px 10px 0;
color: #fff;
text-align: center;
line-height: 30px;
cursor: pointer;
}
.button:hover {
background-color: red;
}
.content {
width: 400px;
height: 100px;
display: block;
background-color: gray;
}
.hide {
display: none;
}
<div class="button" onclick="switch_div('show_1', 'show_2');">
1
</div>
<div class="button" onclick="switch_div('show_1', 'show_2');">
2
</div>
<div class="content" id="show_1">
Show by default (and when button 1 is clicked)
</div>
<div class="content hide" id="show_2">
Show this div when button 2 is clicked
</div>
You had your settings wrong in JSFiddle, you need to run the script in the head not onload. Also you passed in the same parameters twice. Also why dont you try something simpler like this.
https://jsfiddle.net/mgzurjgL/5/
function switch_div(show) {
document.getElementById("show_"+show).style.display = "block";
document.getElementById("show_"+((show==1)?2:1)).style.display = "none";
}
.button {
width: 100px;
height: 30px;
display: inline-block;
background-color: black;
margin: 0 10px 10px 0;
color: #fff;
text-align: center;
line-height: 30px;
cursor: pointer;
}
.button:hover {
background-color: red;
}
.content {
width: 400px;
height: 100px;
display: block;
background-color: gray;
}
.hide {
display: none;
}
<div class="button" onclick="switch_div(1);">
1
</div>
<div class="button" onclick="switch_div(2);">
2
</div>
<div class="content" id="show_1">
Show by default (and when button 1 is clicked)
</div>
<div class="content hide" id="show_2">
Show this div when button 2 is clicked
</div>
Two items: script placement and a typo. Working version at JSFiddle, tested in Google Chrome.
The script has to run before the divs. In the JSFiddle Javascript settings, I changed "Load Type" to "No wrap - in <head>." This way the switch_div function exists when the divs are loaded.
There was a typo:
if (a.style.display == 'block')
should be
if (a.style.display == 'none')
Otherwise you are setting block display on an element that's already block :) .
Edit: This code still doesn't do what you appear to want, because the function you have written toggles the div visibility regardless of which button is pressed. What you really want is in this fiddle:
<div class="button" onclick="switch_div('show_1', 'show_2', true);">
and
<div class="button" onclick="switch_div('show_1', 'show_2', false);">
together with
function switch_div(show_1, show_2, should_show_1) {
var a = document.getElementById(show_1);
var a2 = document.getElementById(show_2);
if(should_show_1) {
a.style.display = 'block';
a2.style.display = 'none';
}
else {
a.style.display = 'none';
a2.style.display = 'block';
}
}
That way you get only the div you want.
You need to switch the statements in if-else or change the condition in the if to "if (a.style.display !== 'block') "
When a.style.display is 'block' then you have to set it to 'none' to hide it.
function switch_div(show_1, show_2) {
var a = document.getElementById(show_1);
var a2 = document.getElementById(show_2);
if (a.style.display !== 'block') {
a.style.display = 'block';
a2.style.display = 'none';
} else {
a.style.display = 'none';
a2.style.display = 'block';
}
}
.button {
width: 100px;
height: 30px;
display: inline-block;
background-color: black;
margin: 0 10px 10px 0;
color: #fff;
text-align: center;
line-height: 30px;
cursor: pointer;
}
.button:hover {
background-color: red;
}
.content {
width: 400px;
height: 100px;
display: block;
background-color: gray;
}
.hide {
display: none;
}
<div class="button" onclick="switch_div('show_1', 'show_2');">
1
</div>
<div class="button" onclick="switch_div('show_1', 'show_2');">
2
</div>
<div class="content" id="show_1">
Show by default (and when button 1 is clicked)
</div>
<div class="content hide" id="show_2">
Show this div when button 2 is clicked
</div>
I changed the js function and the "call" for buttons.
function switch_div(show_1, show_2) {
var a = document.getElementById(show_2);
var a2 = document.getElementById(show_1);
a.style.display = 'none';
a2.style.display = 'block';
}
.button {
width: 100px;
height: 30px;
display: inline-block;
background-color: black;
margin: 0 10px 10px 0;
color: #fff;
text-align: center;
line-height: 30px;
cursor: pointer;
}
.button:hover {
background-color: red;
}
.content {
width: 400px;
height: 100px;
display: block;
background-color: gray;
}
.hide {
display: none;
}
<div class="button" onclick="switch_div('show_1', 'show_2');">
1
</div>
<div class="button" onclick="switch_div('show_2', 'show_1');">
2
</div>
<div class="content" id="show_1">
Show by default (and when button 1 is clicked)
</div>
<div class="content hide" id="show_2">
Show this div when button 2 is clicked
</div>
This also works with:
<div class="button" onclick="switch_div(1,2);">
1
</div>
<div class="button" onclick="switch_div(2,1);">
2
</div>
<div class="content" id="show_1">
Show by default (and when button 1 is clicked)
</div>
<div class="content hide" id="show_2">
Show this div when button 2 is clicked
</div>
<script>
function switch_div(n1,n2) {
document.getElementById("show_"+n1).style.display = 'block';
document.getElementById("show_"+n2).style.display = 'none';
}
</script>

Categories