Showing & Hiding Text with Javascript - javascript

I have some javascript code for a FAQ page for my site. So, you click on the question and the answer appears. NOW, what I can't figure out is when I have clicked on one question and that is open, when I click on another I want the previous one to close. Basically, so there is only ever ONE open at a time. Found similar code, but not exactly what I'm looking for.
Any help would be great, here's my code. THANKS!!!! Kait
<script type="text/javascript">
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
</script>
<p>Here is my Question???</p>
<div id="q1" class="hidden">
<p>The Answer goes here.</p>
</div>
<p>Here is my 2nd Question???</p>
<div id="q2" class="hidden">
<p>The 2nd Answer goes here.</p>
</div>

use a variable to store a reference to the previously shown element, then hide it before showing the one you want to unhide
<script type="text/javascript">
var previous;
function unhide(divID) {
var item = document.getElementById(divID);
if (previous != null)
previous.className='hidden';
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
previous = item;
}
}
</script>
<p>Here is my Question???</p>
<div id="q1" class="hidden">
<p>The Answer goes here.</p>
</div>
<p>Here is my 2nd Question???</p>
<div id="q2" class="hidden">
<p>The 2nd Answer goes here.</p>
</div>
Example
http://jsfiddle.net/hLkks

Give all the answers a class name then select them all and hide them before you reveal the one that you just clicked. If you are using jQuery
$(".answers").addClass("hidden");
$("#"+id).removeClass("hidden");

There is a really simple approach. Improving on Wryte's answer, just add a click event to all items which adds a class to the active one and removes this from all the others.
item.addEventListener("click", function () {
var items = this.parentNode.childNodes;
for (var i=0; i < items.length; i++) {
items[i].className = "";
}
this.className = "active";
}, false);
Fiddle: http://jsfiddle.net/Met3T/
Each item can be whatever you like and you don't need any framework, just plain ole JavaScript.
The CSS could be simple as this:
li {
height: 2em;
background: green;
overflow: hidden;
margin-bottom: 5px;
}
.active {
height: auto;
}

<script type="text/javascript">
var currentItem;
function unhide(divID) {
if (currentItem) {
currentItem.className = 'hidden';
currentItem = null;
}
var item = document.getElementById(divID);
if (item) {
item.className = 'unhidden';
currentItem = item;
}
}
</script>

$(".header a.toggle").click(function(){
if($(this).hasClass("expanded")){
$(this).removeClass("expanded").addClass("collapsed")
.parent().siblings(".body").hide()
}
else{
$(this).removeClass("collapsed").addClass("expanded")
.parent().siblings(".body").show()
}
});
Heres a example where it looks if class is expanded or collapsed
<a class='toggle expanded' href='#'>Text</a>
So make a expanded and collapsed in your CSS

Related

Giving a DIV a maximize button

I currently have a div on my page that I would like a user to be able to click and maximize the div so it appears over the whole screen. I would like it to be similar to how Gmail has a button that allows you to maximize what the user is looking at, and then return to the original size with another click of a button.
The problem I ran into is that my div contains 3 divs inside of it.
Here is my HTML
<div id="pre">
<div id="pre-title">Pre Reading</div>
<div id="pre-text">blahhh.</p></div>
</div>
<div id="passage">
<div id="passage-title">2.2.3</div>
<div id="passage-text">blahlkdsfjahlskdjfh</div>
</div>
<div id="media">
<div id="media-title">Media Videos</div>
<div id="media-text">even more garbage</div>
</div>
These div's are placed directly next to each other on the page and I would like it if I could include a button next to the title that would allow the user to make the section larger, like they were maximizing the readings.
Just giving you the glimpse, change styling as per your requirement.
WORKING:DEMO
JS
$(document).ready(function () {
$(".readmore").click(function () {
var readMore = $(this).parent().attr("id");
var mainDiv = $("#" + readMore).parent().attr("id");
var textDiv = mainDiv +"-text";
$("."+ textDiv).toggleClass("maximize");
});
$(".close").click(function () {
$(".pre-text, .passage-text, .media-text").removeClass("maximize");
});
});
<script>
$(document).ready(function() {
$('#pre').click(function(e) {
$('#pre').toggleClass('maximized', 500); // 500 ms to animate
} );
} );
</script>
<style>
#pre {
width: 50px;
}
#pre.maximized {
width: 500px;
}
</style>

displaying a group of divs by clicking next and back buttons

