CSS position issue when parent element has overflow hidden - javascript

In the below code snippet, on clicking the <div class="inner">Some Text</div> will show up a overlay element. Inside overlay element, on clicking the span element with class popoutTerm will show up the popoutDialog element.
The issue is popoutDialog element is not fully visible, only partially portion of what ever it can display inside the overlay element is visible. I understood that the issue is due to overflow property applied to overlay element. But the requirement is overlay element should be scrollable if it has more content and popoutDialog element should be relative to popoutTerm element.
Please help me to understand and resolve it. Thanks in advance.
HTML Code
<body>
<div style="height:300px;border:1px solid red">Sample Content</div>
<div class="outer">
<div> A </div>
<div> B </div>
<div> C </div>
<div class="inner">Some Text</div>
<div class="overlay">Overlay <span class="popoutTerm">Content <div class="popoutDialog"> popout content </div></span> to display</div>
<div>D</div>
</div>
</div>
<script>
let outerElement = document.querySelector('.outer');
let innerElement = document.querySelector('.inner');
let overlayElement = document.querySelector('.overlay');
let popoutTermElement = document.querySelector('.popoutTerm');
let popoutDialogElement = document.querySelector('.popoutDialog');
innerElement.onclick = function (e) {
console.log('click called');
overlayElement.style.display = 'block';
overlayElement.style.position = 'absolute';
overlayElement.style.top = '50px';
overlayElement.style.left = '50px';
e.stopPropagation();
}
popoutTermElement.onclick = function () {
popoutDialogElement.style.display = 'block';
}
</script>
</body>
CSS Code
.outer {
height: 700px;
border: 1px solid black;
position: relative;
}
.inner {
cursor: pointer;
border: 1px solid blue;
height: 200px;
}
.overlay {
display:none;
height: 500px;
width: 300px;
background-color: green;
color: white;
overflow: auto;
}
.popoutTerm {
color: orange;
cursor: pointer;
position: relative;
}
.popoutDialog {
background-color: red;
color: white;
height: 100px;
width: 100px;
display: none;
position: absolute;
top: -50px;
left: 50px;
}
https://jsfiddle.net/a6v04bLr/

Issue is due to top: -50px; change the value as -10px
.outer {
height: 700px;
border: 1px solid black;
position: relative;
}
.inner {
cursor: pointer;
border: 1px solid blue;
height: 200px;
}
.overlay {
display:flex;
height: 500px;
width: auto;
background-color: green;
color: white;
overflow: auto;
}
.popoutTerm {
color: orange;
cursor: pointer;
position: relative;
}
.popoutDialog {
background-color: red;
color: white;
height: 100px;
width: 100px;
display: none;
position: absolute;
top: -10px;
left: 40px;
}
<!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>WonderWoman</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div style="height:300px;border:1px solid red">Sample Content</div>
<div class="outer">
<div> A </div>
<div> B </div>
<div> C </div>
<div class="inner">Some Text</div>
<div class="overlay">Overlay <span class="popoutTerm">Content <div class="popoutDialog"> popout content </div></span> to display</div>
<div>D</div>
</div>
</div>
<script>
let outerElement = document.querySelector('.outer');
let innerElement = document.querySelector('.inner');
let overlayElement = document.querySelector('.overlay');
let popoutTermElement = document.querySelector('.popoutTerm');
let popoutDialogElement = document.querySelector('.popoutDialog');
innerElement.onclick = function (e) {
console.log('click called');
overlayElement.style.display = 'block';
overlayElement.style.position = 'absolute';
overlayElement.style.top = '50px';
overlayElement.style.left = '50px';
e.stopPropagation();
}
popoutTermElement.onclick = function () {
popoutDialogElement.style.display = 'block';
}
</script>
</body>
</html>

Related

How can I remove class when click the same button

