Div doesn't stay visible - javascript

I have 4 links. When I click the first link div 1 should be displayed and the other 3 hidden.
When I click link 2, div 2 should be displayed and the other 3 hidden, and so on...
What I did:
With CSS I've set the class of the 4 divs to display: none
Created 4 functions with javascript that set the display property of the correct div to block and the 3 others to none
Call the function when clicking the link
When I click a link, the div is shown for a quarter of a second but then it disappears again
CSS:
.CatDiv {
display:none;
}
JS function:
function showKadoballonnen() {
document.getElementById("Kadoballonnen").style.display = "block"
document.getElementById("Geschenkmanden").style.display = "none"
document.getElementById("Pampercadeaus").style.display = "none"
document.getElementById("OrigineleVerpakkingen").style.display = "none";
}
Calling the function:
Kadoballonnen
Div that has to be called:
<div id="Kadoballonnen" class="CatDiv">TEST</div>
function showKadoballonnen(e) {
e.preventdefault();
document.getElementById("Kadoballonnen").style.display = "block";
document.getElementById("Geschenkmanden").style.display = "none";
document.getElementById("Pampercadeaus").style.display = "none";
document.getElementById("OrigineleVerpakkingen").style.display = "none";
}
.CatDiv {
display: none;
}
Kadoballonnen
<div id="Kadoballonnen" class="CatDiv">TEST</div>
<div id="Geschenkmanden" class="CatDiv">TEST</div>
<div id="Pampercadeaus" class="CatDiv">TEST</div>
<div id="OrigineleVerpakkingen" class="CatDiv">TEST</div>
What am I missing?

All is easier than you think. In your tag you got "href" with empty parameter. It makes your page reloading while pressing on it.
So all you should do is to write "#" as a parameter.
Kadoballonnen

You should avoid empty href attribute on a link. Use a button instead.
If it still does not work, attach your method to window object. Also, I don't recommend this approach, you should handle it in your Javascript by targetting at your DOM elements using an ID for example and adding your event listener from here.
document.getElementById('myelement').addEventListener('click', showKadoBallonnen);

You have a few errors in your code, and you also need to stop your link (<a>) firing.
On your link, add return false;:
Kadoballonnen
<!-- ^ Also, add href="#" so you don't have an empty href -->
Also, add semicolons to the end of each line of your javascript:
document.getElementById("Kadoballonnen").style.display = "block";
document.getElementById("Geschenkmanden").style.display = "none";
document.getElementById("Pampercadeaus").style.display = "none";
document.getElementById("OrigineleVerpakkingen").style.display = "none";

I was running into this problem while writing some coffeescript in a rails application. Another answer helped me.
The solution is the event.preventDefault() as shown below:
app/views/posts/index.html.erb:
<%= link_to "Some link", '#', id: 'some-link' %>
<div class="some-div">
<h4>Some list</h4>
<ul id='some-list'>
<li>cats</li>
<li>and</li>
<li>dogs</li>
</ul>
</div>
app/assets/javascripts/posts.coffee:
$(document).on 'turbolinks:load', ->
$('#some-link').click (event) ->
event.preventDefault()
$('#some-list').toggle()

I managed to make it working: https://jsfiddle.net/ke81koj6/
function showKadoBallonnen() {
document.getElementById("one").style.display = "block";
document.getElementById("two").style.display = "none";
document.getElementById("three").style.display = "none";
document.getElementById("four").style.display = "none";
}
EDIT
Edited the fiddle and now works with the press on a button. It's better to use a button than an anchor with a empty href.
HTML:
<button id="button" onclick="showKadoBallonnen()">click here</button>
JS:
document.getElementById("button").onclick = showKadoBallonnen;

Related

Link to another page at an anchor point and also show div

I want to have a single link that will take you to a different HTML page, down to a specific anchor tag, and also show a div that would be hidden by default.
I know how to link to another page and to an anchor on that page.
Link
On anotherpage.html, I have code to show that div.
<a onclick="toggle_visibility('hiddendiv');">Show div</a>
The Javascript for that is this:
<script type="text/javascript">
<!--
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//-->
</script>
But I don't know how I could get the first link to also do what the second link is doing. Is this possible? This is for a local site, so I think I'm limited to just HTML, Javascript, and CSS.
Edit: I'm going to use this with Tipue Search (http://www.tipue.com/slide/). I'm going to have the search results point to specific sections on specific pages which have divs that are hidden by default. But in those sections, there are buttons to show those divs. I also included the Javascript I'm using for that above.
The HTML page with the second link either has a <script> tag pointing to an external javascript file providing the toggle_visiblility function or that function is defined directly on the page.
If you add the function definition either by linking to the javascript file <script src="myscripts.js"></script> or copy the definition directly into a <script> tag.
Once the toggle_visibility function is available on your page, the first link can read simply Link , obviously replacing hiddendiv with the appropriate string.
can you please check this project at: https://github.com/nezirz/anchor_scroll
First page contains only link to second one:
<div>
go to index2 and show diw
</div>
And second page contain this code:
<div>
<div id="anchor1" style="background-color:blue; height:500px;">
</div>
</div>
<div>
<div id="anchor2" style="background-color:green; height:400px;display: none;">
</div>
</div>
<div>
<div id="anchor3" style="background-color:red; height:200px;">
</div>
</div>
<script>
window.onload = function() {
var anchor = window.location.hash.substr(1);
console.log(anchor);
setTimeout(function(){
myFunction(anchor);
Element.prototype.documentOffsetTop = function () {
return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop() : 0 );
};
var top = document.getElementById( anchor ).documentOffsetTop() - (window.innerHeight / 2 );
window.scrollTo( 0, top );
}, 2000);
function myFunction(element) {
console.log(element);
var x = document.getElementById(element);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
};
</script>
This is only proof of concept, please update it to your exact requirement. I think that it is not complicated to you.

