I am developing a site where I can NOT use jQuery (please, no comments on how good is it, it's prohibited) and I need to reproduce something like .toggle() just for show/hide a div with a class.
I've a group of boxes with a arrow, this arrow can expand a submenu. Let's see an example:
<div class="box">
<div class="box-utils">
</div>
<h2>Example case</h2>
<div class="box-submenu hidden">
<ul />
</div>
</div>
I need that click on the <a /> inside the <div class="box-utils" /> shows/hide the box-submenu class. When it's hidden, the <a /> needs to have class="down", when it's not hidden it needs to be class="up". This also needs to work with more than one case in the same page.
Can someone help me?
Thank you in advance!
Create a toggle function like the one below, provide an id attribute on your DIV (call it box-submenu or something) and call the function from your anchor, and use the ID to lookup whatever you want to hide/show.
<script language="javascript">
function toggle() {
var ele = document.getElementById("box-submenu");
var link = document.getElementById("linkId");
if(ele.style.display == "block") {
ele.style.display = "none";
link.className = "down";
}
else {
ele.style.display = "block";
link.className = "up";
}
}
</script>
Related
So I'm building a form in HTML that makes use of a lot of checkboxes and hidden Divs. Right now I'm using
function HideDiv1() {
var checkBox = document.getElementById("Check1");
var div = document.getElementById("Div1");
if (checkBox.checked == true) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
<input type="checkbox" id="Check1">CheckBox to show Div1
<div id="Div1" style="display: none;">I should be hidden, assuming the author didn't mess up!</div>
To hide each div based on the appropriate checkbox. But this means that I am copying and rewriting this function every time and the section where I like to keep my functions is getting quite large. I was wondering if there was an easier way to do this such that I would only need one function and I could dynamically show and hide Divs without needing to copy and rewrite this function every time.
(If there is some easy JQuery solution to this: please keep in mind that I have no clue how to use JQuery)
This may be a duplicate, I saw the answer once before in the past but I have no idea how to find it again :(
You can use data attributes to identify which div to show when the checkbox is changed.
You can do this by listening for the change event on each checkbox and toggling the corresponding div with jQuery.toggle:
$('input[type=checkbox]').change(function(){
$('div[data-id='+$(this).data('target')+']').toggle()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-target="1">CheckBox to show Div1
<div style="display: none;" data-id="1">Div1</div>
<br/>
<input type="checkbox" data-target="2">CheckBox to show Div2
<div style="display: none;" data-id="2">Div2</div>
Vanilla JS implementation:
document.addEventListener('click', function(e){
if(e.target.matches('input[type=checkbox]')){
let target = document.querySelector('div[data-id="'+e.target.dataset.target+'"]');
target.style.display = target.style.display == "none" ? "block" : "none";
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-target="1">CheckBox to show Div1
<div style="display: none;" data-id="1">Div1</div>
<br/>
<input type="checkbox" data-target="2">CheckBox to show Div2
<div style="display: none;" data-id="2">Div2</div>
You would add an onchange attribute to the checkbox to call a single function called hideDiv and pass it two arguments that are the ids of the checkbox and the div that you are hiding with that checkbox:
onchange="hideDiv("check1","div1")"
...then hideDiv uses the arguments passed to it to toggle the correct div:
function hideDiv(checkId, divId) {
const checkbox = document.getElementById(checkId)
const div = document.getElementById(divId);
if (checkBox.checked == true) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
Get in the habit of using let for variables that you need to change and const for variables that will not change value instead of var.
I'm working on a simple page with 8 different languages, it's just a simple onepager.
All the text in the different languages are set in divs with a style="display:none" to be hidden, until the language is choosen then the div with that particular language is shown.
Currently the main language is English and that div is shown on pageload but when selecting a language will load the div UNDER the english div, but this need to be replaced.
I'm not good in Javascript, but found some codes here which I implemented, but it's still not working as it should be.
This is the JS code:
<script type="text/javascript">
var _hidediv = null;
function toggle_visibility(id) {
if(_hidediv)
_hidediv();
var div = document.getElementById(id);
div.style.display = 'block';
_hidediv = function () { div.style.display = 'none'; };
}
</script>
and in my language selector I've the following as example:
EN | ES | SV
What am I doing wrong here, the default language is english, so the div is as follows: and the other languages have style="display:none"
<div id="english" style="display:block">
How about using CSS to hide/show the divs and only use js/jQuery to change a class on body or any parent element?
$('button').click(function() {
$('#body').removeClass().addClass($(this).data('lang'));
});
.lang {
display: none;
}
#body.en .en {
display: block;
}
#body.es .es {
display: block;
}
#body.de .de {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="body" class="en">
<button data-lang="en">English</button>
<button data-lang="es">Spanish</button>
<button data-lang="de">German</button>
<div class="lang en">English</div>
<div class="lang es">Spanish</div>
<div class="lang de">German</div>
<br/>
<div class="lang en">English 2</div>
<div class="lang es">Spanish 2</div>
<div class="lang de">German 2</div>
</div>
You need to handle the default case of English language also. Only that's missing.
var _hidediv = null;
function toggle_visibility(id) {
if(_hidediv) {
_hidediv();
} else {
document.getElementById('english').style.display = 'none';
}
var div = document.getElementById(id);
div.style.display = 'block';
_hidediv = function () { div.style.display = 'none'; };
}
Language:
English
Spanish
Hindi
French
<div id="content">
<div id="english">
English
</div>
<div id="spanish" style="display: none;">
Spanish
</div>
<div id="hindi" style="display: none;">
Hindi
</div>
<div id="french" style="display: none;">
French
</div>
</div>
Problems in your code
_hidediv will never fire because it is always null.
Logic you used in _hidediv is wrong. It is supposed to set div.style.display = 'none' to other divs than the div you passing as parameter in 'toggle_visibility(id)'. According to your code, even if you manage to fire your _hidediv function, it will reset your target div from div.style.display = 'block' to div.style.display = 'none'.
A jQuery-based solution would work like in this example: https://codepen.io/shikifujin/pen/PowqOjB
You create CSS-classes for .language (hidden by default) and .language.active (visible):
div.language {
display: none;
}
div.language.active {
display: block;
}
Then, create all language divs with content like so (only the default one is given the active class) with the id= property containing the content's language:
<div id="english" class="language active">
english content
</div>
<div id="spanish" class="language">
contenido en espaƱol
</div>
Then you need to have jQuery sourced in your document, as well as the <script> below to make the language switching work. Once the DOM is loaded, all .switch-language elements (they do not need to be necessarily) need to have the id= attribute specify the language to switch to (exactly matching the id of the corresponding div):
EN
Once the entire DOM is loaded, or after the content and switching elements are present, you can enable the switcher by handling each click on any of them with the following actions:
get language to switch to from id (switchTo)
hide all content divs
show the desired one (with id switchTo)
This can be done with vanilla javascript, too, but I chose to use jQuery:
<script>
$(document).ready(function() {
$(".switch-language").on("click", function() {
var switchTo = $(this).data("language");
$(".language").hide();
$(".language#" + switchTo).show();
});
});
</script>
Again, you may try it out here: https://codepen.io/shikifujin/pen/PowqOjB
I am trying to create a show/hide toggle that is used multiple times per page. I believe the script I am using is working, but I would like it to also change the text of the link being clicked from "Read More" to "Read Less".
I have tried my best to sift through several many different posts on the website, but I just can't seem to figure out the changing text part. I've tried different variations of code, but none of them seem to do both of the tasks above.
function toggleRead(id) {
var toggle = document.getElementById(id);
if (toggle.style.display == 'block') {
toggle.style.display = 'none';
} else toggle.style.display = 'block';
};
<div style="display: none;" id="post-1">
<p><strong>Hidden</strong> text inside this div container<p>
</div>
<p><a class="question" onclick="toggleRead('post-1')">Read More</a></p>
<div style="display: none;" id="post-2">
<p><strong>Hidden</strong> text inside this div container<p>
</div>
<p><a class="question" onclick="toggleRead('post-2')">Read More</a></p>
I would really appreciate it if someone could figure out how to change the text of the toggle link from "Read More" to "Read Less" and vice versa whenever it is clicked while maintaining the current functionality.
You also need to reference the toggle links, in order to change its text as well.
I would write the whole thing in a different way, but to stick to your code, you can change it to also reference the "Read more" / "Read less" link:
function toggleRead(id, triggeringLink) {
var toggle = document.getElementById(id);
if (toggle.style.display == 'block') {
toggle.style.display = 'none';
triggeringLink.innerHTML = 'Read More';
} else {
toggle.style.display = 'block';
triggeringLink.innerHTML = 'Read Less';
}
}
<div style="display: none;" id="post-1">
<p><strong>Hidden</strong> text inside this div container</p>
<p></p>
</div>
<p><a class="question" onclick="toggleRead('post-1', this)">Read More</a></p>
<div style="display: none;" id="post-2">
<p><strong>Hidden</strong> text inside this div container</p>
<p></p>
</div>
<p><a class="question" onclick="toggleRead('post-2', this)">Read More</a></p>
Hope this helps.
If you want to change the inner text also, then just add this code according to your conditions.
add Id for each read more tag
document.getElementById('readmore').innerText='readless';
I want show div 1 on html load while hiding div 2, then using onclick I want to exchange their visibility like when clicking button hide div1 then show div2, then when clicking again, hide div2 then show div 1. Here is my code:
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'none')
e.style.display = 'block';
else
e.style.display = 'none';
}
Hide DIV 1 show DIV 2
<div id="foo"> This is DIV 1</div></div>
<div id="foo"> This is DIV 2</div></div>
Initially set your div1 to display:none; and simply toggle them.
I have used class targetElement just to get rid of common selector. hidden class is used to use the default style display:none; and to replace the inline-style.
I woul like to use button instead of Click here. to do this simple replace a tag with <button type="button"> Button Name </button>
$('#toggleButton').on('click',function(){
$('.targetElement').toggleClass('hidden');
});
.hidden{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="toggleButton" href="#">Click here</a>
<div id="foo" class="targetElement hidden"> This is DIV 1</div></div>
<div id="foo" class="targetElement"> This is DIV 2</div></div>
The attribute id must be unique in a document. Use class instead.
First use CSS to hide the second div. Then use forEach() to hide/show div. You should also avoid using inline event handler.
Try the following way:
document.querySelector('a').addEventListener('click',function(){
[].forEach.call(document.querySelectorAll('.foo'), function(el){
if(el.style.display == 'none')
el.style.display = 'block';
else
el.style.display = 'none';
});
});
Hide DIV 1 show DIV 2
<div class="foo"> This is DIV 1</div></div>
<div class="foo" style="display:none;"> This is DIV 2</div></div>
It is not good practice to have 2 elements with the same ID. ID's should always be unique. Use classes instead. To hide a div onload. Simply add the css to your html element in a style attribute. You also had unecessary </div> tags that I removed.
Here is working code using JQuery (less code) :
$("#toggle").on("click", function() {
$(".isToggable").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="toggle" href="#" >Hide DIV 1 show DIV 2</a>
<div class="isToggable"> This is DIV 1</div>
<div class="isToggable" style="display:none"> This is DIV 2</div>
In the html, I added classes to elements that you want to be toggled. I also added an ID to the a tag. In the JQuery I added an event listener onclick on that a tag using it's ID. $(".isToggable").toggle(); takes all the elements with the class "isToggable" in the page toggles their visibility.
With no parameters, the .toggle() method simply toggles the visibility of elements
More information on toggle : JQuery Toggle
Old answer (vanilla javascript)
function toggle_visibility(id) {
var container = document.getElementById(id);
for (var i = 0; i < container.children.length; i++) {
let currentElem = container.children[i];
if (currentElem.style.display === "none") {
currentElem.style.display = "block";
} else {
currentElem.style.display = "none";
}
}
}
Hide DIV 1 show DIV 2
<div id="container">
<div> This is DIV 1</div>
<div style="display:none"> This is DIV 2</div>
</div>
How this works is you put your elements that you want to toggle the visibility inside a container and the toggle_visibility function will toggle all the visibilities of the elements inside. That way if you decide to add more div's they will all be handled.
If you have any questions on how this works. Don't hesitate to ask. Hope it helps !
I hope, somebody can explain me where I'm wrong with my code...So I have this function:
function divdisplay(element){
if(document.getElementById(element).style.display == 'none'){
document.getElementById(element).style.display = 'block';
for (var i=0; i<NUMBER_OF_DIVS; i++)
document.getElementById(i).style.display = 'none';
} else
document.getElementById(element).style.display = 'none';
The function displays the divs just fine, but the hiding part is the problem. I want to hide several other <divs>. The ids of these other <divs> are simple numbers, which is why I try to address these elements with the variable i. But when I click on <div> #1 while <div> #2 is already visible, only <div> #1 appears and <div> #2 does not disappear.
The <divs> look like this:
<div id="1" style="display:none;">
<a href="javascript:divdisplay(1);">
<img src="..."/>
</a>
</div>
<div id="2" style="display:none;">
<a href="javascript:divdisplay(2);">
<img src="..." />
</a>
</div>
<div id="3" style="display:none;">
...
And they first appear when the corresponding link
<a href="javascript:divdisplay(1);">
<a href="javascript:divdisplay(2);">
<a href=...
is clicked.
The image in each <div> is linked to the function again, so a click on the image inside the <div> hides it again, but a click on another link does not make the visible <div> disappear again. Where did I go wrong?
Thanks in advance anyway.
Why you don't use Jquery? You only have to add a class to each div you want to hide/show
<div class="test">content here</div>
and now you can use show() and hide() from jquery.
$(".test").show(); and $(".test").hide(); will show/hide all div's with the class test.
You also check out show() and hide().
In addition you have chance to add an effect to your show() and hide() function.
This function loops through all your divs and only shows the one you specify in element
function divdisplay(element){
for (var i=0; i<NUMBER_OF_DIVS; i++){
var div = document.getElementById('div'+i);
if(i == element){
div.style.display = 'block';
}else{
div.style.display = 'none';
}
}
}
// As Alnitak suggested, this can be condensed into:
function divdisplay(element){
for (var i=0; i<NUMBER_OF_DIVS; i++){
document.getElementById('div'+i).style.display = (i == element)? 'block' : 'none';
}
}
I prefer not to use jQuery in small functions like this, because it'll save you from loading a library (-1 HTTP request), and the native functionality is simply faster. (Not significant at this amount of code, but still)
Assuming you're not using jQuery already, that is. If you are, this will work:
Assuming you add a class to all elements like this:
<div class="hideMe" id="1" style="display:none;">
<a href="javascript:divdisplay(2);">
<img src="..." />
</a>
</div>
jquery:
function divdisplay(element){
$(".hideMe").hide();
$("#"+element).show();
}