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>
Related
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;
}
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 :)
Testing out a simple toggle display, however, it takes two clicks to toggle the display the first time. Afterwards it does it in one.
<html>
<head>
<style>
#carousel{border:2px solid blue;
width:1280px;
height:720px;}
#p2{visibility:hidden;}
#p1{display:block;}
#btn{position:absolute;
top:2000px;}
</style>
<script src="mainScript.js"></script>
</head>
<body>
<div id="carousel">
<img id="p1" src="pic1.jpg">
<img id="p2" src="pic2.jpg">
</div>
<button type="button" id="button" onclick="clickEvent()">Click</button>
</body>
</html>
And here is my javascript:
function clickEvent(){
var p = document.getElementById("p1");
if(p.style.display == "block")
p.style.display = "none";
else
p.style.display = "block";
}
It should be noted I am using no jQuery, as all other questions I found about this were jQuery related.
function clickEvent(){
var p = document.getElementById("p1");
if(p.style.display == "none")
p.style.display = "block";
else
p.style.display = "none";
}
you can also simplify things a bit:
p.style.display = p.style.display == "none" ? "block" : "none";
I have an update to my previous fiddle posted in my comment above. My previous fiddle still ran into the same problem after further testing of the double click.
After stepping through, the initial display value is coming back as "" not block. I'm not sure why its not taking your value you set in the <head></head> section but if you inline it like so:
<img id="p1" src="pic1.jpg" style="display: none;" />
it works correctly the first time with only one click of the button.
Here is my new updated fiddle demonstrating this.
I'm going to look more into why your styling in the <head></head> section but for now, here is a quick (and semi crude) fix.
Hope this helps and best of luck!
The default display attribute is "inline" so your logic is not taking this into account. It is changing it the block on the first run, so it is still visible, then it is hiding it on the second click (setting display to none)
your answer
function clickEvent(){
var p = document.getElementById("p1");
if(p.style.display === "block")
p.style.display = "none";
else
p.style.display = "block";
}
I changed the condition I have the same problem and I realize that it was about the order code executes my CSS style for the element was already "block", and I was checking if the element display was "none" then do the display block thing, so when the first time I was clicking, it changed the display to "none", then in the second time it would change the display to block, I hope It was clear my explanation
enjoy
The same problem can be resolved by just replacing "block" : "none"; by ?"none" : "block";
you will not need to double click the toggle button for the first time, single click will work.
I am using jQuery to hide / show sections of content on a page. On one page, I have two such sections. Right now the page loads with both hidden. I need the page to load with the first div visible and the second one hidden.
Here is my javascript:
function a2012() {
var ele = document.getElementById("toggleArch12");
var text = document.getElementById("displayArch12");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "2012 Newsletter Archive";
}
else {
ele.style.display = "block";
text.innerHTML = "Hide Archive";
}
}
function a2011() {
var ele = document.getElementById("toggleArch11");
var text = document.getElementById("displayArch11");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "2011 Newsletter Archive";
}
else {
ele.style.display = "block";
text.innerHTML = "Hide Archive";
}
}
and the HTML to set up the DIVs and their toggle links:
<a id="displayArch12" href="javascript:a2012();">2012 Newsletter Archive</a>
<div id="toggleArch12" style="display:none">content goes here</div>
<a id="displayArch11" href="javascript:a2011();">2011 Newsletter Archive</a>
<div id="toggleArch11" style="display:none">content goes here</div>
I tried changing style="display:none" for the first div to style="display:visible" and while it does cause the page to load with the contents visible, the toggle link still shows the "click to open" text (in this case "2012 Newsletter Archive").
I need the first div to load visible and the correct toggle text (Hide Archive) to show as well. Any ideas?
If you want to use jQuery (which you are not from the code you've posted), you could write it like this:
$("#displayArch11").click(function(e) {
var $display = $(this)
$display.next().toggle(function() {
$display.html($display.html() == "2011 Newsletter Archive" ? "Hide Archive" : "2011 Newsletter Archive");
});
e.preventDefault();
});
$("#displayArch12").click(function(e) {
var $display = $(this)
$display.next().toggle(function() {
$display.html($display.html() == "2012 Newsletter Archive" ? "Hide Archive" : "2012 Newsletter Archive");
});
e.preventDefault();
});
and the HTML like this
<a id="displayArch12" href="#">2012 Newsletter Archive</a>
<div id="toggleArch12" style="display:none">content goes here</div>
<a id="displayArch11" href="#">2011 Newsletter Archive</a>
<div id="toggleArch11" style="display:none">content goes here</div>
This is easier if you use jQuery, but I think simply setting the correct default html should achieve your goal.
<a id="displayArch12" href="javascript:a2012();">Hide Archive</a>
<div id="toggleArch12" style="display:block">content goes here</div>
Change the inline script:
<div id="toggleArch12" style="display:block">content goes here</div>
First, if you want one of the divs to be visible, just don't specify the display property. They are visible by default. Though the value you are looking for with a div is display:block;
I would use a div instead of a link for your toggling needs.
<div id="displayArch12" class="toggleDiv">
2012 Newsletter Archive
<div id="toggleArch12" style="display:block;">Content Here</div>
</div>
<div id="displayArch11" class="toggleDiv">
2011 Newsletter Archive
<div id="toggleArch11" style="display:none;">Content Here</div>
</div>
Then you need some real jQuery to toggle them properly.
$(function() {
$(".toggleDiv").click(function () {
$("div:first-child", this).toggle();
});
});
That should work for you. And of course don't forget to include the jQuery library itself. The easiest way is to use the Google API link.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>