Div showing on clicking button twice in the initial state - html

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>

Related

Event propagation and function that works only on the first div

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!")
}
}

HTML - Hide and unhide div by display none

I am trying to make a show & hide div. I use the tutorial from w3schools (https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_hide_show) but in this the div is already shown and then you hide it while mine is hidden and then shown. So in the example, I just add display: none; to #myDIV:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
display: none;
}
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
When I first click the Try it button then the div doesn't show... Why? From that point on if I reclick it it shows and disappears normally... How can I fix this? Ty
Because first time, x.style.display is not defined!
Modify your condition to if (x.style.display === "none" || !x.style.display)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
display: none;
}
</style>
</head>
<body>
<p>Click the "Try it" button to toggle between hiding and showing the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none" || !x.style.display) {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
</body>
</html>
Under #myDIV you have set display: none remove that line and it will automatically show up

Dont know why i cant center web

So, in web-programming class (a few weeks ago) we started a project to make our own website. Now, most things are going fine, though I tried to center my page it didnt work. I don't know why it doesn't work either, I'm thinking it might be something in the codes that might block/counter it, but I don't know. I basically want the whole html centered. I used an ID which I named "wrap" on the div tag after the bgcolor tag as you will see.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Norskandi</title>
<link rel="stylesheet" type="text/css" href="css/norskandi.css">
<style type="text/css">
</style>
</head>
<body bgcolor="#4A96AD">
<div id="wrap">
<IMG STYLE="WIDTH:1400px; HEIGHT:80px" src="../bilder/3_11.png">
Contact
About
<script type="text/javascript">
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
/*window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}*/
function geography() {
document.getElementById("geography").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
/*window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content1");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}*/
function anthems() {
document.getElementById("anthems").classList.toggle("show");
}
// Close the dropdown menu if the user clicks outside of it
/*window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content2");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}*/
</script>
<div class="dropdown">
<button onmouseover="myFunction()" class="dropbtn">History</button>
<div id="myDropdown" class="dropdown-content">
Sweden
Norway
Denmark
</div>
</div>
<div class="dropdown1">
<button onmouseover="geography()" class="dropbtn">Geography</button>
<div id="geography" class="dropdown-content1">
Sweden
Norway
Denmark
</div>
</div>
<div class="dropdown2">
<button onmouseover="anthems()" class="dropbtn">Anthems</button>
<div id="anthems" class="dropdown-content2">
Sweden
Norway
Denmark
</div>
</div>
</div>
</body>
</html>
CSS:
#wrap{
width: 800px;
margin-right: auto;
margin-left: auto;
height: auto;
}
Like #Juan-Ferres here is a JSFiddle that may help you. Another great resource is Bootstrap and look at the class container in their examples. As a few have pointed out though the key is margin: 0 auto or something like margin: 10px 10px 10px 10px but then you need to be more exacting with your width.
Try justify-content: center in you CSS code
Your #wrap div is being centered on the site. However, for resolutions smaller than 800px, you will see it overflows horizontally.
You may think it's not centered due to your img tag having an inline style of width: 1400px which makes it extend beyond the actual container div.
Here's a fiddle with that tag removed (try not to use inline styles on your HTML for proper separation of concerns as in, CSS in css files, and HTML in html files). https://jsfiddle.net/dm3bmpas/
I've also replaced width: 800px for max-width: 800px and width: 100% so your container takes up to 800px on resolutions big enough but for smaller resolutions it takes all the available width; this is a common responsive pattern.
Finally, just in case, if you want your text to be centered inside your div, the rule you're looking at is text-align: center on your #wrap div.
Try this css
#wrap{
width: 800px;
margin:0px auto;
}

w3 schools modal tutorial not working [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
Hi im following the tutorial on w3 schools on modals
http://www.w3schools.com/howto/howto_css_modals.asp
but i cant seem to get mine to open at all. is there anything in my code that is going wrong or am i missing something.
or is there any different ways that you would recommend i do this?
<?php
session_start();
include 'loginlogoutregister.php';
//connecting to database
$link = mysqli_connect("localhost","root","","authentication");
if(isset($_POST['Login_Btn'])){
login($link);
}
if(isset($_POST['Register_Btn'])){
register($link);
}
if(isset($_POST['Logout_Btn'])){
logout($link);
}
?>
<html>
<head>
<Title>LogIn</Title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var modal = document.getElementById('PopUpLR');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("closeLR")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</head>
<body>
<div class = "headerContainer">
<div class = "headerLeft">
test
</div>
<div class="headerMiddle">
<h1>Website</h1>
<div><h4>
<?php
if(isset($_SESSION['username']) ){
echo "Welcome ".$_SESSION['username'];
}else{
echo "Logged Out ";
}
?>
</h4></div>
</div>
<div class = "headerRight">
<div class = "loginRegister">
<p>Login/Register</p>
</div>
</div>
</div>
<button id="myBtn">Open Modal</button>
<div id = "PopUpLR">
<div class = "PopUpLRContent">
<span class="closeLR">x</span>
<p>Some text in the Modal..</p>
</div>
</div>
</body>
</html>
#PopUpLR{
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
.PopUpLRContent{
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
.closeLR {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.closeLR:hover,
.closeLR:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
moving the script to the bottom of the body tag solved this issue
Move your script <script>
var modal = document.getElementById('PopUpLR');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("closeLR")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
under your HTML so the button knows what its sending to!

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>