HTML/Javascript - Button takes two clicks to execute click event - javascript

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.

Related

Javascript click on one element shows it, click on another: hide the first one and show the second

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 :)

How can I show content when I click a button

I want to show an image when I click on the button. But right now the button hides the image when I click on it. Is there a way to reverse this? This is the code I have.
var flag = 1;
function coursework() {
if (flag == 1) {
document.getElementsById("coursework").style.display = "none";
flag = 0;
} else {
document.getElementById("coursework").style.display = "block";
flag = 1;
}
}
<button onclick="coursework()">Show Coursework</button>
<div id="coursework">
<img src="Wellcome.png" width="300">
</div>
Thank you :)
You can set the image to display: none; initially and then change your if-else condition accordingly so that the image is displayed on first click and hide on second click and so on. Also, it should be getElementById and not getElementsById.
document.getElementById("coursework").style.display="none";
var flag =1;
function coursework() {
if(flag==1)
{
document.getElementById("coursework").style.display="block";
flag=0;
}
else{
document.getElementById("coursework").style.display="none";
flag=1;
}
}
<button onclick="coursework()">Show Coursework</button>
<div id="coursework">
<img src="https://images.pexels.com/photos/87840/daisy-pollen-flower-nature-87840.jpeg?auto=compress&cs=tinysrgb&h=350" width="300">
</div>
I am assume scenario that initially you hide image and when click on button it will show it, may be it will different from what you want and try to give this answer. Refer following code
<html>
<body>
<button onclick="show()">Show Coursework</button>
<div id="coursework" style="display:none">
<img src="welcome.png" width="300">
</div>
<script>
function show(){
document.getElementById("coursework").style.display="block";
}
</script>
</body>
</html>
hope this will help full.

display button onclick pop up close button

Onclick button "button1" , we are displaying pop up box and hiding "button1".
but now we want to display the "button1" once we click on "close" button of "pop up box"
pop up close button code
<a href="javascript:void(0)" class="close">
<input type="button" onclick="showDiv()" style="display:none;" />
</a>
function showDiv() {
document.getElementById('aitcg-control-panel').style.display = "block";
}
button1 code
<div id="aitcg-control-panel"><button>button1</button></div>
Edit
I tried this code : document.getElementById('aitcg-control-panel').style.display = "block"; but still it didt worked for me....
After looking into your website you've provided i found out that the elements you wanted to reappear were removed from the page.
Why don't you just keep the button instead? Because after saving the item it refreshes the page anyway.
There should be any javascript code in the module (aitcg) you've installed on your site that removes the elements aitcg-toolbox-{{somenumber}} and aitcg-control-pane from the page.
I hope this could be of any help.
Is this what you were looking for? I'm sure there is a cleaner way to do it, but your question wasn't super clear.
function showDiv() {
document.getElementById('aitcg-control-panel').style.display = "block";
document.getElementById('ShowDivButton').style.display = "none";
}
function hideDiv() {
document.getElementById('aitcg-control-panel').style.display = "none";
document.getElementById('ShowDivButton').style.display = "initial";
}
div{
width: 200px;
height: 200px;
background: red;
display: none;
}
<button id='ShowDivButton' onclick="showDiv()">Open Div</button>
<div id="aitcg-control-panel" >
<button id='ShowDivButton' onclick="hideDiv()">Close Div</button>
</div>
I've sincerely not fully understood your question. But from what you've said, I'm assuming this is what you want:
function display(a) {
//Hide the button
a.style.display = "none";
//You need setTimeout for the code to wait for the alert to show the button again
setTimeout(function() {
alert('ok');
a.style.display = "block";
}, 100);
}
<button onclick="display(this);">Click me</button>
Hope it helps in some way and if this is not what you wanted, please reply.
after giving link for you website. i can tell you the reason why its not working for you.
on click of save design you are removing code for aitcg-control-panel
that's why you are not able to show it back
proof: before clicking code for button div exists
After click on save design
proof:
code is not there. that's why you are not able to show.
i debugged your code i found one function
_getControlPanelHtml: function()
{
if (this.config.editorEnabled) {
var returnHtml = "";
returnHtml += '<div id="aitcg-control-panel" style="display:none">' +
'<button onclick="return setproductlogin(\'null\', event);" class="aitcg-button apply-but" id="submit-editorApply-{{rand}}" title="{{apply_text}}">{{apply_text}}</button>' +
'<button class="aitcg-button reset-but" id="submit-editorReset-{{rand}}" title="{{reset_text}}">{{reset_text}}</button>' +
'</div>';
return returnHtml;
}
return '';
},
in this function they are returning '';
please change this function or other function to give you the same code what you had before clicking.

Set object string ID's to Javascript parameters

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>

Why does this toggle function only work when the element is loaded a certain way?

I am trying to toggle some text, Q & A style with the question as a button that will display its answer when clicked. It functions fine when the CSS does not load the page with target element set to display:none
However, I want the element to be hidden by default until the button is clicked. For some reason, the js function does not work when the page is loaded in this manner. Anyone know why?
HTML
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="sample.css" media="screen" />
<script src="toggle.js" type="text/javascript"></script>
</head>
<body>
<button type="submit" class="question" id="q1" onclick="toggle_visibility('q1')">
This is my question?
</button>
<div class="dynamic-text-wrapper">
<div class="answer" id="a1">
Here is the answer to your question.
</div>
</div>
</body>
</html>
CSS
.dynamic-text-wrapper {height: 25px;}
.answer {
height: 25px;
display: none; /*DOESN'T WORK WHEN THIS LINE IS INCLUDED. But I want to not displayed to be default*/}
JavaScript
function toggle_visibility(questionID) {
var targetElement = document.getElementById('a'+parseInt(questionID.substring(1)));
if(targetElement.style.display == '') {
targetElement.style.display = 'none';
}
else {
targetElement.style.display = '';
}}
Instead of
targetElement.style.display = '';
you've got to write
targetElement.style.display = 'block';
In the 'if', you've got to check if you've established the display to block. If you haven't, the elment will be invisible (as set by the CSS rule):
if (targetElement.style.display == 'block') {
If you set display: none in CSS, doing .style.display = '' means that you're 'erasing' the inline value (which takes precedence over the value in a CSS file). So, by doing this, the new value for display will be 'none', as set in the CSS. By setting it to 'block', the final value of display is block.
I suggest you to read something about how CSS rules are applied.
Option 1
Use
.answer {
display: none; /* Hide by default */
}
and
targetElement.style.display = targetElement.style.display ? '' : 'block';
That is, if targetElement.style.display is falsy (you haven't set it, so it's hidden by default), you set it to 'block'. And if it is truthy (you have set it to 'block'), you clear it.
Option 2
This option will make your function reusable with non-block elements.
Use
<div class="answer default-hidden" id="a1"></div>
And, at onload, run
var els = document.getElementsByClassName('default-hidden');
for(var i=0, l=els.length; ++i) els[i].style.display = 'none';
And in your function:
targetElement.style.display = targetElement.style.display ? '' : 'none';

Categories