I have 5 divs that contain copy.
I have a back and next button, to display each div.
Back | Next
<div class="vote-result first">
this is example copy
</div>
<div class="vote-result">
this is some more copy
</div>
<div class="vote-result">
some more copy
</div>
<div class="vote-result">
this is the last div
</div>
// hide the divs, except the first one.
.vote-result { display: none; }
.vote-result.first { display: block; }
The first time the next button link is clicked, I want to remove the off class, to show it as clickable, I probably should disable the link initially too and re-enable it too.
$(".back-btn").removeClass("off");
Once I display the last div, I need to add the off class to the next-btn and disable it.
I thought about using a carousel js plugin to accomplish this, but it is overkill for now.
I know of a way to do this, but it would involve assigning subclasses to the links based on what next or back button was clicked, so it will know what div to show next, as well as removing or adding the off class to the links.
I am hoping to find a solution that allows me to add more div's to display without modifying the code. Any help is appreciated, thank you.
Here is solution for you. I have created Fiddle for your requirement.
HTML code:
<a class="back-btn off">Back</a> | <a class="next-btn">Next</a>
<div class="vote-result first selectedDiv">
this is example copy
</div>
<div class="vote-result">
this is some more copy
</div>
<div class="vote-result">
some more copy
</div>
<div class="vote-result last">
this is the last div
</div>
JS/JQuery Code:
$(".back-btn").click(function(){debugger;
var prevElement=$('.selectedDiv').prev();
prevElement.show();
$(".selectedDiv").hide();
$(".selectedDiv").removeClass("selectedDiv");
prevElement.addClass("selectedDiv");
if($('.first').css('display')=="block"){
$(".back-btn").addClass("off");
}
else{
$(".next-btn").removeClass("off");
}
});
$(".next-btn").click(function(){debugger;
var nextElement= $('.selectedDiv').next();
nextElement.show();
$(".selectedDiv").hide();
$(".selectedDiv").removeClass("selectedDiv");
nextElement.addClass("selectedDiv");
if($('.last').css('display')=="block"){
$(".next-btn").addClass("off");
}
else{
$(".back-btn").removeClass("off");
}
});
CSS code:
.vote-result { display: none; }
.vote-result.first { display: block; }
.off{display:none;}
Your HTML file:
<html>
<head>
<style>
.vote-result { display: none; }
.vote-result.first { display: block; }
.off {
color: Red;
}
a {
color: blue;
}
</style>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="code.js"></script>
</head>
<body>
Back | Next
<div class="vote-result first">
this is example copy
</div>
<div class="vote-result">
this is some more copy
</div>
<div class="vote-result">
some more copy
</div>
<div class="vote-result">
this is the last div
</div>
</body>
</html>
Your new "code.js" file in the same directory:
/**
* The zero-based index of the <div class="vote-result"> element that is currently being shown
* #var {Number}
*/
var activeIndex = 0;
function getNumberOfItems() {
return $('.vote-result').length;
}
function synchronizeInterface() {
var numberOfItems = getNumberOfItems(),
lastIndex = numberOfItems - 1;
$('.vote-result').removeClass('first');
$('.vote-result').each(function(index) {
if (index == activeIndex) {
$(this).addClass('first');
}
})
$('.back-btn').toggleClass('off', activeIndex == 0);
$('.next-btn').toggleClass('off', activeIndex == lastIndex);
}
$(function() {
$('.back-btn,.next-btn').on('click', function() {
// If the button clicked is not deactivated
if (!$(this).hasClass('off')) {
// Determine whether the "Next" button was clicked (otherwise "Back" was clicked)
var clickedNext = $(this).hasClass('next-btn');
// Move the active index in the appropriate direction while not allowing it to fall outside the boundaries of appropriate indices
activeIndex = clickedNext
? Math.min(activeIndex + 1, getNumberOfItems() - 1)
: activeIndex = Math.max(0, activeIndex - 1);
// Make sure the interface now reflects the updated JavaScript variables
synchronizeInterface();
}
return false;
});
});
Some notes: You had an unclosed double-quote for one of your class attributes in your provided HTML. Also, I added some additional styling -- you may want to rename the ".first" CSS class to ".active" instead.
take a look at jquerys .next() function for navigating - jQuery - Next(). you can also check for the last item like this.
if($(this).is(':last-child'))
{
$('.next-btn').removeClass('off');
}else{
$('.next-btn').addClass('off');
}
check everytime a navigation button is clicked and do the same for the first button

Get index of child using jQuery