Toggle visibility for multiple divs with one function: navigation bar

My Assignment: Hi! I am doing an assignment in school where I am supposed write code in Javascript in order to toggle visibility for the submenus each belonging to their own topmenu in a navigation bar for a webpage. The visibility should be set to hidden by default and should be shown when a topmenu is clicked on.
I know how to toggle visibility for ONE submenu belonging to a topmenu, but fail to make my code work for multiple elements. My HTML-code:
<a class="left_top1" onclick = "toggle()">Opinion</a><br>
<div class="left_submenu_1" style="display: none;">
<a class="left_sub1">Leaders</a><br>
<a class="left_sub1">Debates</a><br>
</div>
<br>
<a class="left_top2" onclick = "toggle()">Economy</a><br>
<div class="left_submenu_2" style="display: none;">
<a class="left_sub2">News</a><br>
<a class="left_sub2">Your Economy</a><br>
</div>
My Problem: The topmenus I speak of are "Opinion" and "Economy". The visibility of the div with the class "left_submenu_1" should be toggled when you click the topmenu "left_top1". Thus should the visibilily of the div with the class "left_submenu_2" be toggled when you click the topmenu "left_top2". This is what I fail to do. My Javascript code is so far:
function toggle() {
var e = document.querySelectorAll("div.left_submenu_1, div.left_submenu_2");
for (var i=0; i < e.length; i++) { // I know this will enable/disable the visibility for ALL elements selected from the querySelectorAll, which should NOT happen
if(e[i].style.display == "none") {
e[i].style.display = "block";
} else if(e[i].style.display == "block") {
e[i].style.display = "none";
}
}
}
Anyone who knows how to solve this issue of mine? I know there are errors in the for-loop (as I wrote next to it), but this is the best I can manage for now.
Please note: We are NOT allowed to use jQuery or to give the topmenus id:s, as the idea is to use one general function to toggle the visibility. Furthermore, the code which enables the toggle-function should be done in Javascript.
I would approach it by passing the class name of the div to be shown (or hidden) into the function to begin with.
HTML
<a class="left_top1" onclick = "toggle('.left_submenu_1')">Opinion</a>
Then in the function you can grab the element and toggle it's display state.
JavaScript
function toggle(qs) {
var e = document.querySelector(qs);
e.style.display = e.style.display === 'block' ? 'none' : 'block';
}
The e.style.display === 'block' ? 'none' : 'block' part is saying if the elements display state is equal to block, return none, otherwise return block.
The return value is set as the new element display state due to the e.style.display = beforehand.
Tring to make it work modifying it as less as possible :
- use onClick="toggle(this)" in the anchors tags
- use a bit different toggle function like:
function toggle (el) {
var e = document.querySelectorAll('.' + el.className.replace('top', 'submenu_'))[0];
e.style.display = e.style.display.match(/none/) ? '' : 'none';
}
hope it helps, but I have to suggest You to make a small step forward and search for event delegation. Bye

Show/Hide onClick button not working

