Clear all the open div's - javascript

I have a script that open's div's by doing an onclick="toogle_visibility(id)
event but how do i do when i want to close the div that is open and open
the new div ?
Javascript/jQuery:
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
HTML:
<div class="navBar">
Social
Följer
Bokmärken
</div>
<div id="Social">
#Liam_Rab3 - TWITTER<br>
#Liam_Rab3 - INSTAGRAM<br>
#LiamRab3- FACEBOOK<br>
#Liam_Rab3 - YOUTUBE<br>
#Liam_Rab3 - FLICKR<br>
#Liam_Rab3 - TUMBLR<br>
</div>
<div id="Foljer">
Sebbe Stakset (Kartellen)
</div>
CSS:
a:link {
color:white;
text-decoration:none;
-o-transition:.5s;
-ms-transition:.5s;
-moz-transition:.5s;
-webkit-transition:.5s;
transition:.5s;
}
a:hover {
color:white;
text-decoration:none;
font-size:100%;
}
a:visited {
text-shadow:0px 0px 0px #0066BB;
color:white;
}
#social {
display:none;
}
#Foljer {
display:none;
}
DISCLAIMER!
These links in the #social and #bokmarken links is'nt for commercial purpose.

You can use JQuery Toggle
<div id="clickme">
Click here !!!
</div>
<a href="#social" >Social</a>
$( "#clickme" ).click(function() {
$( "#social" ).toggle(); //With no parameters, the .toggle() method simply toggles the visibility of elements:
});
First choose the control you are willing to hide/show, then use that control's id as follows:
$('#<id-of-that-control>').toggle();
Now you can call that in the onclick event handler of a button or div as you wish.
How it might appear for you is:
JS
function toggle_visibility(id) {
$('#' + id).toggle();
}
HTML
<div class="navBar">
Social
Följer
Bokmärken
</div>
Update:
As pointed out by Brodie, seemingly you might always look into the solution provided by Niet the Dark Absol. As he provides you a pure JS implementation. My solution will give you insight of using a library like JQuery and it's API of toggle. Jquery provides a wide range of built-in functionality that helps you to do things quickly. What my piece of code provides you is usage of an api i.e. toggle, which when used will be same as the hide and show behavior.

Basically, you need to close all DIVs, and toggle the current one.
Try this:
var ids = ['Social','Foljer','Bokmarken'];
function toggle_visibility(id) {
var l = ids.length, i, e;
for( i=0; i<l; i++) {
e = document.getElementById(ids[i]);
if( id != ids[i])
e.style.display = 'none';
else if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
}

Related

Show and Hide Javascript HTML5

So, I'm doing my designer-portfolio in html and I wanted to have a menu that only shows when this character is pressed...
But I'm new on programming and my codes are very simple, so I'm using this:
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.visibility == 'hidden')
e.style.visibility = 'visible';
else
e.style.visibility = 'hidden';
}
function untoggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.visibility == 'visible')
e.style.visibility = 'hidden';
else
e.style.visibility = 'visible';
}
<div id="openmenu" style="visibility: visible;" onclick="toggle_visibility('menu'); onclick=toggle_visibility('closemenu');">openmenu</div>
<div id="closemenu" style="visibility: hidden;" onclick="untoggle_visibility('menu'); onclick=untoggle_visibility('closemenu');">closemenu</div>
<div id="menu" style="visibility: hidden;">...</div>
The problem is it only works once...
When I click on #openmenu it shows the #menu and the #closemenu, and when I click on #closemenu it hiddes the #menu and the #closemenu.
BUT it only works once, so if I press #openmenu after #closemenu, it won't work...
Your code is wrong.
onclick="toggle_visibility('menu'); onclick=toggle_visibility('closemenu');"
So what happens with the above code is it runs once. And when it runs it reassigns onclick because you have onclick=functionCall
So after it runs you basically have <div onclick=undefined> because the function did not run.
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.visibility == 'hidden')
e.style.visibility = 'visible';
else
e.style.visibility = 'hidden';
}
function untoggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.visibility == 'visible')
e.style.visibility = 'hidden';
else
e.style.visibility = 'visible';
}
<div id="openmenu" style="visibility: visible;" onclick="toggle_visibility('menu');toggle_visibility('closemenu');">openmenu</div>
<div id="closemenu" style="visibility: hidden;" onclick="untoggle_visibility('menu');untoggle_visibility('closemenu');">closemenu</div>
<div id="menu" style="visibility: hidden;">...</div>
How would most people code it? By toggling a class.
function toggle_visibility(ids) {
ids.forEach( function (id) {
var elem = document.getElementById(id);
elem.classList.toggle('visibilityHidden')
})
}
.visibilityHidden {
visibility: hidden;
}
/* use hidden if you do not want it to take up space */
.hidden {
display: none;
}
<div id="openmenu" onclick="toggle_visibility(['menu','openmenu','closemenu']);">openmenu</div>
<div id="closemenu" class="visibilityHidden" onclick="toggle_visibility(['menu','openmenu','closemenu']);">closemenu</div>
<div id="menu" class="visibilityHidden">...</div>
Most developers would not use inline event handlers either, but that is a different question.