I want to get the index of the clicked child
<div class="parent">
<div class="child">
<div class="c1"></div>
<div class="c2"></div>
</div>
<div class="child">
<div class="c1"></div>
<div class="c2"></div>
</div>
<div class="child">
<div class="c1"></div>
<div class="c2"></div>
</div>
</div>
jQuery:
$('.child .c1').click(function(){
alert($(this).parent().index())
})
I always get -1. How can i do this work?
EDIT:
I tried this:
$('.child .c1').click(function(){
alert($(this).index())
})
The result is -1 all the time.
What could be wrong?
var child_index = '';
$('.c1').click(function() {
var parent = $(this).parent();
child_index = $(parent).index();
alert(child_index);
});
.div{
position:absolute;
left:45%;
top:0;
}
.child{
margin:1%;
text-align:center;
background-color:gray;
width:100px;
height:100px;
}
.c1,.c2{
color:white;
background-color:blue;
}
.c2{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class="div">
<div class="child">
<div class="c1">c1</div>
<div class="c2">c2</div>
<p>click only work on <strong>c1</strong></p>
</div>
<div class="child">
<div class="c1">c1</div>
<div class="c2">c2</div>
<p>click only work on <strong>c1</strong></p>
</div>
<div class="child">
<div class="c1">c1</div>
<div class="c2">c2</div>
<p>click only work on <strong>c1</strong></p>
</div>
</div>
var child_index = ''; //to store .child class parent index when clicked
$('.c1').click(function() {
var parent = $(this).parent(); //getting the specific parent of c1
//parent variable value now is = .child
child_index = $(parent).index();
alert(child_index);
});
The reason that it returns -1 every time is because in Jquery -1 is a boolean for false and 0 is true. .index() basically asks whether an element exists.
If you want to find what number it is this is a code which I think would work.
var loop = $('.parent .child').length;
$('.child .c1').click(function(){
for(i=1; i<= loop; i++) {
if($(this).parent() === $('.parent').children().eq(i)) {
alert(i);
}
}
});
EDIT Since no one can reproduce the problem, here are some possibilities:
The version of jQuery you're using is conflicting with another script on your page. Since it seems your click event handler is firing because your getting an alert box.
Try using the latest version of jQuery.
Your version of jQuery is conflicting with the current browser you are using. When you're having JavaScript issues you should report the versions of the library you are using (if any) and of your browser.
Check your results in another browser and report back.
Your HTML is being manipulated before your click event is fired. What other code do you have on the page?
Share a more complete source code listing.
alert($(this).parent().prevAll().length);
Use .prevAll to get all previous siblings, then use the length of that set as your index.
edit Use .prevAll(".child") if you are expecting other elements that you want to ignore for indexing purposes.
edit You could try removing jQuery all together
var elms=document.getElementsByClassName("c1");
for(var i=0; i<elms.length; i++)
elms[i].onclick = function() {
var elm = this;
var index = 0;
elm = elm.parentNode;
if(elm) {
while(elm=elm.previousSibling) {
if(elm.nodeType == 1) {
index++;
}
}
} else {
alert("There's no parent node");
}
alert(index);
};

Hiding div clicking on other [duplicate]

This question already has answers here:
How to display one div and hide all others
(7 answers)
Closed 10 years ago.
I have four button and four div above it.
I want to only one div at time , but keep showed the four button.
Here it is the html for buttons
HTML
<div id="container">
<a><p id="firstBtn" class="mediabutton"><span class="icon"></span>button1</p></a> <!-- 1st button -->
<div id="firstDiv" class="mediaoptions" >
... <!-- stuff of the div -->
</div>
<a><p id="sndBtn" class="mediabutton active"><span class="icon"></span>button2</p></a> <!-- 2st button -->
<div id="sndDiv" class="mediaoptions" >
... <!-- stuff of the div -->
</div>
This is how I can recogniz which button was clicked
Javascript
$("container").click(function(event){
var that = event.target.id;
if(((that == "firstBtn") || (that == "sndBtn") || (that == "trdBtn") || (that == "fourBtn") )
&& !($("#"+that).hasClass("active"))
)
{
//Here comes the stuff
}
});
Now. The active class let the button to be Highlighted. I want only one button highlight.
The sndDiv is set on display : block , the others are set on display: none.
Making a recap : I want to press a button , show the div above it and hide everybody else. I tried really a lot of stuff, but i failed.
Sorry for my english, Cheers.
Just replace Btn with Div, and you have the element you'd like to show, the others have a common class and are easy to target :
$("#container").on('click', '.mediabutton', function(event){
var that = event.target.id,
elem = $('#' + that.replace('Btn','Div'));
if( !$("#"+that).hasClass("active") ) {
$('.mediaoptions').not(elem).hide();
elem.show()
}
});
The following should work.
$("container").click(function(event){
var that = event.target.id;
if(((that == "firstBtn") || (that == "sndBtn") || (that == "trdBtn") || (that == "fourBtn") ) && !($("#"+that).hasClass("active")))
{
$('.mediaoptions').show();
$('#'+that.replace('Btn','Div')).show();
}
});
I hate to just point you to a link, but I created a really lightweight jQuery script to handle stuff like this that you might found useful: http://cferdinandi.github.com/tabby/.
You may find it easier to just repurpose that than try to modify your existing code to work.
Don't jQuery .hide() and .show() do the job?
http://api.jquery.com/hide/
Add the second line below to your javascript and see what is alerted:
var that = event.target.id;
alert(that);
I'm not sure exactly what you're trying to accomplish perhaps something like:
<p id="sndBtn" class="mediabutton active"><span class="icon"></span>button2</p>
See this example: JsFiddle. I made some updates on javascript and html;
$(".mediabutton").click(function(event){
$(".mediabutton").removeClass("active");
$(this).addClass("active");
$(".mediaoptions").hide();
$("#"+$(this).data("target-div")).show();
});
Here is the working jsFiddle: http://jsfiddle.net/CtqUU/
With this you can have as many <div> and <button> elements as you want. Change class names and id as needed to fit what you need.
HTML:
<div class="hidden" id="box1">Box 1</div>
<button value="box1">Box 1</button>
<div class="hidden" id="box2">Box 2</div>
<button value="box2">Box 2</button>
CSS:
div {
width: 200px;
height: 200px;
border: 1px solid #000000;
}
.hidden {
display: none;
visibility: hidden;
}
JS:
$("button").click(function(){
var val = $(this).val();
$("div").addClass("hidden");
$("#"+val).removeClass("hidden");
});

What code do i need to collapse a div when another is open?

i use a simple bit of code to make a div collapse, this is it:
<script language="JavaScript">
<!--
function expand(param)
{
param.style.display=(param.style.display=="none")?"":"none";
}
//-->
</script>
what code do i add to make it recognise when one div is open an collapse the previous div?here's the link I'd use:
Link 1
<div id="div1" width="300px" style="display:none"></div>
Any ideas?
This is something jQuery works really well for. Here is a working example in jsfiddle.
http://jsfiddle.net/mrtsherman/uqnZE/
Example html
<div class="category">A
<div class="artists">Apple<br/>Ace<br/>Ants<br/></div>
</div>
<div class="category">B
<div class="artists">Bee<br/>Bop<br/>Book<br/></div>
</div>
<div class="category">C
<div class="artists">Cake<br/>Chimp<br/>Charles<br/></div>
</div>
And the code:
$(".category").click( function() {
$(".artists").hide();
$(this).children(".artists").show();
});
Basically what it does is hide all the divs that contain artists, then shows the div for the one you clicked on. Really simple.
If you were willing to use jQuery, the selector of your interest is something along the lines of
$('div#parent-container > div').filter(':visible');
For example, if I were to demonstrate with next & previous, I would do it something like this. With targeted links it would work by appending ID's to the divs and referencing those in the href attribute of `anchors'. (now included within example)
Something to mess with:
$(function(){
//Reference Object
var $divs = $('div > div');
//Buffer for selected variable
var $selected = 0;
//Show first
$divs.eq(0).show();
$('#next').click(function(){
//Update selected var
$selected = $divs.filter(':visible');
//Save next to variable
var $next = $selected.next();
//Change Visibility
toggle($next);
//Prevent Default
return false;
});
$('#prev').click(function(){
$selected = $divs.filter(':visible');
var $prev = $selected.prev();
toggle($prev);
return false;
});
$('a').click(function(){
$selected = $divs.filter(':visible');
var selector = $(this).attr('href');
if(selector == '#') return false;
toggle( $( selector ) );
return false;
});
var toggle = function($toggle){
if(!$toggle.length) return false;
$selected.hide();
$toggle.show();
}
});
<!--Simple Implementation and dependancies-->
<a id="prev" href="#">Prev</a>
<a id="next" href="#">Next</a>
Show Item Four
<div>
<div id="item-1">One</div>
<div id="item-2">Two</div>
<div id="item-3">Three</div>
<div id="item-4">Four</div>
<div id="item-5">Five</div
<div id="item-6">Six</div>
</div>
div > div {
font-size:5em;
width:auto;
text-align:center;
padding:20px 0;
display:none;
}

Categories

Resources