This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I'm attempting to make a p tag appear and disappear when I click on the h1 I feel I have a good understanding of the process in JavaScript (obviously I don't but I cant seem to get it to do anything at all (I'm really new to this, like only a couple weeks into JS)
here is the Code
<script type="text/javascript">
function hideAway() {
var pText = document.getElementsByClassName('imgpar');
if (pText.style.display === 'none') {
pText.style.display = 'block';
}else if (pText.style.display === 'block') {
pText.style.display = 'none';
}
}
</script>
<div class="left-image">
<h1 onClick= hideAway()>header</h1>
<img title="skater name" src="skater.jpeg" alt="skater">
<p class= 'imgpar'>skateboard bio
</p>
</div>
Few problems:
.getElementByClassName() is not a function. It should be getElementsByClassName()
.getElementsByClassName() returns an array - in your case you should be selecting the first element
Your if statements are redundant. They can be shortened to a simple if-else statement
You'll need to explicitly apply display:block in the style attribute on the p element so pText.style.display returns something. If you don't explicity set it, you will have to click twice to hide the p element.
This should work:
<div class="left-image">
<h1 onClick= hideAway()>header</h1>
<img title="skater name" src="skater.jpeg" alt="skater">
<p class= 'imgpar' style="display:block">skateboard bio
</p>
</div>
<script type="text/javascript">
function hideAway() {
var pText = document.getElementsByClassName('imgpar')[0];
if (pText.style.display == 'block') {
pText.style.display = 'none';
}else{
pText.style.display = 'block';
}
}
</script>
Easy solutions
HTML:
<div class="left-image">
<h1>header</h1>
<img title="skater name" src="skater.jpeg" alt="skater">
<p class= 'imgpar'>skateboard bio</p>
</div>
JS:
$(document).ready(function(){
$("h1").click(function(){
if ($("p").hasClass("showEle")) {
$('p').removeClass('showEle')
} else {
$('p').addClass('showEle');
}
});
});
CSS:
.showEle {
display: none;
}
Related
Javascript newbie here. Anyone could let me know what is wrong with my code? The div-to-show does not show after click and I can't figure out why...
let div = document.getElementById('div-to-show');
function openDiv() {
if (div.style.display === 'none') {
div.style.display = 'block';
}
}
#div-to-show {
display: none;
}
<p onclick="openDiv">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
There are 2 problems here.
First, you aren't invoking the function with onclick="openDiv" - you have to put () after a function name to invoke it, eg onclick="openDiv()".
Secondly, although you have a CSS rule of display: none, that doesn't result in the CSS property on the element itself changing; it remains the empty string:
let div = document.getElementById('div-to-show');
function openDiv() {
console.log(div.style.display);
}
#div-to-show {
display: none;
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
Instead, to check whether the element is being displayed, you can check whether its offsetParent is null:
let div = document.getElementById('div-to-show');
function openDiv() {
div.style.display = div.offsetParent === null ? 'block' : 'none';
}
#div-to-show {
display: none;
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
For the general case of checking what CSS rules are being applied to a particular element, you can use getComputedStyle:
let div = document.getElementById('div-to-show');
const styleProp = div.style;
const styleDec = window.getComputedStyle(div);
function openDiv() {
styleProp.display = styleDec.display === 'none' ? 'block' : 'none';
}
#div-to-show {
display: none;
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
<!DOCTYPE html>
<html>
<head>
<style>
#div-to-show{
display: none;
}
</style>
</head>
<body>
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
<script type="text/javascript">
let div = document.getElementById('div-to-show');
function openDiv(){
if(window.getComputedStyle(div).display === 'none'){
div.style.display = 'block';
}
}
</script>
</body>
</html>
In your code is wrong the way you write onclick in this tag <p>, you need to write onclick in this way:
<p onclick="openDiv()">Clique</p>
and try again.
You should mention function name correctly on onclick. onclick=openDiv should be replaced to onclick=openDiv().
You should define the display css style directly on the tag to get div.style.display on javascript. document.getElementById('...').style will only contain the style attributes which are defined on html tag style attribute only so to compare, it will be needed to set display attribute on html file directly.
let div = document.getElementById('div-to-show');
function openDiv() {
if (div.style.display === 'none') {
div.style.display = 'block';
}
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show" style="display: none;">
<p>I am visible</p>
</div>
Hi as some other examples here explains, you should use the addEvenlListener. If you only what to show the div on the click event you do not need a if statement. You can add a class to the div that sets the display:none. Then in the code you only need to call the remove on the classList on the div. This will not throw an error or do anything if the class is not in the classList. So no need to implement any check logic.
Using the hidden class makes so you do not need to know what the display value was on the div element initially. Less to worry about.
https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/remove
let div = document.getElementById('div-to-show')
document.getElementById('p-button').addEventListener("click", openDiv);
function openDiv() {
div.classList.remove('hidden');
}
#div-to-show.hidden {
display: none;
}
<p id="p-button">Clique</p>
<div id="div-to-show" class="hidden">
<p>I am visible</p>
</div>
I am new here, I try to explain my problem as clear es possible.
I want to make working an index part of a big documentation. I have Buttons or Links (in this case in Example only divs) named from A to Z, and to every letter belongs a bunch of words starting with the chosen letter, like a dictionary.
What I want to achieve: if I click on a letter, the list of words will appear under the buttons. After that I click on another letter, the first activated list will disappear, and appear the next one, and so on.
I have found several explanation on different sites how to show and hide something, and it works already somehow (I must click on the letter again in order to hide it, so my goal was not reached yet), but I did not find a code or tutorial like this one.
Please help, may you have an idea!
My code:
html:
<div onclick="openIndexA()">A</div>
<div onclick="openIndexB()">B</div>
<div onclick="openIndexC()">C</div>
<!-- etc. -->
<div class="letters" id="A">
<p>A...1</p>
<p>A...2</p>
<p>A...3</p>
</div>
<div class="letters" id="B">
<p>B...1</p>
<p>B...2</p>
<p>B...3</p>
</div>
<div class="letters" id="C">
<p>C...1</p>
<p>C...2</p>
<p>C...3</p>
</div>
<!-- etc. -->
css:
.letters {
display: none;
}
in openIndex.js:
function openIndexA() {
var x = document.getElementById("A");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function openIndexB() {
var x = document.getElementById("B");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function openIndexC() {
var x = document.getElementById("C");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
<!-- etc. -->
I know, that it is not the best and shortest way to do that, I could loop it through, I've tried it, but till now didn't achieve. I wanted to able to see first, how it works. But if you would have an advice for this, or the whole concept should be changed, please don't hesitate to explain, I am open to learn!.. :-)
See this fiddle!
var openIndex = document.querySelectorAll('.openindex');
var letters = document.querySelectorAll('.letters');
openIndex.forEach(function(el){
el.addEventListener('click', function(){
letters.forEach(function(e){
e.classList.remove('show');
});
var id = el.getAttribute('data-id');
document.getElementById(id).classList.add('show');
});
});
and add this css class
.show {
display: block;
}
Here is a solution and some advice:
function openIndex(id) {
document.querySelectorAll('.letters').forEach(elt => elt.classList.remove('active'));
document.querySelector('#'+id).classList.add('active');
}
.letters {
display: none;
}
.letters.active {
display: block;
}
<div onclick="openIndex('A')">A</div>
<div onclick="openIndex('B')">B</div>
<div onclick="openIndex('C')">C</div>
<!-- etc. -->
<div class="letters" id="A">
<p>A...1</p>
<p>A...2</p>
<p>A...3</p>
</div>
<div class="letters" id="B">
<p>B...1</p>
<p>B...2</p>
<p>B...3</p>
</div>
<div class="letters" id="C">
<p>C...1</p>
<p>C...2</p>
<p>C...3</p>
</div>
<!-- etc. -->
For your CSS: Don't work directly on the style, use classes as much as possible.
Here, as you can see, i've added a class active. If I add it, it will edit the style.
Then, for your JavaScript: if you copy paste more than two times, it's likely you could use a function.
Here, i've done the following: pass the ID you want to activate as a parameter.
Then, i take all the letters item and i remove the active class. Then, only for the one selected, i add the active class.
I hope this is clear and will help you :)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have this HTML setup so that these elements will not display until a certain function gets run. The HTML by itself is fine...
<div id="aftlogin">
<div id="priv1" style="display: none;">
<p>Welcome there!</p>
</div>
<div id="priv2" style="display: none;">
</div>
<div id="priv3" style="display: none;">
</div>
<div id="priv4" style="display: none;">
</div>
<div id="priv5" style="display: none;">
</div>
</div>
...It's the JavaScript the screws everything up: this JavaScript function is supposed to make those elements visible again. The elements that become visible depend on the value stored in the variable "role":
(I used block since visible is for the visible style, not the display style)
if (role == "priv1") {
document.getElementById("priv1").style.display = "block";
}
if (role == "priv2") {
document.getElementById("priv1").style.display = "block";
document.getElementById("priv2").style.display = "block";
}
if (role == "priv3") {
document.getElementById("priv1").style.display = "block";
document.getElementById("priv2").style.display = "block";
document.getElementById("priv3").style.display = "block";
}
if (role == "priv4") {
document.getElementById("priv1").style.display = "block";
document.getElementById("priv2").style.display = "block";
document.getElementById("priv3").style.display = "block";
document.getElementById("priv4").style.display = "block";
}
if (role == "priv5") {
document.getElementById("priv1").style.display = "block";
document.getElementById("priv2").style.display = "block";
document.getElementById("priv3").style.display = "block";
document.getElementById("priv4").style.display = "block";
document.getElementById("priv5").style.display = "block";
}
One way or another, the code doesn't work. If I don't comment it out, the entire function stops working, so it's hard to pinpoint exactly what the problem is. All the syntax is correct, so I have done something else that upset the JavaScript gods?
Here is a jsFiddle demo: https://jsfiddle.net/9p9xx8sz/
You can do this with just CSS. This is a typical example of how you can really reduce your code base by using the power of CSS.
The beautify for stuff like privilege rights is you just add the role class to the top of your page and use CSS selectors to show and hide stuff.
Here is a fiddle that demonstrates:
https://jsfiddle.net/9p9xx8sz/3/
#priv1,#priv2,#priv3,#priv4,#priv5 {
display:none;
}
.priv1 #priv1 {
display:block;
}
.priv2 #priv1, .priv2 #priv2 {
display:block;
}
.priv3 #priv1, .priv3 #priv2,.priv3 #priv3 {
display:block;
}
.priv4 #priv1,.priv4 #priv2,.priv4 #priv3,.priv4 #priv4 {
display:block;
}
.priv5 #priv1,.priv5 #priv2,.priv5 #priv3,.priv5 #priv4,.priv5 #priv5 {
display:block;
}
<div id="aftlogin" class="priv1" >
<div id="priv1" >
<p>Welcome there!</p>
</div>
<div id="priv2" >
</div>
<div id="priv3" >
</div>
<div id="priv4" >
</div>
<div id="priv5" >
</div>
</div>
In this updated fiddle below I have some JS that adds the role dynamically and turns on the correct divs using just CSS.
https://jsfiddle.net/9p9xx8sz/5/
After reviewing your page I noticed that you have the div element you want to show inside the parent element being hidden at the same time.
Move your element so it is a sibling and it will solve the issue!
I am starting coding with HTML, CSS and Javascript and I have a problem. I have a Blogger and my posts usually have a lot of content on it, so I was wondering to split my posts by "categorizing them" and use something like Spoiler. So, I am using some div tags just like above
<div style="background-color:rgb(0, 0, 0);">
<p style="font-family:Segoe UI Light; color:white; vertical-align:middle; font-size:16px;">
<img id="icon_1" src="show.png"
style="width:20px; height:20px; margin:2px; vertical-align:middle;">Example</img>
</p>
</div>
<div id="cont_1" style="display: none;">
<p>just some stuff for an example<br/>
content will be placed on this div</p>
<p>I have set a default ID string, but don't know If I will need it at all</p>
</div>
As you can see, I have a main div which contains an picture (an icon related to show/hide) and a string input. Then, I have another div class, where the content will be placed. I have set and id, in this example cont_1. Plus, on load, this div will be collapsed/hidden so I set display:none;. You can also see that the img tag has an Id icon_1
Next, I built a JavaScript class. There, I will set the cont_1 style display to block; and I also want to change the image src
This is my script code
<script>
function click1(item, ico)
{
var a = document.getElementById(item);
if ( a.style.display == 'block' ) {
a.style.display = 'none';
icon_change(ico, "hide")
}
else {
a.style.display = 'block';
icon_change(ico, "show")
}
}
function icon_change(ico, visibility)
{
var image = document.getElementById(icon);
var s = visibility;
if ( s == "hide" ) {
image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAA20lEQVRoQ+2YUQ7CIBBE2ZNZT66eDDExxmKajpMuMfj6S1k6b6cTIMokT0yioyDk1zqZ2pFa6+VdcEScswBkC6mdkLT10go/BLSOIORbC9IRhRjWUih172AtBRrWUihhLYMS1jKgkVoKNKylUCK1DEpYy4D2kVqN4rXVORm1Rk65tWPzsjp99qsjZGQ/SvmjjhwJltQyaLLXUqBhLYUSey2DEtYyoJFaCjSspVAitQxKWMuARmop0LCWQonUMig9LzJeM/ubD6Pk5pTUn/3ID92rhZA9QqPHp+nIHUEJrDNSwO0mAAAAAElFTkSuQmCC";
}
else {
image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAAqklEQVRoQ+2UUQ6CMADF2Mn06Hqy4SfRv4YGMsv/K6xdGNsiz1jkHFsHuVvJilREMtDVksRibEWwOmlYEUksxlYEq5OGFZHEYmxFsDppWBFJLMZWBKuThj9F5pyvz7se0vvOwr7HGM8jrIOcpRZy/qgINHT5rN/v5Qm+PqAiFZEMdLUksRhbEaxOGlZEEouxFcHqpGFFJLEYWxGsThpWRBKLsRXB6qThMkV2e2UUM4Y5sY4AAAAASUVORK5CYII=";
}
}
</script>
Yeah.. my code is not very organized and probably I just need one function to complete the task, I have tried that and din't worked too..
My problem is carry the ID's to JavaScript function, that must be the issue on my code. I would like to have one or two javascript functions to work with multiple div, the divs that contain the content and will show and hide.
I am using OnClick just like this
<div Onclick="click1(content_1, icon_1)"/>
So, I tried to set two parameters to JavaScript, one it's the div ID and other the image ID
I am inserting it as String, should I do that? Do you know any easier way to do this? I would like to see if there are easier alternatives :)
Thanks! This is my post and hope it's clear enough..
I guess the problem you have there is that your parameters aren't called as string. It should be:
<div Onclick="click1('content_1', 'icon_1')"/>
You could simplify it this way:
function click1(which_div)
{
var a = document.getElementById("content_"+which_div);
var image = document.getElementById("icon_"+which_div);
if ( a.style.display == 'block' ) {
a.style.display = 'none';
image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAA20lEQVRoQ+2YUQ7CIBBE2ZNZT66eDDExxmKajpMuMfj6S1k6b6cTIMokT0yioyDk1zqZ2pFa6+VdcEScswBkC6mdkLT10go/BLSOIORbC9IRhRjWUih172AtBRrWUihhLYMS1jKgkVoKNKylUCK1DEpYy4D2kVqN4rXVORm1Rk65tWPzsjp99qsjZGQ/SvmjjhwJltQyaLLXUqBhLYUSey2DEtYyoJFaCjSspVAitQxKWMuARmop0LCWQonUMig9LzJeM/ubD6Pk5pTUn/3ID92rhZA9QqPHp+nIHUEJrDNSwO0mAAAAAElFTkSuQmCC";
}
else {
a.style.display = 'block';
image.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAAqklEQVRoQ+2UUQ6CMADF2Mn06Hqy4SfRv4YGMsv/K6xdGNsiz1jkHFsHuVvJilREMtDVksRibEWwOmlYEUksxlYEq5OGFZHEYmxFsDppWBFJLMZWBKuThj9F5pyvz7se0vvOwr7HGM8jrIOcpRZy/qgINHT5rN/v5Qm+PqAiFZEMdLUksRhbEaxOGlZEEouxFcHqpGFFJLEYWxGsThpWRBKLsRXB6qThMkV2e2UUM4Y5sY4AAAAASUVORK5CYII=";
}
}
And you call it like this:
<div Onclick="click1('1')"/>
I have created following code snippet which gives same functionality/behavior as you expects but implemented little differently.
Hope this will solve your problem. You could test/play this on JSFiddle.
<figure onclick="showHide('show');" id="show">
<img src="http://bioinformatica.upf.edu/2009/projectes09/Ex/resultats/seli/SelI_human_pfam_files/showButton.png" alt="An awesome picture">
<figcaption>Show</figcaption>
</figure>
<figure onclick="showHide('hide');" id="hide" style="display:none;">
<img src="http://tweetingmeeting.com/images/hide-button.png">
<figcaption>Hide</figcaption>
</figure>
<div id="cont_1" style="display:none;">
<p>just some stuff for an example<br/>
content will be placed on this div</p>
<p>some more content.....</p>
</div>
<script>
function showHide(activity)
{
show = document.getElementById("show");
hide = document.getElementById("hide");
content = document.getElementById("cont_1");
// a.style.display = "none";
if(activity == "show")
{
show.style.display = "none";
hide.style.display = "block";
content.style.display = "block";
}
else if(activity == "hide")
{
show.style.display = "block";
hide.style.display = "none";
content.style.display = "none";
}
}
</script>
I am looking to hide a number of DIVs based upon the specific text of another DIV. My Javascript (below) isn't working.
The HTML:
<div id="LEGEND">abAB</div>
<div id="small-a"></div>
<div id="small-b"></div>
<div id="big-a"></div>
<div id="big-b"></div>
If the LEGEND DIV contains the text a, then I want it to show only DIV small-a.
If the LEGEND DIV contains the text bA, then I want it to show only DIV small-b and big-a.
The Javascript:
<script>
window.onload = function ShowHide{
if (document.getElementById('LEGEND').indexOf("a") > 0){
document.getElementById('small-a').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("b") > 0){
document.getElementById('small-b').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("A") > 0){
document.getElementById('big-a').style.display = 'block';}
if (document.getElementById('LEGEND').indexOf("a") > 0){
document.getElementById('big-b').style.display = 'block';}
</script>
You are forgetting a couple of things.
A function declaration should be like this
function functionName(args) {
}
You have to hide the divs using style.display = "none"
Example:
<div id="LEGEND">abB</div>
<div id="small-a" style="display: none;">This is small-a</div>
<div id="small-b" style="display: none;">This is small-b</div>
<div id="big-a" style="display: none;">This is big-a</div>
<div id="big-b" style="display: none;">This is big-b</div>
<script>
function showElement(id) {
document.getElementById(id).style.display = "block";
}
window.onload = function ShowHide() {
var legend = document.getElementById("LEGEND").innerHTML;
if(legend.indexOf("a") != -1) showElement("small-a");
if(legend.indexOf("b") != -1) showElement("small-b");
if(legend.indexOf("A") != -1) showElement("big-a");
if(legend.indexOf("B") != -1) showElement("big-b");
}
</script>
The problem is that your code changes the other div elements to block-level elements when div is already a block-level element. You need to set them not to display initially using CSS and then reveal them in the JavaScript.
Try this instead:
<div id="LEGEND">abAB</div>
<div id="small-a" style="display: none;"></div>
<div id="small-b" style="display: none;"></div>
<div id="big-a" style="display: none;"></div>
<div id="big-b" style="display: none;"></div>
<script type="text/javascript">
window.onload = function() {
if (document.getElementById('LEGEND').indexOf('a') > 0) {
document.getElementById('small-a').style.display = 'block';
...
// etc.
}
}
</script>
First, try making sure the window.onload is being called:
window.addEventListener('load', ShowHide, false);
function ShowHide()
{...
Second, you should be looking at the InnerHTML of the element:
if (document.getElementById('LEGEND').innerHTML.match("a") == "a"){...
Third, each if statement should also contain an else (replace divName with real div names):
else {
document.getElementById('divName').style.display = 'none'}
Hope that helps!
~md5sum~
EDIT:
Also, I'm not 100% sure on this, but I believe that the syntax:
window.onload = function ShowHide{
will completely fail. I think that the syntax should be:
window.onload = function(){
If me, I will do like this. you dont need to touch HTML part, everything is done in javascript.
you can extend it to CDEFGH...
and you don't need to set <div id="small-X" style="display: none;"> for each tags too. :-)
<body>
<script>
window.onload=function(){
x=document.getElementsByTagName("div");
//first hide everything with small- or big-
for(i in x)
if(/small-|big-/.test(x[i].id))
x[i].style.display="none";
//then turn on each tags based on LEGEND
x= document.getElementById("LEGEND").innerHTML;
for(i=0;i<x.length;i++)
document.getElementById((x[i]<='Z'?'big-':'small-')+x[i].toLowerCase()).style.display='block';
}
</script>
<div id="LEGEND">aAB</div>
<div id="small-a">a</div>
<div id="small-b">b</div>
<div id="big-a">A</div>
<div id="big-b">B</div>
</body>
You need to set the style.display property to none.