Some equivalent to stop Propagation?

I have a issue...
I'm trying to get element ID using:
$('div').on('click',function(ev){
ev.stopPropagation();
checkEl = $(this).attr('id');
if(checkEl != 'topics' && checkEl != 'exfillVal' ){
$("#topics").hide();
}
})
But... it also block other elements with different event listener (click one's)...
How can i achieve that?
$(function(){
var newHTML =[];
$('div').on('click',function(ev){
ev.stopPropagation();
checkEl = $(this).attr('id');
if(checkEl != 'topics' && checkEl != 'exfillVal' ){
$("#topics").hide();
newHTML.push('<span class="reopen" title="usuń">' + checkEl + '</span>');
}
$('#new').html(newHTML);
})
$('body').on('click', '.reopen',function(){
$(this).hide();
$("#topics").show();
})
// but that work
$('.reopen').on('click',function(){
$(this).hide();
$("#topics").show();
})
})
#main{
position:relative;
width:300px;
background-color:red;
}
div{
position:relative;
border:1px solid gray;
padding:15px;
width:100%:
}
#one{
background-color:black;
}
#two{
background-color:blue;
}#three{
background-color:orange;
}#four{
background-color:yellow;
}#fifth{
background-color:purple;
}
span{
padding:3px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main">
<div id="one">
<div id="three">
<div id="four">
<div id="fifth">
</div>
</div>
</div>
</div>
<div id="topics">SOME COOL DATA </div>
</div>
<div id="new"></div>;
As you can see when i click on div with id "one,two,three,four,fifth,main" everything is working... but when append span element were clicked... Event listener aren't working correct, because append element schooled be hidden when click... instead of it just create another element.... where i make a issue?
Can i replace propagation with something else?
How i can rearrange a code?
Any help will be appreciate
You could verify whether the handler is dealing with the original element or with a parent by comparing ev.target with ev.currentTarget. When they are the same then you know the click was really on that element, and it's not a parent you are looking at:
$('div').on('click',function(ev){
checkEl = $(this).attr('id');
if (ev.target === ev.currentTarget && checkEl != 'topics' && checkEl != 'exfillVal' ){
$("#topics").hide();
}
});

javascript expand/collapse text - collapse on default

I'm very inexperienced in javascript but have managed (with the help of google) to put together the following expandable/collapsible link
<script type="text/javascript">
function toggleMe(a) {
var e = document.getElementById(a);
if(!e) return true;
if(e.style.display == "none") {
e.style.display = "block"
}
else {
e.style.display = "none"
}
return true;
}
</script>
<p>
<input onclick="return toggleMe('para1')" style="font-size:18px; color:#008080;" type="text" value="LINK TO EXPAND" />
</p>
<p id="para1">
<strong><em>text text text text</em></strong>
</p>
The only problem with it is that it is expanded by default and I wanted it collapsed by default. Can anyone help with this? Thank you!
Also, if anyone knows how to get +/- signs next to the link that change depending on whether it is expanded or collapsed, that would be great.
<script type="text/javascript">
function toggleMe(a) {
var e = document.getElementById(a);
var toggleIcon = document.getElementById('toggle-icon');
if(!e) return true;
if(e.style.display == "none") {
e.style.display = "block";
toggleIcon.innerHTML = '-';
}
else {
e.style.display = "none";
toggleIcon.innerHTML = '+';
}
return true;
}
</script>
<p>
<input onclick="return toggleMe('para1')" style="font-size:18px; color:#008080;" type="text" value="LINK TO EXPAND" />
<span id="toggle-icon">+</span>
</p>
<p id="para1" style="display: none;">
<strong><em>text text text text</em></strong>
</p>
You can try putting in style statement the display option like below:
<p id="para1" style="display:none"><strong><em>text text text text</em></strong></p>
That can default collapse when you open your html, hope it help you...
Options 1:
Add this to your css to hide it by default:
#para1 {
display: none;
}
Options 2:
Move your script down, and call it initially toggleMe('para1'); so you will hide it first.
<p>
<input onclick="return toggleMe('para1')" style="font-size:18px; color:#008080;" type="text" value="LINK TO EXPAND" />
</p>
<p id="para1">
<strong><em>text text text text</em></strong>
</p>
<script type="text/javascript">
function toggleMe(a) {
var e = document.getElementById(a);
if(!e) return true;
if(e.style.display == "none") {
e.style.display = "block"
}
else {
e.style.display = "none"
}
return true;
}
toggleMe('para1');
</script>
Daniel has the correct answer to your question. This is a bit more than you asked for, but I think you will have a better time if you manipulate classes instead of element styles properties. Just makes it a bit more flexible.
In the example below I wrapped your code in a common element and then changed that element's class to achieve your desired effect. That let me easily add in your plus and minus too.
It's a little raw but you can see where this can take you. Hope it helps.
https://jsfiddle.net/6xoe1b94/
function toggleMe(a) {
var e = document.getElementById('wrapper');
if(! e.classList.contains('active')) {
e.classList.add('active');
}
else {
e.classList.remove('active');
}
}
#para1{
display:none;
}
.active #para1{
display:block;
}
#plus{
display:inline-block;
}
#minus{
display:none;
}
.active #plus{
display:none;
}
.active #minus{
display:inline-block;
}
<div id='wrapper'>
<p>
<input onclick="return toggleMe('para1')" style="font-size:18px; color:#008080;" type="text" value="LINK TO EXPAND" /><span id='plus'>+</span><span id='minus'>-</span>
</p>
<p id="para1">
<strong><em>text text text text</em></strong>
</p>
</div>
I added a solution that removes the javascript and css from your html. I also changed your expand/collapse element to a div instead of input. I've added a span element within the div that changes it's text content (either + or -) based on whether #para1 is displayed or not. Also, in css I added display: none; to #para1 (this initially hides the element), cursor: pointer; (shows it is clickable when the user hovers over it) user-select: none; (stop div from highlighting when user clicks on it).
// store elements
var expandEl = document.getElementById("expand");
var plusMinusEl = document.getElementById("plusMinus");
var para1El = document.getElementById("para1");
// toggle function: pass element as argument
function toggleMe(el) {
// check if element is hidden
if(el.offsetParent === null) {
plusMinusEl.textContent = "-";
el.style.display = "block"
}
else {
plusMinusEl.textContent = "+";
el.style.display = "none"
}
}
// click function for expand div
expandEl.addEventListener("click", function() {toggleMe(para1El)});
#expand {
font-size:18px;
color:#008080;
cursor: pointer;
user-select: none; /* stop div from highlighting */
}
#para1 {
display: none;
}
<div id="expand">
LINK TO EXPAND <span id="plusMinus">+</span>
</div>
<p id="para1"><strong><em>text text text text</em></strong></p>