Please see code below:
const sectionIcon = document.querySelectorAll(".nk-section-icons")
const sectionContainer = document.querySelectorAll(".nk-sec-container")
const sectionIconHover = document.querySelectorAll(".nk-section-icons")
sectionIcon.forEach((sectionBtn)=> {
sectionBtn.addEventListener("click", (btns)=> {
// console.log(sectionIconHover)
const containerTarget = btns.currentTarget.parentElement.children[1]
const containerHoverTarget = btns.currentTarget.parentElement.children[0]
sectionContainer.forEach(items => {
if(items !== containerTarget) {
items.classList.remove("show")
// itemHover.classList.remove("rb")
}
})
sectionIconHover.forEach(itemHover => {
if(itemHover !== containerHoverTarget) {
itemHover.classList.remove("rb")
}
})
containerTarget.classList.toggle("show")
containerHoverTarget.classList.add("rb")
})
})
.nk-section-icons {
height: 30px;
min-width: 30px;
width: 30px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
border-radius: 3px;
background: yellow;
margin-bottom: 5px;
}
.nk-section-icons.rb {
background: black;
}
.nk-sec-container {
width: 300px;
min-width: 300px;
height: 100%;
background: red;
position: absolute;
z-index: 11;
box-shadow: rgba(17, 17, 26, 0.1) 0px 0px 16px;
border-radius: 6px;
left: 70px;
top: 0px;
}
.nk-sec-container.show {
background: green;
}
.nk-section-icons-container {
position: relative;
}
<div class="nk-section-l-icons">
<div class="nk-section-icons-container">
<div class="nk-section-icons fav" data-title="Favorites">btn</div>
<div class="nk-sec-container nk-sec-fav-c">
</div>
</div>
<div class="nk-section-icons-container">
<div class="nk-section-icons recent" data-title="Recent">btn</div>
<div class="nk-sec-container nk-sec-recent-c">
</div>
</div>
<div class="nk-section-icons-container">
<div class="nk-section-icons notifs" data-title="Notifications">btn</div>
<div class="nk-sec-container nk-sec-notif-c">
</div>
</div>
</div>
Hello guys, can you please see my code? Currently, it's working fine when I click the button it's working the classes are moved when I click any of the buttons. However, if I tried clicking the same button again the class rb is not removed but the show class is removed. Can you please help me with how can I fix this? Thanks
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
if($("p").hasClass("main"))
{
$("p").toggleClass("main1");
}
else
{
$("p").toggleClass("main");
}
});
});
</script>
<style>
.main {
font-size: 120%;
color: red;
}
.main1 {
font-size: 120%;
color: green;
}
</style>
</head>
<body>
<button>Toggle class "main" for p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p><b>Note:</b> Click the button more than once to see the toggle effect.</p>
</body>
</html>
Use toggling: Toggle between adding and removing the "main" class name for all elements
The toggleClass() method toggles between adding and removing one or more class names from the selected elements.

when click on the one dropdown other dropdown will be close

