Hide and Show div works only once - javascript

I made such a simple code to show and hide div but i don't know why it works only once. When i show and hide other div, then when iw ant to do it again it dosen't work. Here is code (content of div is not important). In css i set display:none on both of divs
function pokazMail(ID) {
if (document.getElementById(ID).style.display != 'none') {
if (document.getElementById('wizyta').style.display == 'block') {
document.getElementById('wizyta').style.display = 'none';
document.getElementById(ID).style.display = 'block';
} else {
document.getElementById(ID).style.display = 'block';
}
}
}
function pokazWizyta(ID) {
if (document.getElementById(ID).style.display != 'none') {
if (document.getElementById('mail').style.display == 'block') {
document.getElementById('mail').style.display = 'none';
document.getElementById(ID).style.display = 'block';
} else {
document.getElementById(ID).style.display = 'block';
}
}
}
#mail{display:none;}
#wizyta{display:none;}
<a class="btn btn-primary btn-lg" onclick="pokazMail('mail');">First.</a>
<a class="btn btn-primary btn-lg" onclick="pokazWizyta('wizyta');">Second.</a>
<div id="mail">dsjdhs </div>
<div id="wizyta">12313213</div>
Here it is: http://jsfiddle.net/Lcbm8m8m/

function pokazMail(IDtoShow,IDtoHide) {
document.getElementById(IDtoShow).style.display = 'block';
document.getElementById(IDtoHide).style.display = 'none';
}
#mail{display:none;}
#wizyta{display:none;}
<a class="btn btn-primary btn-lg" onclick="pokazMail('mail','wizyta');">First.</a>
<a class="btn btn-primary btn-lg" onclick="pokazMail('wizyta','mail');">Second.</a>
<div id="mail">dsjdhs </div>
<div id="wizyta">12313213</div>

You should use jQuery methods like .hide() and .show()
Here is and example of using it:
function pokazMail(ID) {
$("#mail").show();
$("#wizyta").hide();
}
function pokazWizyta(ID) {
$("#mail").hide();
$("#wizyta").show();
}
jsFiddle
function pokazMail(ID) {
$("#mail").show();
$("#wizyta").hide();
}
function pokazWizyta(ID) {
$("#mail").hide();
$("#wizyta").show();
}
#mail{display:none;}
#wizyta{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn btn-primary btn-lg" onclick="pokazMail('mail');">First.</a>
<a class="btn btn-primary btn-lg" onclick="pokazWizyta('wizyta');">Second.</a>
<div id="mail">dsjdhs </div>
<div id="wizyta">12313213</div>

I guess you can use Jquery since I see you using bootstrap classes. Using your approach checking if the display is block then hiding it:
//javascript
function pokazMail(ID) {
if($("#wizyta").css('display') == "block"){
$("#wizyta").css("display", "none");
}
$("#mail").css("display", "block");
}
function pokazWizyta(ID) {
if($("#mail").css('display') == "block"){
$("#mail").css("display", "none");
}
$("#wizyta").css("display", "block");
}
//css
#mail{display:none;}
#wizyta{display:none;}
<!--html-->
<a class="btn btn-primary btn-lg" onclick="pokazMail('mail');">First.</a>
<a class="btn btn-primary btn-lg" onclick="pokazWizyta('wizyta');">Second.</a>
<div id="mail">dsjdhs </div>
<div id="wizyta">12313213</div>