Javascript onclick needs 2 clicks

Each div is shown only after 2 clicks at the start.After 2 initial clicks on each div, each div showhide works with just 1 click. Javascript and html
function showhide() {
var div = document.getElementsByClassName('search_form')[0];
if (div.style.display == "none") {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
function showhide2() {
var div = document.getElementsByClassName('login')[0];
if (div.style.display == "none") {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
function showhide3() {
var div = document.getElementsByClassName('carrello')[0];
if (div.style.display == "none") {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
.search_form {
display: none;
float: right;
}
.login {
display: none;
float: right;
}
.carrello {
display: none;
float: right;
}
<div class="login-carrello">
<img src="img.png" onClick="showhide();" onmouseover="this.src='img.png'" onmouseout="this.src='gg.png'" width="50px" height="50px"> &nbsp &nbsp
<img src="img.png" onClick="showhide2()" onmouseover="this.src='img.png'" onmouseout="this.src='img.png'" width="50px" height="50px">
<img src="imgt.png" onClick="showhide3()" onmouseover="this.src='img.png'" onmouseout="this.src='img.png'" width="50px" height="50px">
</div>
are both in a single PHP page.Thanks in advance.
The problem is in JavaScript code. Since display property was initially set in css, div.style.display won't give you none. So, you have to change your code a little bit. Like this:
if(div.style.display != "block")
div.style.display = "block";
else
div.style.display = "none";
Once you set the display property using JavaScript code, you can read it using JavaScript.
Because the display property is not actually set (although it is applied through CSS), it's initial value is empty (and thus not equal to 'none' ).
If checked in the reverse order, it would work, but perhaps safer is to use an extra class (with the display property) you toggle instead.
A minimized example:
function showhide(cn) {
var div = document.getElementsByClassName(cn)[0];
div.classList.toggle('show');
}
.login-carrello >img{
width:50px;
height: 50px;
}
.search_form,.login, .carrello {
float: right;
display: none;
}
.show{
display:block;
}
<div class="login-carrello">
<img src="/wp-content/themes/kyro/img/search.png" onClick="showhide('search_form')">
<img src="img.png" onClick="showhide('login')">
<img src="imgt.png" onClick="showhide('carrello')">
</div>
<div class="search_form">search_form</div>
<div class="login">login</div>
<div class="carrello">carrello</div>
The start setting for .search_form,.login, .carrello is display:none, but adding .show overrides that. (I've also taken the liberty of parameterizing the classname to show/hide so only a single function is needed. With late binding it could be automated further, but this stays pretty close to the original)
Not sure if you're looking for a double click, or just two seperate clicks. However if a double click would satisfy your functionality requirement, you could try something like the following:
<img src="img.png" ondblclick="showhide2()" onmouseover="this.src='img.png'" mouseout="this.src='img.png'" width="50px" height="50px">

Making JavaScript menu close when clicking outside

I'm basically trying to make open menu close when user click anywhere. im new and i dont know what is problem. so far i am using this code, here is my html, css and javaScript. i think problem is in my JavaScript.
thanks for help.
HTML
<div class="menu-button" style="width:23px; cursor: pointer;" onClick="show_menu()"><span style="color:#b0acac;">▼</span></div>
<div id="dropdown_menu" class="hidden_menu">
<ul id="container">
<li>Settings<br></li>
<li>Log Out</li>
</ul>
</div>
CSS
.menu-button{
position: relative;
left:1556px;
top:-43px;
}
.hidden_menu{
display:none
}
#dropdown_menu ul li {
text-decoration:none;
display: inline;
cursor: pointer;
position: relative;
left:-20px;
top:2px;
}
#dropdown_menu ul{
width:80px;
height:90px;
background-color:#efefef;
position:relative;
top:-64px;
left:1460px;
border-color:#ff0000;
border-width:2px;
}
JavaScript
<script>
function show_menu(){
var menu = document.getElementById('dropdown_menu');
if(menu.style.display == 'block'){
menu.style.display = 'none';
}else {
menu.style.display = 'block';
}
}
function hide_menu(){
var menu = document.getElementById('dropdown_menu');
if(menu.style.display == 'none'){
menu.style.display = 'block';
}
}
var cl = document.getElementById("body");
cl.addEventListener("click", hide_menu);
</script>
This can help you.
HTML Code
<div class="menu-button" style="width:23px; cursor: pointer;" ><span id="button" style="color:#b0acac;">Show Menu</span></div>
<div id="dropdown_menu" class="hidden_menu">
<ul id="container">
<li>Settings<br></li>
<li>Log Out</li>
</ul>
</div>
Css
.hidden_menu { display:none;}
JavaScript Code
var dropMenu = document.getElementById('dropdown_menu'),
menuButton = document.getElementById('button'),
dropUL = document.getElementById('container').childNodes;
function hide_menu(evt){
evt = evt || window.event; // get window.event if evt is falsy (IE)
var targetElement = evt.target || evt.srcElement; // get srcElement if target is falsy (IE)
if(targetElement === menuButton || targetElement.nodeName.toLowerCase() === 'li' ){
dropMenu.style.display = 'block'
} else {
dropMenu.style.display = 'none'
}
}
// For legacy broser(IE8 and IE7) support
function addEvent(el, type, fn){
if(typeof addEventListener !== 'undefined'){
el.addEventListener(type, fn, false)
} else {
el.attachEvent('on'+type, fn);
}
}
addEvent(document, 'click', hide_menu);
Demo
If you want plain js:
document.addEventListener('click', function(e){
console.log(e.target.id)
if(e.target.id!=="dropdown_menu")
console.log("document Clicked");
});
It is same as above function but written in javascript
Try
function hide_menu(e){
var menu = document.getElementById('dropdown_menu');
if(e.target != menu) {
menu.style.display = 'none';
}
}
document.body.addEventListener("click", hide_menu);
$('body').click(function(){
if($(this).attr('id')!='dropdown_menu' && !$(this).hasClass('menu-button'))
// code to close the menu
});
Making sure that the click is not on the div for menu

Categories

Resources