I created a dropdown list Javascript Toggle method. I face a problem a problem. The problem is - After clicking one dropdown, another dropdown still opens. I want others dropdown Will to be closed when I click on dropdown. This happen will be each dropdown. How do I do it?
<html>
<head>
<style>
nav{
width:100%;
height:50px;
background-color:#000;
}
button{
height:50px;
margin-left: 10px;
border:0;
background-color: transparent;
color: #fff;
cursor: pointer;
}
div{
display: none;
width: 100%;
height: 300px;
position: absolute;
}
#myDIV1{
background-color: rgb(0,0,255);
color: #fff;
}
#myDIV2{
background-color: rgb(0,255,0);
color: #000;
}
.show{
display:block;
}
</style>
</head>
<body>
<nav>
<button onclick="myFunction1()">Dropdown1</button>
<button onclick="myFunction2()">Dropdown2</button>
</nav>
<div id="myDIV1">
This Dropdown for Dropdown 1
</div>
<div id="myDIV2">
This Dropdown for dropdown 2
</div>
<script>
function myFunction1() {
var element = document.getElementById("myDIV1");
element.classList.toggle("show");
}
function myFunction2() {
var element = document.getElementById("myDIV2");
element.classList.toggle("show");
}
</script>
</body>
</html>
here is the solution, all the code is commented.
div1 and div2 are hidden by default...
so with .toggle(): https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle
I will add the class .show if there isn't
else I will remove the class from it.
so if the user clicks the first time on the button it will show the div1 then if he reclicked will hide, and this is looped (if he reclick)...
with classList.remove, we will hide the other element (always):
if clicked the button N1 will hide div2
if clicked the button N2 will hide div1
let div1 = document.getElementById("myDIV1");
let div2 = document.getElementById("myDIV2");
function myFunction1() {
div1.classList.toggle("show");
// remove the class for the second div
div2.classList.remove("show");
}
function myFunction2() {
div2.classList.toggle("show");
// remove the class for the first div
div1.classList.remove("show");
}
nav {
width: 100%;
height: 50px;
background-color: #000;
}
button {
height: 50px;
margin-left: 10px;
border: 0;
background-color: transparent;
color: #fff;
cursor: pointer;
}
div {
display: none;
width: 100%;
height: 300px;
position: absolute;
}
#myDIV1 {
background-color: rgb(0, 0, 255);
color: #fff;
}
#myDIV2 {
background-color: rgb(0, 255, 0);
color: #000;
}
/* this is the class we add and remove or toggle with javascript*/
.show {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="./script.js" defer></script>
</head>
<body>
<!-- navbar -->
<nav>
<button onclick="myFunction1()">Dropdown1</button>
<button onclick="myFunction2()">Dropdown2</button>
</nav>
<!-- 1 -->
<div id="myDIV1">
This Dropdown for Dropdown 1
</div>
<!-- 2 -->
<div id="myDIV2">
This Dropdown for dropdown 2
</div>
</body>
</html>
You can make this a little easier to scale by using one function for all dropdown menus. This function closes all open drop-downs and toggles the target one.
function toggleDropDown(id) {
document.querySelectorAll('.dropdown-menu').forEach(el => el.id === id ? el.classList.toggle('show') : el.classList.remove("show"));
}
function toggleDropDown(id) {
document.querySelectorAll('.dropdown-menu').forEach(el => el.id === id ? el.classList.toggle('show') : el.classList.remove("show"));
}
nav {
width: 100%;
height: 50px;
background-color: #000;
}
button {
height: 50px;
margin-left: 10px;
border: 0;
background-color: transparent;
color: #fff;
cursor: pointer;
}
.dropdown-menu {
display: none;
width: 100%;
height: 300px;
position: absolute;
}
#myDIV1 {
background-color: rgb(0, 0, 255);
color: #fff;
}
#myDIV2 {
background-color: rgb(0, 255, 0);
color: #000;
}
.show {
display: block;
}
<nav>
<button onclick="toggleDropDown('myDIV1')">Dropdown1</button>
<button onclick="toggleDropDown('myDIV2')">Dropdown2</button>
</nav>
<div class='dropdown-menu' id="myDIV1">
This Dropdown for Dropdown 1
</div>
<div class='dropdown-menu' id="myDIV2">
This Dropdown for dropdown 2
</div>
Here is the same thing, but instead of hard-coding click events, it's better practice to use eventListeners, which get applied through the script after the page loads, like:
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('nav button').forEach(button => {
button.addEventListener('click', e => {
let id = e.target.dataset.dropdown
document.querySelectorAll('.dropdown-menu').forEach(el => el.id === id ? el.classList.toggle('show') : el.classList.remove("show"));
})
})
})
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('nav button').forEach(button => {
button.addEventListener('click', e => {
let id = e.target.dataset.dropdown
document.querySelectorAll('.dropdown-menu').forEach(el => el.id === id ? el.classList.toggle('show') : el.classList.remove("show"));
})
})
})
nav {
width: 100%;
height: 50px;
background-color: #000;
}
button {
height: 50px;
margin-left: 10px;
border: 0;
background-color: transparent;
color: #fff;
cursor: pointer;
}
.dropdown-menu {
display: none;
width: 100%;
height: 300px;
position: absolute;
}
#myDIV1 {
background-color: rgb(0, 0, 255);
color: #fff;
}
#myDIV2 {
background-color: rgb(0, 255, 0);
color: #000;
}
.show {
display: block;
}
<nav>
<button data-dropdown="myDIV1">Dropdown1</button>
<button data-dropdown="myDIV2">Dropdown2</button>
</nav>
<div class='dropdown-menu' id="myDIV1">
This Dropdown for Dropdown 1
</div>
<div class='dropdown-menu' id="myDIV2">
This Dropdown for dropdown 2
</div>

How can I add a tooltip when mouse is over an item?