The problem you've stated was a little bit off than what your code was trying to achieve... BUT I THINK I've understood what you're actually trying to achieve...
So, if this is what you are trying to achieve than my solution will work just fine:
You expect than when you click on a display control element, other 'similar' associated elements are hidden but the one that's associated to the display control element you've clicked... A bit of a mouthful, right? Sorry, but I am not a native English person :(
So the code, as generic as possible is the one I've set you up with on your jsfiddle http://jsfiddle.net/Lcbm8m8m/71/
Anyway, just in case someone comes up w/ a better idea and overrides the fiddle, here's the code as well..
HTML
<a class="btn btn-primary btn-lg" onclick="javascript: hideAllButMe('mail');">First.</a>
<a class="btn btn-primary btn-lg" onclick="javascript: hideAllButMe('wizyta');">Second.</a>
<a class="btn btn-primary btn-lg" onclick="javascript: hideAllButMe('third');">Third.</a>
<a class="btn btn-primary btn-lg" onclick="javascript: hideAllButMe('fourth');">Fourth.</a>
<div id="mail" class="carouselle hidden">MAIL</div>
<div id="wizyta" class="carouselle hidden">WIZTYA</div>
<div id="third" class="carouselle hidden">THIRD</div>
<div id="fourth" class="carouselle hidden">FOURTH</div>
CSS
.hidden{display:none;}
.carouselle{}
JAVASCRIPT
function hideAllButMe(show) {
// Get all the elements on the page with the 'carouselle' class name.
var elementsMarkedForHidingList = document.getElementsByClassName('carouselle');
// document.getElementsByClassName returns a NodeList and this turns it into an array
var nodeArray = Array.prototype.slice.call(elementsMarkedForHidingList);
// we iterate the array and hide all the elements...
nodeArray.map( function(item) {
addClass(item, 'hidden');
});
// and we show the one referenced by the element we've clicked...
removeClass(document.getElementById(show), 'hidden');
}
function addClass(el, className) {
var cls = el.className.match(/\S+/g) || [];
if (!hasClass(el, className)) {
cls.push(className);
}
el.className = cls.join(' ');
}
function removeClass(el, className) {
var cls = el.className.match(/\S+/g) || [];
if (hasClass(el, className)) {
cls.pop(className);
}
el.className = cls.join(' ');
}
function hasClass(el, className) {
var re = new RegExp('(^|\\s+)' + className + '(\\s+|$)');
return re.test(el.className);
}
However, I strongly suggest using a javascript library such as JQuery for DOM manipulation and don't get carried away like myself and write vanilla javascript...

Related

Toggle display of an an element when you click on another element

I have a p element and a hidden pre element. I want to make it so that when you click on a p element with (for example) id/class = "p1", it changes the display of the pre element with (for example) id/class = "pre1".
This is my javascript code :
var p = 1;
setInterval(function() {
if(p <= document.querySelectorAll(".show").length) {
document.getElementById("display-pre"+p).onclick = function() {
console.log(p);
if(document.getElementById("display-pre-a"+p).style.display == '') {
document.getElementById("display-pre-a"+p).style.display = 'block';
} else if(document.getElementById("display-pre-a"+p).style.display == 'block') {
document.getElementById("display-pre-a"+p).style.display = 'none';
}
};
p++;
if(p > document.querySelectorAll(".show").length) {p = 1;}
}
}, 100);
This code kind of works but not really. It sometimes changes other elements and sometimes does nothing.
This is my full javascript code : https://pastebin.com/wEwdKKLy
This is my html :
<div id="test-div">
<input type="text" id="search"/>
<button type="submit" onclick="query()">Submit</button>
<button type="submit" onclick="newInput()">New</button>
<button type="submit" onclick="remove()">Delete</button>
<button type="submit" onclick="deleteAll()">Delete All</button>
<div class="query-div"><p class="query-p">Test-a</p></div>
<div class="query-div"><p class="query-p">Test-b</p></div>
<div class="query-div"><p class="query-p">Test-ba</p></div>
<p id="query-show0">TEST-SHOW</p>
<p id="child"></p>
</div>
Note : elements with class "show" have display none
I tried doing this with jquery but I'm just began learning jquery yesterday and it didn't work (I had the same problem as this).
Jquery code I tried : https://pastebin.com/cBisCmEZ
Thank you for your help.
Here is the solution for you
$("p[data-id]").on("click", function() {
var idFound = $(this).data("id");
$("[data-pre='"+ idFound +"']").toggleClass("show");
});
pre {
display:none;
}
.show {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p data-id="p1">This is the paragraph</p>
<pre data-pre="p1">This is the pre<pre>
I recommend using a button element for anything you click so that it stays accessible.

(One button creates one element) multiple times

I'm trying to have a setup where there are multiple buttons that each add one element (and one only) to a list (further down my webpage) + disables the button which was just clicked (but not the other buttons). Moreover, if you click on the corresponding element that was created, it deletes itself and enables the corresponding button back.
I managed to do it for one instance of a button, with the following code :
Javascript :
var btn1 = document.getElementById('btn1')
, sortie = document.getElementById('sortie');
function createSortie() {
var d = document.createElement("span");
d.id = "sortieBtn1";
d.className = "label label-success";
d.onclick = removeSelf;
d.innerHTML = "Hey, sup', now click on me to make me disappear";
sortie.appendChild(d);
}
function removeSelf() {
document.getElementById('sortieBtn1').remove();
document.getElementById('btn1').disabled = false;
}
function modifyButton(a) {
document.getElementById(a).disabled = true;
}
HTML :
<button class="btn btn-primary" id="btn1" onclick="createSortie();modifyButton(this.id)">Click on me to create a new element</button><br />
<br/>
<br/>
Sortie :
<div id="sortie"></div>
Example : http://www.codeply.com/go/SEL7ZqBI49
I now want it for multiple buttons, I could of course do something like this, but there are smarter ways to do achieve what I need (*), namely, more buttons and obviously, without having designated functions for each pair of button/created element.
(*) : maybe - but not mandatory - with something similar to function factories in R ?
Any idea on how to achieve that ? Thanks.
You can actually pass the reference to the clicked button as a parameter to the onclick function which makes things lots easier than trying to work with ids. Also, you won't have to find the elements every time and thus you can apply to as many items as you want. Check a working example:
var btns = document.getElementsByClassName('.btn'),
sortie = document.getElementById('sortie');
// Creates the labels on the output div when a button is clicked
function createSortie(button) {
// Create a label using a <span> element
var label = document.createElement("span");
// The ID will not be used but it's useful to link it to the
// originating button in some way
label.id = "sortie" + button.id;
label.className = "label label-success";
// Set click handler on the label
label.onclick = function() {
// Remove itself, using self-reference as argument
removeLabel(label);
// Toggle the originating button to enabled again
// (disabled = false)
toggleButton(button, false);
};
label.innerHTML = "I''m label for " + button.id;
// Set button to disabled
toggleButton(button, true);
// Add this label to sortie
sortie.appendChild(label);
}
// Removes a label, passed as parameter
function removeLabel(label) {
label.remove();
}
// Toggles a button ON or OFF, as specified on the state parameter
function toggleButton(button, state) {
button.disabled = state;
}
.label {
cursor: pointer;
display: block;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<h3>Buttons</h3>
<button class="btn btn-primary" id="btn1" onclick="createSortie(this);">Element 1</button>
<br />
<button class="btn btn-primary" id="btn2" onclick="createSortie(this);">Element 2</button>
<h3>Sortie :</h3>
<div id="sortie">
</div>
I also forked your Codeply: http://www.codeply.com/go/cJwYL0iBeY
Feel free to ask anything.
If you use classes for the buttons, and then use a number in the ID's, it would be easy to target the sortie belonging to each button, something like
var buttons = document.getElementsByClassName('btn');
for (var i=0; i<buttons.length; i++) {
buttons[i].addEventListener('click', btnClick);
}
function btnClick() {
var sortie = document.getElementById('sortie' + this.id.replace('btn',''));
createSortie(sortie, this);
}
function createSortie(sortie, button) {
var d = document.createElement("span");
d.className = "label label-success";
d.addEventListener('click', function() {
button.disabled = false;
this.remove();
});
d.innerHTML = "Hey, sup', now click on me to make me disappear";
sortie.appendChild(d);
button.disabled = true;
}
<button class="btn btn-primary" id="btn1">Click on me to create a new element</button><br />
<br/><br/>
Sortie :
<div id="sortie1"></div>
<br/><br/>
<button class="btn btn-primary" id="btn2">Click on me to create a new element</button><br />
<br/><br/>
Sortie :
<div id="sortie2"></div>
<br/><br/>
<button class="btn btn-primary" id="btn3">Click on me to create a new element</button><br />
<br/><br/>
Sortie :
<div id="sortie3"></div>
I created a fiddle for you, it is mostly based on relative selection and not on IDs, i pass the whole element in function and then do further action on that basis, have a look
Fiddle
HTML
<div>
<button class="btn btn-primary" id="btn1" onclick="createSortie(this);modifyButton(this)">Click on me to create a new element</button><br />
<br/>
<br/>
Sortie :
<div class="sortie"></div>
</div>
<div>
<button class="btn btn-primary" id="btn1" onclick="createSortie(this);modifyButton(this)">Click on me to create a new element</button><br />
<br/>
<br/>
Sortie :
<div class="sortie"></div>
</div>
JS
function createSortie(elem) {
elem.parentElement.querySelector('.sortie').innerHTML+='<span class="label label-success" onclick="removeSelf(this)">Hey, sup, now click on me to make me disappear</span>';
}
function removeSelf(ele) {
console.log( ele.parentElement.parentElement.querySelector('button'));
ele.parentElement.parentElement.querySelector('button').removeAttribute('disabled')
ele.remove();
}
function modifyButton(ele) {
ele.setAttribute('disabled','disabled')
}

Use two or more Buttons to Show/hide and replace text in single DIV

I'm building an about us page and I'm hoping to use JavaScript to show/hide/replace a DIV's content with a vision statement or a bio depending on which is clicked by the user. I'm brand new to using script, so I'm hoping there is someone who has done this before.
I currently have a button for the bio and one for the vision and while I'm able to show and hide text with no problem I have no clue how to replace the DIV so that the Bio and Vision don't show at the same time.
Here is what I have so far:
function showhide(id) {
var e = document.getElementById(id);
e.style.display = (e.style.display == 'block') ? 'none' : 'block';
}
<button type="button" onclick="javascript:showhide('vision')">Vision</button>
<button type="button" onclick="javascript:showhide('bio')">Bio</button>
<div id="vision" style="display: none;">
<p>This is my vision</p>
</div>
<div id="bio" style="display: none;">
<p>This is my bio</p>
</div>
I'd also like the button text to change to "Hide Bio" or "Hide Vision" depending on which is revealed as well.
If anyone could help with this it would be GREATLY appreciated for a Java Noob like me.
This is also my first time using a forum like this so any pointers or feedback is appreciated...gotta start somewhere, right?
UPDATE - I attached an image to give a better idea of what I'm try to accomplish.
There are a couple of issues with logic. If you show/hide one div, you'll still need to hide/show the second div. So you can either add more lines of code to do that.. or simply you can use one div and update its content based on the button clicked.
so you can try this:
<script>
var textStrings = {"author1": {"Vision":"this is author1 vision", "Bio":"this is author1 bio"},
"author2": {"Vision":"this is author2 vision", "Bio":"this is author2 bio"},
"author3": {"Vision":"this is author3 vision", "Bio":"this is author3 bio"}};
function showhide(element) {
reset();
var id=element.id;
var author = document.getElementById("authors").elements["authors"].value;
var flag = document.getElementById('content').innerHTML == textStrings[author][id];
document.getElementById('content').innerHTML = flag ? "" : textStrings[author][id];
element.innerHTML = flag ? id : "hide " + id;
}
function reset(){
for (var k in textStrings["author1"]){
document.getElementById(k).innerHTML = k;
}
}
function resetAuthor(){
document.getElementById('content').innerHTML = ""
reset();
}
</script>
<form id="authors">
<input type="radio" name="authors" id="author1" onchange="resetAuthor()" value="author1" checked> author 1
<input type="radio" name="authors" id="author2" onchange="resetAuthor()" value="author2"> author 2
<input type="radio" name="authors" id="author3" onchange="resetAuthor()" value="author3"> author 3
</form>
<div style="display:inline">
<button type="button" id="Vision" onclick="javascript:showhide(this)">Vision</button>
<button type="button" id="Bio" onclick="javascript:showhide(this)">Bio</button>
</div>
<div style="display: block;">
<p id="content"></p>
</div>
This code also toggles/set contents as empty if you hit the button again.
DEMO
Try to pass the this object into the inline event handler and check the content's display state to toggle the button's text,
HTML:
<button type="button" onclick="javascript:showhide('vision',this)">Vision</button>
<button type="button" onclick="javascript:showhide('bio',this)">Bio</button>
<div id="vision" style="display: none;">
<p>This is my vision</p>
</div>
<div id="bio" style="display: none;">
<p>This is my bio</p>
</div>
JS
function showhide(id,elem) {
var e = document.getElementById(id);
var cond = (e.style.display == 'block');
e.style.display = cond ? 'none' : 'block';
elem.textContent = (id == "vision") ? (cond ? "Show Vision" : "Hide Vision")
: (cond ? "Show Bio" : "Hide Bio");
}
DEMO
Try this out.
var prevPage = "";
var currPage = "";
function showhide(event) {
prevPage = currPage;
currPage = event.id.split("_")[1];
if(prevPage !== currPage){
showEle(currPage);
if(prevPage !== ''){
hideEle(prevPage);
}
} else {
toggle(currPage);
}
}
function toggle(id){
var curr = document.getElementById(id);
if(curr.style.display === 'block'){
curr.style.display = 'none';
updateBtn('btn_'+id, 'Show');
} else {
curr.style.display = 'block';
updateBtn('btn_'+id, 'Hide');
}
}
function updateBtn(id, newStr){
var btn = document.getElementById(id);
btn.innerHTML = newStr + ' ' + btn.innerHTML.split(' ')[1];
}
function showEle(id){
document.getElementById(id).style.display = 'block';
updateBtn('btn_'+id, 'Hide');
}
function hideEle(id){
document.getElementById(id).style.display = 'none';
updateBtn('btn_'+id, 'Show');
}
<button id="btn_vision" type="button" onclick="showhide(this)">Show Vision</button>
<button id="btn_bio" type="button" onclick="showhide(this)">Show Bio</button>
<button id="btn_xyz" type="button" onclick="showhide(this)">Show Xyz</button>
<button id="btn_abc" type="button" onclick="showhide(this)">Show Abc</button>
<div id="vision" style="display: none;">
<p>This is my vision</p>
</div>
<div id="bio" style="display: none;">
<p>This is my bio</p>
</div>
<div id="xyz" style="display: none;">
<p>This is my xyz</p>
</div>
<div id="abc" style="display: none;">
<p>This is my abc</p>
</div>
Note: You might want to initialize the currPage with the first page's id since it gives a better feel.
Say currPage = "vision" and also make display block for div id = "vision".

changing a button text after loading/resetting by bootstrap

I'm trying to create like / unlike buttons using bootstrap3.
Here is my button
<button type="button" id="testBtn"
class="btn btn-success glyphicon glyphicon-thumbs-up"
data-loading-text=" ... " onclick="like()" >
4</button>
Here is a simplified version of my JavaScript function without AJAX call:
function like(){
var btn = $('#testBtn');
btn.button('loading');
var current = parseInt(btn.text());
current++;
console.log(current);
btn.button('reset');
btn.text(current);
}
Usually this works and button text increments on each click.
However now that I'm using bootstrap, after resetting the button it keeps the old text even though in the console.log(current); I see a new incremented one.
I think because I'm using bootstrap button loading/resetting I have to do something else to change button text.
'btn.text()' is getting data-loading-text value, not '4'. So I updated my answer which created vote up and down for you in FIDDLE
HTML
<button type="button" id="testBtn" class="btn btn-success glyphicon glyphicon-thumbs-up" data-loading-text=" ... ">
4</button>
<button type="button" id="testBtnDown" class="btn btn-success glyphicon glyphicon-thumbs-down" data-loading-text=" ... ">
4</button>
JS
$('#testBtn').click(function () {
var cnt=4;
var btn = $(this);
btn.button('loading');
setTimeout(function () {
cnt++;
btn.button('reset');
btn.text(' ' + cnt);
}, 1000);
});
$('#testBtnDown').click(function () {
var cnt=4;
var btn = $(this);
btn.button('loading');
setTimeout(function () {
if (cnt > 0) {
cnt--;
}
btn.button('reset');
btn.text(' ' + cnt);
}, 1000);
});
The reason for this is related to that function not being on the global context. You can find more details on this answer here.
Basically, recommendation is to do the binding on Document Ready and not to use onclick for this.
Hope this helps!

When clicking on button like showcaps,small,number no change is happening to the div in html, visibility not working

stack.html:
when clicking on the button show caps,show small,show number nothing will happening,showcaps only dispaly kcaps div but now it display all the divs.iam expecting a result such that showcaps only display the kcaps div,similarly showsmall displays ksmall,shownumber displays knumber.The java script file(ext.js) should be an external file,that must be kept separate.
<html>
<head>
<script src="ext.js"></script>
</head>
<body>
<!--Caps Div-->
<div class="bttn1" id="kcaps">
<button class="CSSButton" id="A">A</button>
</div>
<div class="bttn2" id="ksmall">
<button class="CSSButton" id="a">a</button>
</div>
<div class="bttn3" id="knumber">
<button class="CSSButton" id="0">0</button>
</div>
<button type="button" id="ckey"/> Show caps </button>
<button type="button" id="skey"/> Show small </button>
<button type="button" id="nkey"/> Show number </button>
</body>
</html>
ext.js:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('ckey').addEventListener('click', showElem);
document.getElementById('skey').addEventListener('click', showElem2);
document.getElementById('nkey').addEventListener('click', showElem3);
});
function showElem(e)
{
document.getElementById('kcaps').style.visibility. = "visible";
document.getElementById('ksmall').style.visibility = "hidden";
document.getElementById('knumber').style.visibility = "hidden";
}
function showElem2(e)
{
document.getElementById("kcaps").style.visibility="hidden";
document.getElementById("ksmall").style.visibility="visible";
document.getElementById("knumber").style.visibility="hidden";
}
function showElem3(e)
{
document.getElementById("kcaps").style.visibility="hidden";
document.getElementById("ksmall").style.visibility="hidden";
document.getElementById("knumber").style.visibility="visible";
}
You're using wrong id:-
In your html the if of the buttons are ckey, skey, nkey
and in the javascript file you've written:-
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('ckeys').addEventListener('click', showElem);
document.getElementById('skeys').addEventListener('click', showElem2);
document.getElementById('nkeys').addEventListener('click', showElem3);
});
You should write:- ckey instead of ckeys and so on.
And remove the extra . in showElem function
function showElem(e)
{
document.getElementById('kcaps').style.visibility.(* extra dot should be removed) = "visible";

Categories

Resources