Event propagation and function that works only on the first div - html

I have a multiple div with texts. I have a function that on click (in each part of the screen) change background color and slides text with the next. I also wanted a copy to clipboard button for each poetry and an alert that return a message with "author" returned.
I succeded on click to copy and return the alert message but it applies only to the first div. What is the problem? Is there also a problem of event propagation?
This is the code. I hope someone could give me an insight! Thanks in advance, I'm a newbie :D
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container{
position: relative;
width: auto;
height: 700px;}
.mySlides{
position: absolute;padding: 15px;
top: 50%; left: 50%;
transform: translate(-50%,-50%);
min-width: 50px;
min-height: 50px;
}
body {
transition: background-color 0.5s ease;
}
p {
font-size: 30px;
text-align: left;
color:white;
font-family: 'Baskerville';
}
.author {
padding-top:50px !important;
text-align: right;
}
</style>
</head>
<body>
<div id="btn" class="totale">
<div id="btn" class="container">
<div id="bottone" class="mySlides"><p>Text1</p><p class="author">Author1</p><button type="button" onclick="CopyToClipboard('bottone','author')">Copy text</button></div>
<div id="bottone" class="mySlides"><p>Text2</p><p class="author">Author2</p><button type="button" onclick="CopyToClipboard('bottone','author')">Copy text</button></div>
<div id="bottone" class="mySlides"><p>Text3</p><p class="author">Author3</p><button type="button" onclick="CopyToClipboard('bottone','author')">Copy text</button></div>
</div>
</div>
<script>
/*FUNCTION CHANGE BACKGROUND COLOR AND SLIDES */
var slideIndex = 1;
showSlides(slideIndex);
const button = document.getElementById("btn");
const body = document.body;
const colors = ['#3141AD','#FF9964','#00BAA4','#DF4D44','#514399','#015CCA']
body.style.backgroundColor = colors[0]
button.addEventListener('click',() => {
changeBackground();
plusSlides(1);
});
function changeBackground(){
const colorsIndex = Math.floor(Math.random()*colors.length)
body.style.backgroundColor = colors[colorsIndex]
}
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slides[slideIndex-1].style.display = "block";
}
/*FUNCTION COPY TEXT*/
function CopyToClipboard(id){
var r = document.createRange();
r.selectNode(document.getElementById(id));
var q = document.createRange();
q.selectNode(document.getElementById('author'));
window.getSelection().removeAllRanges();
window.getSelection().addRange(r);
try {
document.execCommand('copy');
window.getSelection().removeAllRanges();
alert('Text copied! ' +q +' will thank you');
} catch (err) {
console.log('Unable to copy!');
}
}
</script>
</body>
</html> ```

You have multiple id values that are the same. ids need to be unique across the whole document. Since you are doing document.getElementById(id) you are only returning the first element that matches the id passed.
I would refactor that function, and make use of the event.target, which is a parameter that gets passed to all events, such as "click".
Change buttons to pass in the event to copyToClipboard.
<div id="btn" class="totale">
<div id="btn" class="container">
<div id="bottone" class="mySlides">
<p>Text1</p>
<p class="author">Author1</p>
<button type="button" onclick="copyToClipboard(event)">Copy text</button>
</div>
<div id="botttwo" class="mySlides">
<p>Text2</p>
<p class="author">Author2</p>
<button type="button" onclick="copyToClipboard(event)">Copy text</button>
</div>
<div id="bottthree" class="mySlides">
<p>Text3</p>
<p class="author">Author3</p>
<button type="button" onclick="copyToClipboard(event)">Copy text</button>
</div>
</div>
</div>
And in the function, I change it to camelCase, because PascalCase is loosely reserved for Objects, or other framework specific modules.
Also, you were calling getElementById on "authors", but again, the same problem as before, except this time, those elements have the class of "authors", not id, so it's ok to have more than one per page.
I changed the lookup for authors by using the e.target.previousElementSibling since the author element is just above the button in document order.
function copyToClipboard(e) {
var r = document.createRange()
r.selectNode(e.target)
var q = document.createRange()
q.selectNode(e.target.previousElementSibling())
window.getSelection().removeAllRanges()
window.getSelection().addRange(r)
try {
document.execCommand("copy")
window.getSelection().removeAllRanges()
alert("Text copied! " + q + " will thank you")
} catch (err) {
console.log("Unable to copy!")
}
}

Related

how to make a loading animation with my code

I can't seem to figure out how to make the boxes rotate. I tried transformation, JS, and even html special code. I do suck at CSS, so this is my code so far:
<!DOCTYPE html>
<html>
<head>
<script>
//great code from Scriptkiddy1337 on stack overflow
const pageStack=[];
function getParameterByName(name, url) {
url = url || window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
window.addEventListener('load', function (e) {
var templates = document.getElementsByClassName('sitecontent');
for (var i = 0, v; v = templates[i]; i++) {
for (var j = 0, x; x = v.childNodes[j]; j++) {
if (x.nodeType === Node.ELEMENT_NODE) {
pageStack.push(x);
}
}
}
var pageIndex = getParameterByName('page') || '0';
loadPage(pageIndex);
});
function loadPage(index) {
if (index >= pageStack.length || index < 0) {
document.body.innerText = '404 Page not found';
return;
}
document.body.innerHTML = '';
document.body.appendChild(pageStack[index]);
}
</script>
<style>
box{
transition: 3s;
width:50px;
height:50px;
position:fixed;
transform:/*im confused here*/;
}
</style>
</head>
<body>
<pageholder class="sitecontent">
<page>
<animator>
<!--I want them to rotate in a circle-->
<box style="background-color:red">.</box><br><br><br>
<box style="background-color:red">.</box><br><br><br>
<box style="background-color:red">.</box><br><br><br>
</animator>
Next Page
</page>
<page>
<h1>Homepage</h1>
<hr>
<p>Need help :(</p>
</page>
</pageholder>
</body>
</html>
I tried to transform CSSstuff, JS animations (which I also kinda suck at), and even special HTML code. I might be missing something, but as far as I know (which isn't a lot, unfortunately), I have done nearly everything I can think of.
I would highly recommend you read up on CSS Animations
<style>
/* The animation code */
#keyframes rotateBox {
to {transform: rotate(360deg)}
}
box{
transition: 3s;
width: 50px;
height: 50px;
position: fixed;
/* Use the animation here */
animation: rotateBox 3s;
}
</style>

HTML - Resize multiple divs and their content

I am looking to create a bottom pannel with a resizable height. The top pannel consists of 2 divs with a resizable width. I was able to follow this https://htmldom.dev/create-resizable-split-views/ , but the vertical resizing is not resizing the contents of the two top divs. How can I fill the contents of the top container with the contents of the two Divs, to ensure that they resize when the bottom pannel is dragged up?
In other words, I'm looking for two top horizontally resizable pannels and one bottom pannel vertically resizable from them, while shrinking/expanding the contents during resize.
Edit: The bottom container needs to be set on all tabs and show up under all tab content on the page.
<div class="container">
<div class = "container__top">
<div class="tab-content" >
<body class="noscroll">
<div class="Tab1">
<div class="main-body">
<div class="page-wrapper">
<div class="row">
<div class="col-sm-12">
<div class="container__left">
STUFF</div>
<div class="resizer" data-direction="horizontal"></div>
<div class="container__right">
STUFF</div>
</div>
</div>
</div>
</div>
<div class="Tab2"></div>
</body>
</div>
</div>
<div class="resizer" data-direction="vertical"></div>
<div class = "container__bottom">
STUFF</div>
You could try something like this. You'll have to be explicit for a few things, like parent height and the min/max heights for top and bottom sections, but this could be a decent start. It's ugly, sorry.
edit: it's still ugly, and you'll have to fix up the tab/hide function for more tabs, but this works as intended as far as I can tell.
document.addEventListener('DOMContentLoaded', function() {
const resizable = function(resizer) {
const direction = resizer.getAttribute('data-direction') || 'horizontal';
const prevSibling = resizer.previousElementSibling;
const nextSibling = resizer.nextElementSibling;
// The current position of mouse
let x = 0;
let y = 0;
let prevSiblingHeight = 0;
let prevSiblingWidth = 0;
// Handle the mousedown event
// that's triggered when user drags the resizer
const mouseDownHandler = function(e) {
// Get the current mouse position
x = e.clientX;
y = e.clientY;
const rect = prevSibling.getBoundingClientRect();
prevSiblingHeight = rect.height;
// Attach the listeners to `document`
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
};
const mouseMoveHandler = function(e) {
// How far the mouse has been moved
const dx = e.clientX - x;
const dy = e.clientY - y;
const parentHeight = resizer.parentNode.getBoundingClientRect().height;
const h = (prevSiblingHeight + dy)
prevSibling.style.height = `${h}px`;
nextSibling.style.height = `${parentHeight - h}px`;
const cursor = 'row-resize';
resizer.style.cursor = cursor;
document.body.style.cursor = cursor;
prevSibling.style.userSelect = 'none';
prevSibling.style.pointerEvents = 'none';
nextSibling.style.userSelect = 'none';
nextSibling.style.pointerEvents = 'none';
};
const mouseUpHandler = function() {
resizer.style.removeProperty('cursor');
document.body.style.removeProperty('cursor');
prevSibling.style.removeProperty('user-select');
prevSibling.style.removeProperty('pointer-events');
nextSibling.style.removeProperty('user-select');
nextSibling.style.removeProperty('pointer-events');
// Remove the handlers of `mousemove` and `mouseup`
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};
// Attach the handler
resizer.addEventListener('mousedown', mouseDownHandler);
};
// Query all resizers
document.querySelectorAll('.resizer').forEach(function(ele) {
resizable(ele);
});
// Query the element
const horizontalResizer = document.getElementById('dragMeHorizontal');
const leftSide = horizontalResizer.previousElementSibling;
const rightSide = horizontalResizer.nextElementSibling;
// The current position of mouse
let x = 0;
let y = 0;
let leftWidth = 0;
// Handle the mousedown event
// that's triggered when user drags the resizer
const mouseDownHandler = function(e) {
// Get the current mouse position
x = e.clientX;
y = e.clientY;
leftWidth = leftSide.getBoundingClientRect().width;
// Attach the listeners to `document`
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
};
const mouseMoveHandler = function(e) {
// How far the mouse has been moved
const dx = e.clientX - x;
const dy = e.clientY - y;
const newLeftWidth = ((leftWidth + dx) * 100) / horizontalResizer.parentNode.getBoundingClientRect().width;
leftSide.style.width = `${newLeftWidth}%`;
horizontalResizer.style.cursor = 'col-resize';
document.body.style.cursor = 'col-resize';
leftSide.style.userSelect = 'none';
leftSide.style.pointerEvents = 'none';
rightSide.style.userSelect = 'none';
rightSide.style.pointerEvents = 'none';
};
const mouseUpHandler = function() {
horizontalResizer.style.removeProperty('cursor');
document.body.style.removeProperty('cursor');
leftSide.style.removeProperty('user-select');
leftSide.style.removeProperty('pointer-events');
rightSide.style.removeProperty('user-select');
rightSide.style.removeProperty('pointer-events');
// Remove the handlers of `mousemove` and `mouseup`
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};
// Attach the handler
horizontalResizer.addEventListener('mousedown', mouseDownHandler);
});
// Tab Changer
function changeActiveTab(tabNumber) {
const allOtherTabs = document.getElementsByClassName("tab")
const hideElements = [...allOtherTabs].filter((element, index) => index !== tabNumber)
const selectedTab = document.getElementsByClassName("tab")[tabNumber]
hideElements.forEach(element => element.classList.add("hidden"));
selectedTab.classList.remove("hidden");
}
// handle tab 1 select
document.getElementById("tab1").addEventListener('mousedown', () => {
changeActiveTab(0)
})
// handle tab 2 select
document.getElementById("tab2").addEventListener('mousedown', () => {
changeActiveTab(1)
})
// handle tab 3 select
document.getElementById("tab3").addEventListener('mousedown', () => {
changeActiveTab(2)
})
.resizer[data-direction='vertical'] {
background-color: #cbd5e0;
cursor: ns-resize;
height: 10px;
width: 100%;
}
.button__container {
margin: 6px 12px;
display: flex;
flex-direction: row;
}
.tab__internal {
max-height: 18%;
}
button {
background-color: orange;
border: none;
padding: 8px;
min-width: 150px;
margin: 1px;
border: 1px solid teal;
}
.main__container {
display: flex;
flex-direction: column;
justify-content: center;
border: 1px solid blue;
}
.sub__container {
height: 250px;
/* Misc */
}
#tab__2 {
background-color: green;
}
#tab__3 {
background-color: teal;
}
.container__top {
/* Initial height */
height: 100%;
/* Misc */
display: flex;
flex-direction: row;
background-color: green;
}
.hidden {
display: none;
}
.tabs__container {
background-color: blue;
height: 100px;
max-height: calc(100% - 100px);
min-height: 50px;
}
.tab__contents {
height: 100%;
}
.container__bottom {
/* Take the remaining height */
width: 100%;
height: 150px;
min-height: 100px;
max-height: calc(100% - 50px);
/* Misc */
display: flex;
flex-direction: column;
background-color: red;
}
.container__left {
width: 50%;
height: 100%;
/* Misc */
display: flex;
background-color: goldenrod;
}
.resizer__horizontal {
background-color: #cbd5e0;
cursor: ew-resize;
height: 100%;
width: 5px;
}
.container__right {
/* Take the remaining width */
flex: 1;
height: 100%;
/* Misc */
display: flex;
background-color: purple;
}
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML DOM - Create resizable split views</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="/css/demo.css" />
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter&family=Source+Code+Pro&display=swap" />
</head>
<body>
<div class="main__container">
<h3>Main Container</h3>
<div class="button__container">
<button class="tab_selector" id="tab1">Tab 1</button>
<button class="tab_selector" id="tab2">Tab 2</button>
<button class="tab_selector" id="tab3">Tab 3</button>
</div>
</div>
<div class="sub__container">
<div class="tabs__container">
<div class="container__top tab" id="tab__1">
<div class="container__left">
<div class="tab__contents">
<div class="tab__internal">stuff</div>
<div class="tab__internal">stuff</div>
<div class="tab__internal">stuff</div>
<div class="tab__internal">stuff</div>
</div>
</div>
<div class="resizer__horizontal" id="dragMeHorizontal"></div>
<div class="container__right tab__contents">Right</div>
</div>
<div class="container__top tab hidden" id="tab__2">
<div class="tab-contents">Tab 2</div>
</div>
<div class="container__top tab hidden" id="tab__3">
<div class="tab-contents">Tab </div>
</div>
</div>
<div class="resizer" data-direction="vertical"></div>
<div class="container__bottom">
<h4>Bottom</h4>
<p>Stuff up in here.</p>
</div>
</div>
</body>
</html>

Div showing on clicking button twice in the initial state

In the very initial state, I need to click on Read More button TWICE to have the content below show. Weird - how do i fix this problem? I only want to click on Read More button once to show the content underneath it.
function myFunction() {
var x = document.getElementById("myDIV");
var btnText = document.getElementById("myBtn");
if (x.style.display === "none") {
x.style.display = "block";
btnText.innerHTML = "Read less";
} else {
x.style.display = "none";
btnText.innerHTML = "Read More";
}
}
#myDIV {
display: none;
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>
<div id="myDIV">
This is my DIV element.
</div>
<button onclick="myFunction()" id="myBtn">Read More</button>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
You should include a check if myDiv's display style is empty.
function myFunction() {
var x = document.getElementById("myDIV");
var btnText = document.getElementById("myBtn");
if (x.style.display === "none" || x.style.display === "") { // notice this line
x.style.display = "block";
btnText.innerHTML = "Read less";
} else {
x.style.display = "none";
btnText.innerHTML = "Read More";
}
}
#myDIV {
display: none;
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>
<div id="myDIV">
This is my DIV element.
</div>
<button onclick="myFunction()" id="myBtn">Read More</button>
<p>
<b>Note:</b> The element will not take up any space when the display property set to "none".
</p>
The reason it's working on two clicks is that the DOM is ready but the script does not knows that the div's style is display: none.
There are two ways you can fix this:
Using window.getComputedStyle()
The Window.getComputedStyle() method returns an object containing the values of all CSS properties of an element, after applying active stylesheets and resolving any basic computation those values may contain.
This way it will ensure that content will show in one click.
Demo:
function myFunction() {
var x = document.getElementById("myDIV");
var displayDiv = window.getComputedStyle(x).display; //this function
var btnText = document.getElementById("myBtn");
if (displayDiv === "none") {
x.style.display = "block";
btnText.innerHTML = "Read less";
} else {
x.style.display = "none";
btnText.innerHTML = "Read More";
}
}
#myDIV {
display: none;
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<div id="myDIV">
This is my DIV element.
</div>
<button onclick="myFunction()" id="myBtn">Read More</button>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
</body>
</html>
Using Inline styling on the div
You could simply set the display to inline style as display:none.
This way it will ensure that content will show in one click.
Demo:
function myFunction() {
var x = document.getElementById("myDIV");
var btnText = document.getElementById("myBtn");
if (x.style.display === "none") {
x.style.display = "block";
btnText.innerHTML = "Read less";
} else {
x.style.display = "none";
btnText.innerHTML = "Read More";
}
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<div id="myDIV" style="display: none;">
This is my DIV element.
</div>
<button onclick="myFunction()" id="myBtn">Read More</button>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
</body>
</html>

Printing what is inside a modal

I have a modal where I want to print the full contents of it. I don't want anything else printed aside what is within the modal.
Here I created the button within the modal:
This should not be printed...
<button id="btnPrint">Print (this btn should not be printed!)</button>
<hr />
<div id="printThis">
This should BE printed!
</div>
<div id="printThisToo">
This should BE printed, too!
</div>
I have some text next to the button, but this text should not show when you click the button to preview the print view.
Here I wrote some js to show what content should be printed:
document.getElementById("btnPrint").onclick = function() {
printElement(document.getElementById("printThis"));
printElement(document.getElementById("printThisToo"), true, "<hr />");
window.print();
}
function printElement(elem, append, delimiter) {
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("printSection");
if (!$printSection) {
var $printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
if (append !== true) {
$printSection.innerHTML = "";
}
else if (append === true) {
if (typeof(delimiter) === "string") {
$printSection.innerHTML += delimiter;
}
else if (typeof(delimiter) === "object") {
$printSection.appendChlid(delimiter);
}
}
$printSection.appendChild(domClone);
}
Finally, I wrote some css:
#media screen {
#printSection {
display: none;
}
}
#media print {
body {
font-family: 'Open Sans', sans-serif;
font-size: 12px;
font-weight: 500;
color: #101010;
background: #f6f5fa;
visibility:hidden;
}
#printSection, #printSection {
visibility:visible;
}
#printSection {
position:absolute;
left:0;
top:0;
}
}
When I click the button in the modal, nothing happens and no errors appear in the console. Not sure what the issue is. Any help would be much appreciated.
UPDATED CODE:
(HTML)
<div>
This should not be printed...
<button ng-click="printPreview()">Print (this btn should not be printed!)</button>
</div>
<hr />
<div id="printThis">
This should BE printed!
</div>
(JS)
var app = angular.module('dmdesktop');
app.controller('PrintViewCtrl', rollUpCtrl);
rollUpCtrl.$inject = ['$scope', '$rootScope', '$http', '$uibModal','headersvc','locFiltersvc']
function rollUpCtrl($scope, $rootScope, $http, $uibModal, headersvc, locFiltersvc) {
$scope.printPreview = function() {
printElement(document.getElementById("printThis"));
}
function printElement(elem) {
alert ("printing!");
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("printSection");
if (!$printSection) {
var $printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
$printSection.innerHTML = "";
$printSection.appendChild(domClone);
window.print();
}
}
(CSS)
same as before
With the updated code and window.print inside a evalAsync function allows you to print the content inside a modal
$scope.$evalAsync(function () {
window.print();
});

Show/Hide Multiple Divs Javascript

Looking for a good JavaScript to help me hide/show multiple divs with a button click not an a href click so I can use it in blogger.
I've been looking for an answer for a while now and have been unable to find a good one that uses JavaScript and/or CSS. I am a bit of a novice so bear with me.
Following is my code that works but I would like to simplify it and make it work so that it will close the div when I click the appropriate button again.
css
<head>
<style>
#myDIV1 {
width: 150px;
height: 150px;
background-color: lightblue;
display: none;
}
#myDIV2 {
width: 150px;
height: 150px;
background-color: lightblue;
display: none;
}
#myDIV3 {
width: 150px;
height: 150px;
background-color: lightblue;
display: none;
}
#myDIV4 {
width: 150px;
height: 150px;
background-color: lightblue;
display: none;
}
</style>
</head>
I know there is an easier way but this is the only way that I can find that works for what I want it to do for the most part
html
<body>
<p>Click button to see div.</p>
<button onclick="myFunction1()">One</button>
<button onclick="myFunction2()">Two</button>
<button onclick="myFunction3()">Three</button>
<button onclick="myFunction4()">Four</button>
<div id="myDIV1">
This is the div1 element.
</div>
<div id="myDIV2">
This is the div2 element.
</div>
<div id="myDIV3">
This is the div3 element.
</div>
<div id="myDIV4">
This is the div4 element.
</div>
Javascript
<script>
function myFunction1() {
document.getElementById("myDIV1").style.display = "block";
document.getElementById("myDIV2").style.display = "none";
document.getElementById("myDIV3").style.display = "none";
document.getElementById("myDIV4").style.display = "none";
}
function myFunction2() {
document.getElementById("myDIV1").style.display = "none";
document.getElementById("myDIV2").style.display = "block";
document.getElementById("myDIV3").style.display = "none";
document.getElementById("myDIV4").style.display = "none";
}
function myFunction3() {
document.getElementById("myDIV1").style.display = "none";
document.getElementById("myDIV2").style.display = "none";
document.getElementById("myDIV3").style.display = "block";
document.getElementById("myDIV4").style.display = "none";
}
function myFunction4() {
document.getElementById("myDIV1").style.display = "none";
document.getElementById("myDIV2").style.display = "none";
document.getElementById("myDIV3").style.display = "none";
document.getElementById("myDIV4").style.display = "block";
}
</script>
Any help would be appreciated thanks in advance.
I would suggest to separate your code first - it would be then more clean and reusable - like myStyle.css, myScript.js, index.html
Add the css and js file in the html file like -
<link rel="stylesheet" type="text/css" href="myStyle.css">
<script type="text/javascript" src="myScript.js"></script>
src -> indicates the source path of the file. Here I assume that all our css, js, 'html' file in same place.
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-size: 16px;
}
<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>
if you want to hide/show all divs simultaneously than you have to give all divs same class for ex: .toggle and than you can do this:
function myFunction1(){
$(".toggle").slideToggle();
}
if you want to hide/show one div at a time than you can do this with id :
function myFunction1(){
$("#myDIV1").slideToggle();
}
with different buttons :
function myFunction1(id){
$("#"+id).slideToggle();
}
pass id here :
<button onclick="myFunction1('myDIV1')">One</button>
<button onclick="myFunction1('myDIV2')">Two</button>
<button onclick="myFunction1('myDIV3')">Three</button>
<button onclick="myFunction1('myDIV4')">Four</button>
I found the answer to what I wanted with the .toggle function thanks for the help. The answer I found here: radomsnippets.com
We can easily add an unlimited amount of buttons using reusable code.
here is a full example! Enjoy
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.generalclass {
width: 100%;
color: #ffffff;
text-align: center;
background-color: #000000;
margin: 10px;
padding: 10px;
display: none;
}
.button{
background: red;
padding: 10px;
border-radius: 5px;
color: #FFFFFF;
font-size: 16px;
border: none;
}
.button:hover{
background: black;
}
</style>
</head>
<body>
<button class="button" onclick="myFunction('button1')">Button 1</button>
<button class="button" onclick="myFunction('button2')">Button 2</button>
<div id="button1" class="generalclass">
<p>I can show anything here</p>
</div>
<div id="button2" class="generalclass">
<p>I can show anything here too and different from button 1</p>
</div>
<script>
function myFunction(divid) {
var x = document.getElementById(divid);
if (x.style.display == "none")
{
x.style.display = "block";
}
else {
x.style.display = "none";
}
}
</script>
</body>
</html>