I want wen I click on first paragraph, the element with id « envoie » shows up as a tooltip and disappear when mouse leave.
What I have is the tooltip is display une the first element. I mean when I click on the last « first element », the tooltip is still under the first element.
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
border: 1px solid black;
margin: 5px;
}
.envoie-fr, .ship-fr {
margin-top: -25px;
opacity: 1;
z-index: 2000;
visibility: visible;
.transition(all 0.1s linear);
}
</style>
<script>
window.addEventListener("load", () => {
var x = document.querySelectorAll("#envoie");
console.log(x.length);
});
</script>
</head>
<body>
<div>
<div>
<p class="#envoie">First Paragraph</p>
<div id="envoie" class="envoie-fr">Envoie</div>
</div>
<div>
<p class="#ship">Second Paragraph</p>
<div id="ship" class="ship-fr">Ship</div>
</div>
</div>
<hr />
<div>
<div>
<p class="#envoie">First Paragraph</p>
<div id="envoie" class="envoie-fr">Envoie</div>
</div>
<div>
<p class="#ship">Second Paragraph</p>
<div id="ship" class="ship-fr">Ship</div>
</div>
</div>
<div>
<p class="#example" style="margin-top:50px">Bottom</p>
</div>
</body>
</html> ```
var myDiv = document.getElementById('foo');
myDiv.onmouseenter = function() {
// do your stuff to show element like display:block;
alert('entered');
}
myDiv.onmouseout = function() {
// do your stuff to hide element like display:none;
alert('left');
}
You can use the title tag as a tooltip to the HTML element.
You do not need any script to make that happened. Also, from your issue title I can tell that you want the tooltip be displayed on hover (not on click) and disappeared when the mouse is away (this is how actually tooltips work). So, here is the code for you:
<!DOCTYPE html>
<html>
<head>
<style>
body {
/*optional: these are to make the content centered*/
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
div {
/*optional*/
border: solid 1px #f9cd23;
padding: 30px;
}
p {
padding: 0;
cursor: pointer;
position: relative;
margin: 40px 0;
}
/*for the tooltip box*/
p:hover:after {
position: absolute;
bottom: 30px;
left: 50%;
transform: translateX(-50%);
background: #f9cd23;
border-radius: 8px;
color: black;
content: attr(title);
text-align: center;
font-size: 16px;
padding: 8px;
width: 200px;
}
/*for the tooltip triangle*/
p:hover:before {
left: 50%;
transform: translateX(-50%);
top: -20px;
position: absolute;
border: solid;
border-color: #f9cd23 transparent;
border-width: 15px 15px 0 15px;
content: '';
}
</style>
</head>
<body>
<div>
<p title="This is the first paragraph tooltip...">First Paragraph</p>
<p title="This is the second paragraph tooltip...">Second Paragraph</p>
</div>
</body>
</html>

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>

JavaScript - Swap colors

In this JavaScript example when user clicks on 'Change colors' button, it need to swap colors of two div elements. But it doesn't.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
#first
{
border-radius: 100%;
background-color: red;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
#second
{
border-radius: 100%;
background-color: green;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
</style>
</head>
<body>
<button id="color">Change colors</button>
<br />
<div id="first">Random text.</div>
<div id="second">Random text.</div>
<div id="third"></div>
<script type="text/javascript">
document.getElementById('color').onclick = function () {
var divColor = document.getElementById('first').style.backgroundColor;
document.getElementById('first').style.backgroundColor = document.getElementById('second').style.backgroundColor.toString();
document.getElementById('second').style.backgroundColor = divColor.toString();
}
</script>
</body>
</html>
But when I change it a little bit and remove 'background-color' from <style> and put it within <div> then it's working.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<style>
#first
{
border-radius: 100%;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
#second
{
border-radius: 100%;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
</style>
</head>
<body>
<button id="color">Change colors</button>
<br />
<div id="first" style="background-color: red;">Random text.</div>
<div id="second" style="background-color: green;">Random text.</div>
<script type="text/javascript">
document.getElementById('color').onclick = function () {
var divColor = document.getElementById('first').style.backgroundColor;
document.getElementById('first').style.backgroundColor = document.getElementById('second').style.backgroundColor.toString();
document.getElementById('second').style.backgroundColor = divColor.toString();
}
</script>
</body>
</html>
So is there any way to make it works for solution when 'background-color' is within <style> in <head>?
Element.style only applies to styles within the style attribute of the element. If you want the computed style, which factors in stylesheets and the like...
var firstElem = document.getElementById('first'),
secondElem = document.getElementById('second'),
firstBackground = window.getComputedStyle(firstElement).backgroundColor,
secondBackground = window.getComputedStyle(secondElement).backgroundColor;
firstElem.style.backgroundColor = secondBackground;
secondElem.style.backgroundColor = firstBackground;
This should swap the two colours, regardless of where they are defined.
For this case it whould be more common to use 3 classes in css. One for defining the common style of the divs. And two for defining the differences. Switching the appearance in that case whould just require switching of classes. Such a set-up is far more flexible also for example in combination with annimations.
A way to alter style using Javascript, without inline styling:
https://jsfiddle.net/6tyw211s/10/
<html>
<style>
#first
{
border-radius: 100%;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
#second
{
border-radius: 100%;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
float: left;
margin: 5px;
}
.color{
background-color: red;
}
.color1{
background-color: green;
}
</style>
<body>
<input type="button" id="color" value="Change colors" />
<br />
<div id="first">Random text.</div>
<div id="second">Random text.</div>
<div id="third"></div>
</body>
<script>
var y= document.getElementById('color');
var f=document.getElementById('first');
var s=document.getElementById('second');
y.addEventListener('click', function(){
if (f.className === "color1") {
f.className = "color";
}
else {
f.className = "color1";
}
if(s.className==="color"){
s.className="color1";
}
else{
s.className="color";
}
})
</script>
</html>
You can use switchClass() in jqueryui to do it.
That way, you don't have to specify the background-color values to the divs.
$("#color").click(function myFunction() {
$(".first").switchClass("first", "second", 200, "easeInOutQuad");
$(".second").switchClass("second", "first", 200, "easeInOutQuad");
});
Here is a working version with jqueryui
http://api.jqueryui.com/switchclass/

Categories