Hey guys I have searched for many answers and none of them seem to be working so I am going to put my code here and hopefully you can help me figure this out.
I am going to have two buttons. The first button (show_Chappie) is going to show the hidden contents and another button (hide_Chappie) and hides it self when clicked.
The second button (hide_chappie) is going to hide the contents and bring back the first button (show_chappie). The hide_chappie button itself would also be hidden.
The information div is already hidden from the start. I did this on the CSS using the display:none;
Here's my HTML code so far:
<button class ="show_chappie" onclick="showInfo()">Show More</button>
<div class="info">Info here.</div>
<button class ="hide_chappie" onclick="hideInfo()">Show Less</button>
Here's my JavaScript code so far:
function showInfo(){
document.getElementById('chappie_info').style.display = "inline-block";
document.getElementById('show_chappie').style.display = "none";
document.getElementById('hide_chappie').style.display = "inline-block";
}
I haven't written the code for the hide_chappie button because I wanted to see this working first.
So where have I gone wrong here? Thanks for the help in advance.
You are trying to get the elements by id while they have a class, you should change the elements class to id like this:
<button id="show_chappie" onclick="showInfo()">Show More</button>
<div id="info">Info here.</div>
<button id="hide_chappie" onclick="hideInfo()">Show Less</button>
you should change your code to:
<button id ="show_chappie" onclick="showInfo()" >Show More</button>
<div class="info">Info here.</div>
<button id= "hide_chappie" onclick="showInfo()">Show Less</button>
if you want to use class here,you should change your Javascript Code to
function showInfo(){
document.getElementByClass('chappie_info')[0].style.display = "inline-block";
document.getElementByClass('show_chappie')[0].style.display = "none";
document.getElementByClass('hide_chappie')[0].style.display = "inline-block";
}
because function getElementsByClass returns a collection,so you should add [] to find out the result you want!
It's kind of annoying to turn all id's into classes, you can use:
function showInfo(){
document.getElementsByClassName('chappie_info').style.display = "inline-block";
document.getElementsByClassName('show_chappie').style.display = "none";
document.getElementsByClassName('hide_chappie').style.display = "inline-block";
}
This is supported by practically every browser these days so I wouldn't worry about that. If that is still an issue an you need to support ancient browsers, use this:
document.getElementsByClassName = function (a) {
var b = document.getElementsByTagName('*'), i, c=[];
for (i = 0; i < b.length; i += 1) { b[i].getAttribute('class')===a&&c.push(b[i]); }
return c;
};

Javascript Collapsible Menu (hide the other elements)

I have the following working Javascript function:
function collapsible(zap) {
if (document.getElementById) {
var abra = document.getElementById(zap).style;
if (abra.display == "block") {
abra.display = "none";
} else {
abra.display = "block";
}
return false;
} else {
return true;
}
}
When I use the following in html code it displays or hides the "element" div:
<li>Element</li>
Thats working fine. But the problem is, that I want to use the function for multiple links, and then the other elements, that were clicked before, stay, open.
How can I reprogram the code, so that only one div stays open and the other gets closed if i click on another link?
Thanks beforehand!
If you could use jQuery and more importantly jQueryUI accordion I think it would accomplish exactly what you're looking for.
However, without using those two, here is how I would structure it. Like mentioned above, I would use classes to modify the styles of the divs you want shown or hidden. Then the js code can just toggle those classes on each of your elements. The slightly more difficult part (without jquery) is modifying class values since in your final application you may have lots of classes on each div. This is just a very crude example to get you going.
Working JSFiddle Example
Sample DOM
<div >
<li>Element1</li>
<div id='elem1' class='myelem visible'>
Element 1 contents
</div>
</div>
<div >
<li>Element2</li>
<div id='elem2' class='myelem'>
Element 2 contents
</div>
</div>
<div >
<li>Element3</li>
<div id='elem3' class='myelem'>
Element 3 contents
</div>
</div>
Sample JS
window['collapsible'] = function(zap) {
if (document.getElementById)
{
var visDivs = document.getElementsByClassName('visible');
for(var i = 0; i < visDivs.length; i++)
{
visDivs[i].className = visDivs[i].className.replace('visible','');
}
document.getElementById(zap).className += " visible";
return false;
}
else
return true;
}
Sample CSS:
.myelem {
display: none;
}
.visible {
display: block;
}
The way to go is to create a class(or maybe two), like collapsible and active or open that has this style(display: block or none) and then you working adding or removing the class.
The logic would be:
Links that has the class collapsible when clicked would add the active or open class which would give the behavior that remains opens(or active) by css.
If you want to hide others elements you would look for the elements with the class collapsible and then remove the active(or open) class if has any.
Here is my solution: http://jsfiddle.net/g5oc0uoq/
$('.content').hide();
$('.listelement').on('click', function(){
if(!($(this).children('.content').is(':visible'))){
$('.content').slideUp();
$(this).children('.content').slideDown();
} else {
$('.content').slideUp();
}
});
show() and hide() can be used instead of slideUp() and slideDown() if you have performance issues.

Display : None/Block Style Tab Menu Creation with Buttons and Javascript

function tab_menu(){
if (buttonObject.value == value){
document.getElementById("div1").style.display = "block";
}
}
i was trying when click to buttons check Button Value and show a div based on Button's Value and hide others divs it should show just one div at same time. I wonder there is a javascript Master who can solve this problem.
SCRIPT:
function tabmenu(buttonObject){
var value = buttonObject.value
var target = document.getElementById(value);
if(target) {
var siblings = target.parentNode.getElementsByTagName("DIV");
for(i=0;i<siblings.length;i++){
siblings[i].style.display = "none";
}
target.style.display = "block";
}
}
HTML:
<div>
<div id="tab1">Tab1</div>
<div id="tab2">Tab2</div>
<div id="tab3">Tab3</div>
</div>
<button onclick="tabmenu(this);" value="tab1">Tab1</button>
<button onclick="tabmenu(this);" value="tab2">Tab2</button>
find the tab to activate (assuming value = tab.id)
find the parent and hence it's siblings (assuming they are DIVs)
hide the siblings
show the target
You can see it working here: http://jsfiddle.net/4rWdQ/

Categories