How do I toggle multiple divs individually? - javascript

I've tried searching the site and I found a bunch of responses that have to deal with toggling divs on this site. I've also read the documentation on the jquery site. However all of my programming experience has been with mostly back-end java services and I am not a front-end web dev at all so when I see all of the explanations that are given to the answers, I really don't understand them. I've gotten things to work on one individual div but I want things to work on a page that will have hundred of divs that I want to be able to toggle individually.
Can somebody help me not just get the answer but to really understand what is going on?
I have a page with story that has two languages. One language is hidden by default and the other language is displayed. I want to be able to click on an individual div and just have that specific div toggle the languages. I'm using 4 divs in my example, but I want this to work on a page that will have hundreds of divs on it.
I've tried a few different things.
Do I need to assign a class or id to the outside divs that I have wrapping things? Why?
How to get my action to apply to every div on the page without having to use write an onclick() attribute to each div and passing in individual id's?
HTML
<div>
<div id="l12" class="l1">
CHAPTER I Down the Rabbit-Hole
</div>
<div id="l22" class="l2" toggeled="true">
Capítulo I Descendo a Toca do Coelho
</div>
</div>
<div>
<div id="l13" class="l1">
<p>
Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice 'without pictures or conversation?'
</p>
</div>
<div id="l23" class="l2" toggeled="true">
<p>
Alice estava começando a ficar muito cansada de sentar-se ao lado de sua irmã no banco e de não ter nada para fazer: uma ou duas vezes havia espiado o livro que a irmã estava lendo, mas não havia imagens nem diálogos nele, "e para que serve um livro", pensou Alice, "sem imagens nem diálogos?"
</p>
</div>
</div>
The Rest
<head>
<meta charset="utf-8"/>
<style>
.l2{display: none;}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js">
<script>
$( ".toggeled" ).click(function() {
$( ".l10" ).toggle();
});
</script>
</head>

If you want to dynamically do this, you will have to traverse through the document to find each div which needs to be translated.
You can indicate which div has translated parts by giving that section a classname (.e.g .section). Then placing your original and translated text each in their own divs (so you know which to hide and which to show) and giving each their own classnames again (e.g. .text and .english).
<b>Click text to translate:</b>
<hr>
<div class="section">
<div class="english">
CHAPTER I Down the Rabbit-Hole
</div>
<div class="text">
Capítulo I Descendo a Toca do Coelho
</div>
</div>
<hr>
<div class="section">
<div class="english">
CHAPTER II Up the Rabbit-Hole
</div>
<div class="text">
Capítulo II Ascendo a Toca do Coelho
</div>
</div>
Upon page load complete, your JavaScript will then loop through each of the .section and hook the click() event, which does the following:
Show English text by toggling visibility of the .english element within the section
Hide original text by toggling visibility of the .text element within the section
(#2 Is optional)
$( document ).ready(function() {
$('.section').each(function() {
// Save the two div references in a var so they can be called later within the event handler
var translationDiv = $(this).children('.english');
var originalDiv = $(this).children('.text'); // Remove if you do not want to hide original text upon toggling
translationDiv.hide(); // Sets initial translation to hide. You can alternatively do this via css such that all .english { display: none; }.
$(this).click(function(e) {
translationDiv.toggle();
originalDiv.toggle(); // Remove if you do not want to hide original text upon toggling
});
});
});
Its much clearer in the example here:
jsFiddle: http://jsfiddle.net/SECLs/1/

Do I need to assign a class or id to the outside divs that I have
wrapping things? Why?
You don't have to, it's up to you. In this case I think it's unnecessary.
How to get my action to apply to every div on the page without having
to use write an onclick() attribute to each div and passing in
individual id's?
Select via. class name - you already seem to have that part set up (with .l1 on English paragraphs and .l2 on Portuguese paragraphs).
Here is a toggle function as such - you don't have to change your HTML, and all you need to do to add another language to it is to add the class name in the selector:
$(".l1, .l2").click(function() {
$(this).hide();
var languages = $(this).parent().children();
languages.eq((languages.index(this) + 1) % languages.length).show();
});
jsFiddle here.
Here's an example of it being used for four languages, just give them the respective class in HTML (l3, l4), hide them via CSS, and add the class names to the selector (I've implemented wrapping so that it goes back to language 1 afterwards):
$(".l1, .l2, .l3, .l4").click(function() {
$(this).hide();
var languages = $(this).parent().children();
languages.eq((languages.index(this) + 1) % languages.length).show();
});
jsFiddle here.

Related

How do I create a draggable div with javascript?

I am using a modified version of the w3 schools example to have multiple draggable boxes containing information and it works very well, but now I must turn that into a function that can be called at any time. I pieced together this from multiple examples:
function createList() {
let div = document.createElement('div');
//div.classList.add('draggable', 'list');
div.innerHTML = `
<!-- list ui template -->
<div class="draggable list" id="list-template">
<!-- listheader div will contain file name variable, etc. -->
<div class="listheader">New Shopping List</div>
<h3>List - Incomplete</h3>
<p>Test Item<p>
<p>Number of items : 1</p>
</div>`
document.body.appendChild(div);
document.getElementById('listsdiv').appendChild(div);
}
I import it at the end of my index.html. The javascript from w3 that handles moving the boxes uses the class "draggable". This does not work. That might be obvious to some people, and I really hope this is the case because I can't find a solution online. I used to use id instead of class and other mistakes, but I've gone over it all and I'm stuck. Why does it only work when it's hard coded into the html? I apologize if this is not enough information, thank you for your help!

Trying to build a content locker using jQuery

I am very new to jQuery and not entirely sure what I'm doing. Will try my best to explain the problem I'm facing.
I'm trying to lock some content on a landing page until a user shares the link using FB, Twitter, LinkedIN or G+. The first version of the script I wrote (which worked fine) ran like this:
<head>
<script type="text/javascript">
...
$(document).ready(function()
{
$('.class').click(clearroadblock());
buildroadblock();
}
</script>
<style>
.class
{
[css stuff]
}
</style>
</head>
<body>
<div id="something">
<ul>
<li> Link1 </li>
<li> Link2 </li>
</ul>
</div>
</body>
The problem I'm now facing is changing out this code to replace the list elements with social share buttons. As they are no longer under .class, but classes like fb-share-button and twitter-share-button. Please help me understand what I need to modify to accommodate this? PS: This is not a Wordpress site.
function clearroadblock()
{
$('#roadblockdiv').css('display', 'none');
$('#roadblockBkg').css('display','none');
}
This is the way I'm clearing the overlay once a click is detected, BTW.
Can I wrap the social buttons in divs, assign them IDs and use those IDs to trigger the click like below?
<div id="Button">
Tweet
</div>
$('#Button').click(clearroadblock());
You can have multiple classes on an element by separating them with a space. Try the following:
class="class fb-share-button"
Your jquery will still work off the "class" class. I would recommend you change this name to something more meaningful though. Your css can target the "class" for general styles, but you can also target fb and twitter separately.
Update
I decided to create a quick JSFiddle for this.
Some of the styles etc won't be the same as what you're doing, but the problem is resolved. I've created a div with id main that contains the content that you want to hide. There's an absolutely positioned div over the top of this, this is the roadblock. The javascript is showing the roadblock (assuming that's what you wanted to do with buildroadblock()).
On click of a link in the ul with id socialMedia we call clearroadblock. Notice the lack of parenthesis. This hides the roadblock.
This isn't a great way of preventing someone from seeing information, you might want to think about pulling the content down from the server when the action is performed, however, I think this answers your question.

JS - Toggle all DIVs

My issue involves multiple DIVs that display:block or display:none each with their own anchor tag. The main problem is that I have recommissioned the JS code that runs this feature without completely understanding it. All I need is a way to toggle all of the DIVs with a single "Show All/Hide All" link. I cannot wrap my head around it.
I have tried absolutely everything that my exceptionally limited grasp will allow - which consists mostly of swinging my arms in the dark and hoping I accidently build a miracle. Since that hasn't worked I am shamefully seeking help.
The only thing that makes this question unique are all the variables with this specific issue -
An (almost) working example can be found at: www.robertmeans.com/menu.htm
The JS code:
imageX01='plus';
imageX02='plusEven';
function toggleOdd(ee){
imgX="imagePM"+ee;
divX="div"+ee;
imageX="imageX"+ee;
divLink="divHref"+ee;
imageXval=eval("imageX"+ee);
element = document.getElementById(divX).style;
if (element.display=='none') {element.display='block';}
else {element.display='none';}
if (imageXval=='plus') {document.getElementById(imgX).src='_images/minus.gif';eval("imageX"+ee+"='minus';");document.getElementById(divLink).title='Hide Content';}
else {document.getElementById(imgX).src='_images/plus.gif';eval("imageX"+ee+"='plus';");document.getElementById(divLink).title='Show Content';}
}
function toggleEven(ee){
imgX="imagePM"+ee;
divX="div"+ee;
imageX="imageX"+ee;
divLink="divHref"+ee;
imageXval=eval("imageX"+ee);
element = document.getElementById(divX).style;
if (element.display=='none') {element.display='block';}
else {element.display='none';}
if (imageXval=='plusEven') {document.getElementById(imgX).src='_images/minusEven.gif';eval("imageX"+ee+"='minusEven';");document.getElementById(divLink).title='Hide Content';}
else {document.getElementById(imgX).src='_images/plusEven.gif';eval("imageX"+ee+"='plusEven';");document.getElementById(divLink).title='Show Content';}
}
The HTML
<div id="task_item01">
<img src="_images/plus.gif" alt="" name="imagePM01" width="33" height="33" border="0" class="task_itemPlusImage" id="imagePM01" />
Div #1
</div>
<div style="display:none;" id="div01">
Content 1
</div>
<!-- ******************************** Item 1 End **************************** -->
<!-- ******************************** Item 2 Start ************************** -->
<div id="task_item02">
<img src="_images/plusEven.gif" alt="" name="imagePM01" width="33" height="33" border="0" class="task_itemPlusImage" id="imagePM02" />
Div #2
</div>
<div style="display:none;" id="div02">
Content 2
</div>
I have spent countless hours trying to work this out on my own. Any help is deeply appreciated.
Ok first of all, it seems like way too much code to me... you can do this very easily by using jQuery. I have made an example here: http://jsfiddle.net/Nr2f6/4/
Here is some simple html to help you better understand what is being done:
<div id="item-1"><span class="plus"></span>Open these items</div>
<div class="contents" data-rel="item-1">
I have superb items in this div... the world is about to understand just how awesome I am!
</div>
<div id="item-2"><span class="plus"></span>Open these other items</div>
<div class="contents" data-rel="item-2">
I have amazing contents in this div. I want to show them to the world!
</div>
as you can see above, there is no inline css. All the styling (display: none) should be placed separately, to not conflict with what you are trying to do. So simply place it in a separate css file.Then run this code:
$("div[id^=item]").click(function(){
var reference2open = $(this).attr("id");
//get the data-rel attribute associated
$("div[data-rel='"+reference2open+"']").slideToggle();
$("span",this).toggleClass('minus');
});
$("#all").click(function(){
if($(this).hasClass('close')){
$("div[data-rel^=item]").slideUp();
$("div[id^=item] span").removeClass('minus');
$("#all").removeClass('close');
$("#all").html('open them all');
}else{
//open and close them all by clicking
$("div[data-rel^=item]").each(function(){
if($(this).is(':hidden')){
$(this).slideDown();
$("div[id^=item] span").addClass('minus');
$("#all").html('close them all');
}
});
//change the button to close
$("#all").addClass('close');
}
//$("div[id^=item] span").toggleClass('minus');
});
****ADDED IN THE TOGGLE PLUS AND MINUS SIGNS USING CSS****
.plus{
background: url(http://www.robertmeans.com/offsite_files/code_help/_images/plus.gif);
width: 33px;
height: 33px;
display: inline-block;
}
.minus{
background: url(http://www.robertmeans.com/offsite_files/code_help/_images/minus.gif);
width: 33px;
height: 33px;
display: inline-block;
}
Do not forget to include your jQuery file! Hope this helps :)
Just wanted to add in some details for better understanding:
div[id^=item]: Is saying whenever a div is clicked that has an id that starts with (^=) item, run the code.
$("div[data-rel='"+reference2open+"']").slideToggle(): is saying take the id from the div that was clicked and find the content box where with the same name but in the data-rel attribute. The slide it down, if it is already down, slide it back up (toggle). You do not have to use a slide effect, I just thought it was more fun!
Then last but not least, the function you were looking for: How to open them all at once. Again we are using the (^=) to find all of the divs.
$("div[data-rel^=item").slideToggle();: So here we are saying to jQuery, hey toggle all the boxes that have a data-rel attribute that starts with (^=) item.
This last part is pretty neat, because you can create many instances of the item-? boxes and this code will work for any number of them. You can also add the same code to a different div, like even and odd, and toggle all the even and all the odd elements accordingly.
You could assign a specific class to all the things you want to toggle, then loop through all of them with a toggle function.

When click on title, make information appear on another div for the information?

I'm looking for a jQuery solution for this. When I click, let's say on a artist name. Theirs another div beside that has the information showing up. (possibly in a animation/fading way)
Can anyone help?
Link and Info Within Physical Proximity
Use this method if your artist link and artist info is within physical proximity (i.e., sibling in the DOM). Let's say you have:
<a ... class="artistInfo">Artist name</a>
<div class="artistInfo"> .... shown on link click </div>
... repeat
Then use:
$('div.artistInfo').hide(); // Initially hide info
$('a.artistLink').click(function() { // Show on click
$(this).next('div.artistInfo').fadeIn();
});
next() is used to avoid wrapping each link-info set in "per-artist" container. Thus, you should be able to have multiple "sets" of link-plus-info in the same page.
Link and Info in Different Places
When there is no physical proximity between the link and tha info, you will need some sort of identifiers from the link to the info*. E.g.,
<a ... class="artistLink" id="artistLink-1">Artist name</a>
...
<div class="artistInfo" id="artistInfo-1"> .... shown on link click </div>
You can now:
$('div.artistInfo').hide(); // Initially hide all infos
$('a.artistLink').click(function() { // Show on click (by reference)
var n = $(this).attr('id').substring(11); // Remove "artistLink-"
$('#artistInfo' + n).fadeIn();
});
*) Note: You could use the DOM index if links and infos are ordered similarly. I.e., the nth <a> element corresponds to the n info element.
Use the .html method of jquery
If by 'beside' you mean it is the very next sibling, you can use next:
$(".artist").click(function() {
$(this).next("div").slideToggle("slow");
});
<span class="artist">Foo and the Jackals</span>
<div>some content</div>
<span class="artist">Jeff and the misshapen lunatics</span>
<div>some content</div>
...
slideToggle will "Display or hide the matched elements with a sliding motion.".
There can be a number of ways to do this. But then it actually depends on how exactly you want it. one possible way can be use of fadeIn method on a hidden DIV.
<div class='box' style="display:none;">
<p> Artist Description </p>
</div>
<p id='abcd'>Artist Name</p>
for example on this code use this jquery
jQuery('#abcd').click(function(){
jQuery('.box').fadeIn();
});

show/hide ajax? javascript toggle

I'm looking for a wordpress plugin that hides to start with the when I click say an arrow image an ajax feature pops out with say a contact form inside and also another show hide feature at the bottom of the page to show and hide multiple divs.
Is there a plugin that can do all this?
My pages have to be editable for my client so it is impossible for me to build this into the theme. The javascript function needs to be part of a page.
I've found WP ShowHide Elements but this does not allow me to do it with multiple divs in the same placement.
Here's some of the script I'm using as allowed by the plugin in my pages
<p id="mytest">my text</p>
<p><a onclick="wp_showhide('mytest')" href="javascript:void(0);">my link</a></p>
<p id="new">new</p>
<p><a onclick="wp_showhide('new')" href="javascript:void(0);">new</a></p>
Thanks for your help
Regards
Judi
P.S. http://wordpress.digitalnature.ro/mystique/
Please notice the sidebar on this website, this is what I'm trying to achive but within the main page content
This short script works within a page but I want a swap div effect
How can I use this to work with multipe divs? - i'd like to change the visability of multiple divs all with the same space or div
<p><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></p>
<p><a onclick="toggle_visibility('foo');" href="#">Click here to toggle visibility of element #foo</a></p>
<div id="foo">This is foo</div>
<p><a onclick="toggle_visibility('too');" href="#">Click here to toggle visibility of element #too</a></p>
<div id="too">This is too</div>
I think I may have solved my own problem :)
Would love to know whether anyone can modify it so the 1st div is already open when the page loads
<p><script type="text/javascript">
lastone='empty';
function showIt(lyr)
{
if (lastone!='empty') lastone.style.display='none';
lastone=document.getElementById(lyr);
lastone.style.display='block';
}
</script></p>
<p>link</p>
<div id="divID" style="display: none;">content</div>
<p>link</p>
<div id="new" style="display: none;">content</div>
To answer your edit: can't you just remove the display:none style from the original div?
If you need to do it in Javascript, chuck a showIt('divID'); line in after your function.
To do it properly, add it into window.onload:
window.onload = showIt('divID');
Or more properly, have a function that enqueues into the onload (like this).
Or probably best, use a framework :)

Categories

Resources