first time asking a question here, so thank you in advance and please excuse me if I violate any rules. I'm trying to use this jquery pagination plugin from this site:
http://www.script-tutorials.com/how-to-create-easy-pagination-with-jquery/
and some how it's just not working with the jquery scrollbar plugin I'm using, which is from here:
http://manos.malihu.gr/jquery-custom-content-scroller/
Here's the code I'm working with, you'll see that the scrollbar plugin works on the first page, but after you click on any other subsequent pages it no longer functions:
var Imtech = {};
Imtech.Pager = function() {
this.paragraphsPerPage = 3;
this.currentPage = 1;
this.pagingControlsContainer = '#pagingControls';
this.pagingContainerPath = '#content';
this.numPages = function() {
var numPages = 0;
if (this.paragraphs != null && this.paragraphsPerPage != null) {
numPages = Math.ceil(this.paragraphs.length / this.paragraphsPerPage);
}
return numPages;
};
this.showPage = function(page) {
this.currentPage = page;
var html = '';
this.paragraphs.slice((page-1) * this.paragraphsPerPage,
((page-1)*this.paragraphsPerPage) + this.paragraphsPerPage).each(function() {
html += '<div>' + $(this).html() + '</div>';
});
$(this.pagingContainerPath).html(html);
renderControls(this.pagingControlsContainer, this.currentPage, this.numPages());
}
var renderControls = function(container, currentPage, numPages) {
var pagingControls = 'Page: <ul>';
for (var i = 1; i <= numPages; i++) {
if (i != currentPage) {
pagingControls += '<li>' + i + '</li>';
} else {
pagingControls += '<li>' + i + '</li>';
}
}
pagingControls += '</ul>';
$(container).html(pagingControls);
}
}
.scroll_container {
overflow: auto;
max-height: 100px;
}
body {
background: black;
font-family: Verdana, Helvetica, Arial, sans-serif;
margin: 0;
padding: 0;
color: white;
}
.example {
background: #FFF;
width: 1000px;
font-size: 80%;
border: 1px #000 solid;
margin: 0.5em 10% 0.5em;
padding: 1em 2em 2em;
-moz-border-radius: 3px;
-webkit-border-radius: 3px
}
#content p {
text-indent: 20px;
text-align: justify;
}
#pagingControls ul {
display: inline;
padding-left: 0.5em
}
#pagingControls li {
display: inline;
padding: 0 0.5em
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="assets/imtech_pager.js"></script>
<!-- Add jquery scrollbar plugin -->
<link rel="stylesheet" href="assets/malihu-custom-scrollbar-plugin-master/jquery.mCustomScrollbar.css" />
<script src="assets/malihu-custom-scrollbar-plugin-master/jquery.mCustomScrollbar.min.js"></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<section>
<div>
<div class="wrapper">
<h1>Deals</h1>
<div id="content" class="scroll_container scroll">
<div class="z">
Sergey LUKYANENKO - The Boy and the Darkness - Chapter 1. The Sun Kitten.
<h3>Xmas Special Menu</h3>
<div class="button">
Read More
</div>
</div>
<div class="z">
Everything happened because I got ill.
</div>
<div class="z">
It was already two in the afternoon, and I was lying in bed flicking through "Peter Pan" - I must have read it a hundred times over. I had long since pulled off the bandage my mother had tied around my neck in the morning, and thrown it into a corner. I simply can't understand - how can cotton wool soaked in vodka possibly help a cough? I don't argue with my mum, of course, but after she leaves I look after myself in my own way - namely, lie in bed with a book and wait for my germs to get tired of such a boring method of passing time. It usually helps - perhaps not at once, but after a day or three. A good thing, really, that the street outside looked quite miserable - the sun poking out for brief moments, only to make room for a patchy, nasty drizzle. Though, the sun never actually peeked into the room - our house is so unfortunately placed that it is in the shadows of the new nine-floor high-rises on every side. "The only use for such a flat is to grow mushrooms", - dad used to say, back when he still lived with us.
<div>
testing testing testing
</div>
</div>
<div class="z">
I put my book down on the floor next to the bed, and lay on my back. Perhaps, had I shut my eyes now, nothing would have happened. But there I was, lying staring at the ceiling and listening to the ticking of the clock in the hallway.
</div>
<div class="z">
And a speck of sunlight jumped into the room through the glass. Small - the size of my hand - but surprisingly bright. As though the window was open, with bright summer sun outside. Someone was probably playing with a mirror on the balcony of the house across the street.
</div>
<div class="z">
The rabbit floated across the ceiling, climbed down a wall, made a vase on the dressing-table glint, and stopped, shaking slightly, on my headrest.
</div>
<div class="z">
- Don't go, - I said for some reason, knowing that in a moment the mirror would shift and the rabbit would leave my room forever. - Stay...
</div>
<div class="z">
And that's when it all started.
</div>
<div class="z">
The sun rabbit tore free of the bed and floated in the air. I didn't even realise at first that such things don't happen. It was only when the flat spot hanging in the air started puffing out to form a fuzzy orange ball that I understood - a miracle had happened.
</div>
<div class="z">
Four paws stretched from orange glowing fur, followed by a tail and a head. Green cat eyes blinked and gazed at me steadily. And overall, in fact, the rabbit looked more like a kitten than anything else. Except he was hanging in the air, glowing, and seemed light as the fairy fluff that floats away if one blows gently.
</div>
<div class="z">
- Hello, - purred the kitten. - Thank you for the invitation.
</div>
<div class="z">
I closed my eyes for a second, but when I opened them again, the kitten hadn't disappeared. In fact, he'd flown closer.
</div>
<div class="z">
- I don't believe in fairy tales, - I told myself. - I'm grown up now.
</div>
<div class="z">
- Well, compared to the girl who was holding the True Mirror, you are quite grown up, - declared the kitten, unperturbed, and lowered himself onto the blanket. I glanced over - to see if there would be smoke - but everything seemed all right. I could feel warmth with my chest, but not strong. And the kitten tilted his head and added: - But one can't really call you adult, either. How old are you? Ten, maybe?
</div>
<div class="z">
- Fourteen, - I replied, finding myself calming down at such a mundane question. - Who're you?
</div>
<div class="z">
- A sun rabbit, - replied the kitten, examining himself curiously. - What an appearance.. do I look like one?
</div>
<div class="z">
- <b>Like</b> what?
</div>
<div class="z">
- Like a
<p style="font-weight:bold;color:red;">sun</p>
rabbit.
</div>
<div class="z">
- More like a kitten.
</div>
<div class="z">
- Hardly better, - stated the Kitten sadly and stretched out. And I didn't think of anything better than repeating:
</div>
<div class="z">
- Who're you?
</div>
<div class="z">
- But we have already arrived at a consensus! - said the Kitten with sudden hurt. - A sun rabbit, or more precisely - a kitten, because I look far more like one! What is there not to understand?
</div>
<div class="z">
I found myself tongue-tied. Well, naturally, a small green animal that eats stones would simply be - a small green stone-eater. Simple. And a sun rabbit is a sun kitten, because he looks nothing like a rabbit.
</div>
<div class="z">
- So you mean - any rabbit can come to life if one just calls it? - I asked cautiously. For some reason it seemed to me the Kitten would be hurt at the question again. But he just shook his head proudly:
</div>
<div class="z">
- As if! Any! Only True Light, reflected in a True Mirror, can come to life.
</div>
</div>
<div id="pagingControls">
</div>
</div>
</div>
</section>
</body>
<script type="text/javascript">
var pager = new Imtech.Pager();
$(document).ready(function() {
pager.paragraphsPerPage = 5; // set amount elements per page
pager.pagingContainer = $('#content'); // set of main container
pager.paragraphs = $('div.z', pager.pagingContainer); // set of required containers
pager.showPage(1);
$.mCustomScrollbar.defaults.scrollButtons.enable=true; //enable scrolling buttons by default
$(".scroll").mCustomScrollbar({theme:"light-2"}); //I have modified the theme light-2
$(".all-themes-switch a").click(function(e){
e.preventDefault();
var $this=$(this),
rel=$this.attr("rel"),
el=$(".content");
switch(rel){
case "toggle-content":
el.toggleClass("expanded-content");
break;
}
});
});
</script>
</html>
The rest is the files from the malihu jquery-custom-content-scroller
Thanks in advance!
Wrap the #content div within a new div and add the 'scroll_container' class to that. That should work.
jsfiddle
<div class="example">
<h3>Paragraph pagination sample</h3>
<div class="scroll_container">
<div id="content">
<div class="z">Sergey LUKYANENKO - The Boy and the Darkness - Chapter 1. The Sun Kitten.</div>
.....
</div>
</div>
<div id="pagingControls"></div>
</div>
Related
I have a set of divs within a container. I want these divs to appear at the top of the div, one by one, using the fade-in and then fade-out effect. At the moment I am using a for loop to try and achieve this, but it is having a strange result. Instead of iterating through the class elements, it is displaying them all at once. I have been trying to figure out the problem, but I just cant seem to find the issue.
var customerComments = $(".customercomment");
for (var i = 0; i < customerComments.length; i++) {
$(customerComments[i]).fadeIn("slow", function() {
$(customerComments[i]).delay(600).fadeOut("slow");
})
}
/*STYLING FOR TESTIMONIALS SECTION */
#customerreviews {
background-color: #5a2a27;
min-height: 300px;
}
.customercomment {
margin-top: 20px auto;
padding: 20px 120px;
text-align: center;
display: none;
}
.customercomment p {
font-size: 30px;
line-height: 45px;
}
.customercomment h4 {
border-top: 1px solid white;
margin: 0 auto;
width: 50%;
padding-top: 20px;
}
.location {
font-size: 20px;
font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="testimonials">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1>TESTIMONIALS FROM OUR MEMBERS</h1>
</div>
</div>
<div class="row text-center">
<div class="col-md-12" id="customerreviews">
<div class="customercomment text-center">
<p>"What I find to be the best thing about Elite Fitness Gym, other than the facilities they have to offer, is their overall service and the fact that they do not tie you down to a contract. They make things as easy as possible, inside and outside
the gym, in every way!"</p>
<h4>Rachel Smith<span class="location"> (Manchester)</span></h4>
</div>
<div class="customercomment text-center">
<p>"I am blown away at how cheap the membership is and how much we get back in return. I take full advantage of the MMA classes they offer! I also like the fact that there is more than one class per week, which offers me flexibility - something
I need with my busy schedule."</p>
<h4>Darren Wise<span class="location"> (London)</span></h4>
</div>
<div class="customercomment text-center">
<p>"I am really impressed with the amount of equipment Elite Fitness Gym offer. Even during rush hour I rarely find myself waiting around for equipment. They have certainly done a fantastic job there. I like to keep my workouts short but intense,
so its a great benefit for me."</p>
<h4>Arif Akhtar<span class="location"> (Leeds)</span></h4>
</div>
<div class="customercomment text-center">
<p>"I've been around the block with a number of gyms, but what sets Elite Fitness Gym apart from the rest is their ability to always improve on their service and benefits. I dont feel the need to look elsewhere because this gym is always growing
and taking fantastic, ongoing care of its members."</p>
<h4>Jason Hardy<span class="location"> (London)</span></h4>
</div>
<div class="customercomment text-center">
<p>"I am a big lover of swimming and the facilities that Elite Fitness Gym offer, not just with resistance workouts, but also with cardio, is what encouraged me to join in the first place. I must say that I am so happy with the decision as they
really do have great facilities here."</p>
<h4>Michelle Rousey<span class="location"> (Birmingham)</span></h4>
</div>
<div class="customercomment text-center">
<p>"The thing I benefit from most about Elite Fitness Gym is their timings. They are open 24 hours a day so it gives me a chance to drop in and do my workout just before going to work on my nightshifts. I am grateful to be able to attend such a
great gym during those hours of the day."</p>
<h4>Jermaine Clarke<span class="location"> (Bristol)</span></h4>
</div>
</div>
</div>
</div>
</section>
Thank you for the help!
I tested the following and it fades the divs in one by one. While it does not use the fadeOut function, it still uses the fadeIn function.
$($(".customercomment").get().reverse()).each(function(fadeInDiv) {
$(this).delay(fadeInDiv * 600).fadeIn(1000);
});
Easiest way I can think of is using the promises available in the returned value of the animation functions, and chain them using array#reduce
var customerComments = $(".customercomment");
function doit() {
[].reduce.call(customerComments, function(p, unused, i) {
var $comment = customerComments.eq(i);
return p.then(function() {
return $comment.fadeIn("slow").promise().then(function() {
return $comment.delay(600).fadeOut("slow").promise();
});
});
}, $.when()).then(doit);
}
doit();
/*STYLING FOR TESTIMONIALS SECTION */
#customerreviews {
background-color: #5a2a27;
min-height: 300px;
}
.customercomment {
margin-top: 20px auto;
padding: 20px 120px;
text-align: center;
display: none;
}
.customercomment p {
font-size: 30px;
line-height: 45px;
}
.customercomment h4 {
border-top: 1px solid white;
margin: 0 auto;
width: 50%;
padding-top: 20px;
}
.location {
font-size: 20px;
font-style: italic;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="testimonials">
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<h1>TESTIMONIALS FROM OUR MEMBERS</h1>
</div>
</div>
<div class="row text-center">
<div class="col-md-12" id="customerreviews">
<div class="customercomment text-center">
<p>"What I find to be the best thing about Elite Fitness Gym, other than the facilities they have to offer, is their overall service and the fact that they do not tie you down to a contract. They make things as easy as possible, inside and outside
the gym, in every way!"</p>
<h4>Rachel Smith<span class="location"> (Manchester)</span></h4>
</div>
<div class="customercomment text-center">
<p>"I am blown away at how cheap the membership is and how much we get back in return. I take full advantage of the MMA classes they offer! I also like the fact that there is more than one class per week, which offers me flexibility - something
I need with my busy schedule."</p>
<h4>Darren Wise<span class="location"> (London)</span></h4>
</div>
<div class="customercomment text-center">
<p>"I am really impressed with the amount of equipment Elite Fitness Gym offer. Even during rush hour I rarely find myself waiting around for equipment. They have certainly done a fantastic job there. I like to keep my workouts short but intense,
so its a great benefit for me."</p>
<h4>Arif Akhtar<span class="location"> (Leeds)</span></h4>
</div>
<div class="customercomment text-center">
<p>"I've been around the block with a number of gyms, but what sets Elite Fitness Gym apart from the rest is their ability to always improve on their service and benefits. I dont feel the need to look elsewhere because this gym is always growing
and taking fantastic, ongoing care of its members."</p>
<h4>Jason Hardy<span class="location"> (London)</span></h4>
</div>
<div class="customercomment text-center">
<p>"I am a big lover of swimming and the facilities that Elite Fitness Gym offer, not just with resistance workouts, but also with cardio, is what encouraged me to join in the first place. I must say that I am so happy with the decision as they
really do have great facilities here."</p>
<h4>Michelle Rousey<span class="location"> (Birmingham)</span></h4>
</div>
<div class="customercomment text-center">
<p>"The thing I benefit from most about Elite Fitness Gym is their timings. They are open 24 hours a day so it gives me a chance to drop in and do my workout just before going to work on my nightshifts. I am grateful to be able to attend such a
great gym during those hours of the day."</p>
<h4>Jermaine Clarke<span class="location"> (Bristol)</span></h4>
</div>
</div>
</div>
</div>
</section>
I am a newbie in programming. I have here my javascript code. Its working fine but I want a different style.
this code is a random quote generator.
<html>
<head>
<title>
Daily Quotes
</title>
</head>
<h1>Inspirational Quotes</h1>
<body>
<script language="JavaScript">
var quoteGroups=70;
var quoteNum;
var theQuote=new Array();
theQuote[0]='Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker';
theQuote[1]='If you\'re not part of the solution, you\'re part of the problem. - African Proverb';
theQuote[2]='When you confront a problem you begin to solve it. - Rudy Giuliani';
theQuote[3]='I dream of painting and then I paint my dream. - Vincent Van Gogh';
theQuote[4]='Be silent or let thy words be worth more than silence. - Pythagoras';
theQuote[5]='The past cannot be changed. The future is yet in your power. - Mary Pickford';
theQuote[6]='Anything\'s possible if you\'ve got enough nerve. - J.K. Rowling';
var quoteNum = Math.round(Math.random() * quoteGroups);
document.write(theQuote[quoteNum]);
</script>
<div>
<button style="background-color:lightgreen;width:230;height:70;border: none; font: bold 25px GreatVibes;" onclick="history.go(0)">Inspire Me More!</button>
</div>
<div>
<button style="background-color:blue;width:200;height:70" onclick=>Share</button>
</div>
</body>
<img src="images/bg.jpg" id="bg" alt="">
</html>
For example, the above code will generate random quotes. Now how do i change the font family as a result of clicking the button from this code?
Thanks in advance.
Looking at this:
<button style="background-color:blue;width:200;height:70" onclick=>Share</button>
You have no function set to onclick. Do something like:
<button style="background-color:blue;width:200;height:70" onclick="changeFont(this, 'font name');">Share</button>
changeFont:
function changeFont(element, name) {
element.style.fontFamily = name;
}
Some things to improve:
Don't use document.write, but instead reserve an element in your HTML that you will populate with the quote, assigning to textContent;
Don't use round in your random generating expression, but floor, otherwise you risk to produce a value that is out of range
Don't use a separate variable for the number of quotes you have (which currently does not match the actual number), but use theQuote.length
Don't define long style values in your HTML, but use CSS classes instead
Don't reload the page at every click, but change the quote within the current page without navigating.
To dynamically set the font, you could reserve a few CSS classes to choose from, even randomly.
Here is how it could work:
function displayQuote() {
var theQuote= [
"Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker",
"If you're not part of the solution, you're part of the problem. - African Proverb",
"When you confront a problem you begin to solve it. - Rudy Giuliani",
"I dream of painting and then I paint my dream. - Vincent Van Gogh",
"Be silent or let thy words be worth more than silence. - Pythagoras",
"The past cannot be changed. The future is yet in your power. - Mary Pickford",
"Anything's possible if you've got enough nerve. - J.K. Rowling"
];
var quoteNum = Math.floor(Math.random() * theQuote.length);
var clsName = "special" + Math.floor(Math.random() * 3); // choose random font style
quote.textContent = theQuote[quoteNum];
quote.className = clsName;
}
next.onclick = displayQuote; // execute on click
displayQuote(); // execute on page load
.shareButton {
background-color:blue;
width:200;
height:70
}
.inspireButton {
background-color:lightgreen;
width:230;
height:70;
border: none;
font: bold 25px GreatVibes;
}
.special0 {
font-family: Georgia;
font-size: 24px;
color: #444;
}
.special1 {
font-family: Calibri;
font-size: 32px;
color: #844;
}
.special2 {
font-family: Tahoma;
font-size: 28px;
color: #484;
}
<div id="quote">
</div>
<div>
<button id="next" class="inspireButton">Inspire Me More!</button>
</div>
As you are new, it's best not to pick up bad habits which, unfortunately is easy to do because so much of the code out there is just copied and pasted by folks who don't know any better, so:
Try not to write inline styles or inline event handlers like this:
<button style="background-color:lightgreen;width:230;height:70;border: none; font: bold 25px GreatVibes;" onclick="history.go(0)">Inspire Me More!</button>
As you can see, it makes the code difficult to read as there are 3 languages in that one element!
Instead, separate your languages into their own sections, or even files.
With regard to CSS styles, it would be better to define CSS classes ahead of time and then just switch to the class you need, rather than write all that inline CSS.
You also have some errors in your code.
So, here's an updated version of your code that also changes the font. Make sure to review the comments for details.
<html>
<head>
<title>Daily Quotes</title>
<style>
/* We'll separate the CSS into this section and prepare pre-made classes for styles.
See how much cleaner this is, not only here but in the HTML as well? */
button {
background-color:lightgreen;
width:230;height:70;
border: none;
font: bold 25px GreatVibes;
}
.share {
background-color:blue;
width:200px; /* Don't forget to add the unit */
height:70px; /* Don't forget to add the unit */
}
#output {
/* Now, just the output area has its own style! */
font-family: fantasy;
}
</style>
</head>
<body>
<!-- All your content must be between the opening and closing body tags. -->
<h1>Inspirational Quotes</h1>
<div>
<button>Inspire Me More!</button>
</div>
<div>
<button class="share">Share</button>
<img src="images/bg.jpg" id="bg" alt="">
</div>
<!-- Don't use document.write() to inject content into a page. Instead, prepare an
element ahead of time that you will update later. -->
<div id="output"></div>
<!-- Place your script tags just before the closing of the body tag. That way, you can be
sure that any HTML element you reference in the script has already been read into memory. -->
<script>
// First, get references to the HTML elements you'll want to work with:
var btn = document.querySelector("button");
var out = document.getElementById("output");
// Then, set up your event handlers in JavaScript, not in HTML
btn.addEventListener("click", getQuote);
function getQuote(){
// Here's a simpler way to set up an array:
var theQuotes= [
'Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker',
'If you\'re not part of the solution, you\'re part of the problem. - African Proverb',
'When you confront a problem you begin to solve it. - Rudy Giuliani',
'Dream of painting and then I paint my dream. - Vincent Van Gogh',
'Be silent or let thy words be worth more than silence. - Pythagoras',
'The past cannot be changed. The future is yet in your power. - Mary Pickford',
'Anything\'s possible if you\'ve got enough nerve. - J.K. Rowling'
];
// You only want your radom number to be from 0 to the amount of the quotes array -1
var quoteNum = Math.floor(Math.random() * theQuotes.length);
// Now, just update the prexisting element:
output.textContent = theQuotes[quoteNum];
}
</script>
</body>
</html>
in short, here is working example:
<body onload="generateRandomQuote()">
<h1>Inspirational Quotes</h1>
<div id="quote-holder" style="font-family: sans-serif; color: red;">
</div>
<div>
<button style="background-color: lightgreen; width:230px; height:70px; border: none; font: bold 25px GreatVibes;" onclick="generateRandomQuote()">Inspire Me More!</button>
</div>
<button style="background-color: blue; width: 200px; height: 70px" onclick="">Share</button>
<img src="images/bg.jpg" id="bg" alt="">
<script>
var quoteHolder = document.getElementById('quote-holder');
var theQuote = [
'Whenever you see a successful business, someone once made a courageous decision. - Peter Drucker',
'If you\'re not part of the solution, you\'re part of the problem. - African Proverb',
'When you confront a problem you begin to solve it. - Rudy Giuliani',
'I dream of painting and then I paint my dream. - Vincent Van Gogh',
'Be silent or let thy words be worth more than silence. - Pythagoras',
'The past cannot be changed. The future is yet in your power. - Mary Pickford',
'Anything\'s possible if you\'ve got enough nerve. - J.K. Rowling'
];
function generateRandomQuote() {
var quoteIndex = Math.floor((Math.random() * theQuote.length));
quoteHolder.innerHTML = theQuote[ quoteIndex ];
}
</script>
</body>
in css you should define units, you had just numbers,
there shouldn't bee any h1 or images or any elements outside your body tag,
it's better to just append your desired content to some div, rather than refreshing the whole page,
...
I see that you already have answer.
I have created a list on my site. This list is created by a foreach loop that builds with information from my database. Each item is a container with different sections, so this is not a list like 1, 2, 3... etc. I am listing repeating sections with information. In each section, there is a subsection. The general build is as follows:
<div>
<fieldset class="majorpoints" onclick="majorpointsexpand($(this).find('legend').innerHTML)">
<legend class="majorpointslegend">Expand</legend>
<div style="display:none" >
<ul>
<li></li>
<li></li>
</ul>
</div>
</div>
So, I am trying to call a function with onclick="majorpointsexpand($(this).find('legend').innerHTML)"
The div I am trying to manipulate is style="display:none" by default, and I want to use javascript to make it visible on click.
The "$(this).find('legend').innerHTML" is attempting to pass, in this case, "Expand" as an argument in the function.
Here is the javascript:
function majorpointsexpand(expand)
{
if (expand == "Expand")
{
document.write.$(this).find('div').style = "display:inherit";
document.write.$(this).find('legend').innerHTML = "Collapse";
}
else
{
document.write.$(this).find('div').style = "display:none";
document.write.$(this).find('legend').innerHTML = "Expand";
}
}
I am almost 100% sure my problem is syntax, and I don't have much of a grasp on how javascript works.
I do have jQuery linked to the document with:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
In the <head></head> section.
Okay, so you've got two options here :
Use jQuery UI's accordion - its nice, easy and fast. See more info here
Or, if you still wanna do this by yourself, you could remove the fieldset (its not semantically right to use it for this anyway) and create a structure by yourself.
Here's how you do that. Create a HTML structure like this :
<div class="container">
<div class="header"><span>Expand</span>
</div>
<div class="content">
<ul>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
</ul>
</div>
</div>
With this CSS: (This is to hide the .content stuff when the page loads.
.container .content {
display: none;
padding : 5px;
}
Then, using jQuery, write a click event for the header.
$(".header").click(function () {
$header = $(this);
//getting the next element
$content = $header.next();
//open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
$content.slideToggle(500, function () {
//execute this after slideToggle is done
//change text of header based on visibility of content div
$header.text(function () {
//change text based on condition
return $content.is(":visible") ? "Collapse" : "Expand";
});
});
});
Here's a demo : http://jsfiddle.net/hungerpain/eK8X5/7/
how about:
jQuery:
$('.majorpoints').click(function(){
$(this).find('.hider').toggle();
});
HTML
<div>
<fieldset class="majorpoints">
<legend class="majorpointslegend">Expand</legend>
<div class="hider" style="display:none" >
<ul>
<li>cccc</li>
<li></li>
</ul>
</div>
</div>
Fiddle
This way you are binding the click event to the .majorpoints class an you don't have to write it in the HTML each time.
You might want to give a look at this simple Javascript method to be invoked when clicking on a link to make a panel/div expande or collapse.
<script language="javascript">
function toggle(elementId) {
var ele = document.getElementById(elementId);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
</script>
You can pass the div ID and it will toggle between display 'none' or 'block'.
Original source on snip2code - How to collapse a div in html
So, first of all, your Javascript isn't even using jQuery. There are a couple ways to do this. For example:
First way, using the jQuery toggle method:
<div class="expandContent">
Click Here to Display More Content
</div>
<div class="showMe" style="display:none">
This content was hidden, but now shows up
</div>
<script>
$('.expandContent').click(function(){
$('.showMe').toggle();
});
</script>
jsFiddle: http://jsfiddle.net/pM3DF/
Another way is simply to use the jQuery show method:
<div class="expandContent">
Click Here to Display More Content
</div>
<div class="showMe" style="display:none">
This content was hidden, but now shows up
</div>
<script>
$('.expandContent').click(function(){
$('.showMe').show();
});
</script>
jsFiddle: http://jsfiddle.net/Q2wfM/
Yet a third way is to use the slideToggle method of jQuery which allows for some effects. Such as $('#showMe').slideToggle('slow'); which will slowly display the hidden div.
Many problems here
I've set up a fiddle that works for you: http://jsfiddle.net/w9kSU/
$('.majorpointslegend').click(function(){
if($(this).text()=='Expand'){
$('#mylist').show();
$(this).text('Colapse');
}else{
$('#mylist').hide();
$(this).text('Expand');
}
});
try jquery,
<div>
<a href="#" class="majorpoints" onclick="majorpointsexpand(" + $('.majorpointslegend').html() + ")"/>
<legend class="majorpointslegend">Expand</legend>
<div id="data" style="display:none" >
<ul>
<li></li>
<li></li>
</ul>
</div>
</div>
function majorpointsexpand(expand)
{
if (expand == "Expand")
{
$('#data').css("display","inherit");
$(".majorpointslegend").html("Collapse");
}
else
{
$('#data').css("display","none");
$(".majorpointslegend").html("Expand");
}
}
Here there is my example of animation a staff list with expand a description.
<html>
<head>
<style>
.staff { margin:10px 0;}
.staff-block{ float: left; width:48%; padding-left: 10px; padding-bottom: 10px;}
.staff-title{ font-family: Verdana, Tahoma, Arial, Serif; background-color: #1162c5; color: white; padding:4px; border: solid 1px #2e3d7a; border-top-left-radius:3px; border-top-right-radius: 6px; font-weight: bold;}
.staff-name { font-family: Myriad Web Pro; font-size: 11pt; line-height:30px; padding: 0 10px;}
.staff-name:hover { background-color: silver !important; cursor: pointer;}
.staff-section { display:inline-block; padding-left: 10px;}
.staff-desc { font-family: Myriad Web Pro; height: 0px; padding: 3px; overflow:hidden; background-color:#def; display: block; border: solid 1px silver;}
.staff-desc p { text-align: justify; margin-top: 5px;}
.staff-desc img { margin: 5px 10px 5px 5px; float:left; height: 185px; }
</style>
</head>
<body>
<!-- START STAFF SECTION -->
<div class="staff">
<div class="staff-block">
<div class="staff-title">Staff</div>
<div class="staff-section">
<div class="staff-name">Maria Beavis</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Maria earned a Bachelor of Commerce degree from McGill University in 2006 with concentrations in Finance and International Business. She has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007.</p>
</div>
<div class="staff-name">Diana Smitt</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Diana joined the Diana Smitt Group to help contribute to its ongoing commitment to provide superior investement advice and exceptional service. She has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses.</p>
</div>
<div class="staff-name">Mike Ford</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Mike: A graduate of École des hautes études commerciales (HEC Montreal), Guillaume holds the Chartered Investment Management designation (CIM). After having been active in the financial services industry for 4 years at a leading competitor he joined the Mike Ford Group.</p>
</div>
</div>
</div>
<div class="staff-block">
<div class="staff-title">Technical Advisors</div>
<div class="staff-section">
<div class="staff-name">TA Elvira Bett</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Elvira has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007. Laura works directly with Caroline Hild, aiding in revising client portfolios, maintaining investment objectives, and executing client trades.</p>
</div>
<div class="staff-name">TA Sonya Rosman</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Sonya has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses through the Canadian Securities Institute. She recently completed her Wealth Management Essentials course and became an Investment Associate.</p>
</div>
<div class="staff-name">TA Tim Herson</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Tim joined his father’s group in order to continue advising affluent families in Quebec. He is currently President of the Mike Ford Professionals Association and a member of various other organisations.</p>
</div>
</div>
</div>
</div>
<!-- STOP STAFF SECTION -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript"><!--
//<![CDATA[
$('.staff-name').hover(function() {
$(this).toggleClass('hover');
});
var lastItem;
$('.staff-name').click(function(currentItem) {
var currentItem = $(this);
if ($(this).next().height() == 0) {
$(lastItem).css({'font-weight':'normal'});
$(lastItem).next().animate({height: '0px'},400,'swing');
$(this).css({'font-weight':'bold'});
$(this).next().animate({height: '300px',opacity: 1},400,'swing');
} else {
$(this).css({'font-weight':'normal'});
$(this).next().animate({height: '0px',opacity: 1},400,'swing');
}
lastItem = $(this);
});
//]]>
--></script>
</body></html>
Fiddle
Take a look at toggle() jQuery function :
http://api.jquery.com/toggle/
Also, innerHTML jQuery Function is .html().
Since you have jQuery on the page, you can remove that onclick attribute and the majorpointsexpand function. Add the following script to the bottom of you page or, preferably, to an external .js file:
$(function(){
$('.majorpointslegend').click(function(){
$(this).next().toggle().text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
This solutionshould work with your HTML as is but it isn't really a very robust answer. If you change your fieldset layout, it could break it. I'd suggest that you put a class attribute in that hidden div, like class="majorpointsdetail" and use this code instead:
$(function(){
$('.majorpoints').on('click', '.majorpointslegend', function(event){
$(event.currentTarget).find('.majorpointsdetail').toggle();
$(this).text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
Obs: there's no closing </fieldset> tag in your question so I'm assuming the hidden div is inside the fieldset.
If you used the data-role collapsible e.g.
<div id="selector" data-role="collapsible" data-collapsed="true">
html......
</div>
then it will close the the expanded div
$("#selector").collapsible().collapsible("collapse");
Pure javascript allowing only one expanded div at a time. It allows multi-level sub-expanders. The html only need the expanders contents. The javascript will create the expanders headers with the titles form the content data attribute and a svg arrow.
<style>
/* expanders headers divs */
.expanderHead {
color: white;
background-color: #1E9D8B;
border: 2px solid #1E9D8B;
margin-top: 9px;
border-radius: 6px;
padding: 3px;
padding-left: 9px;
cursor: default;
font-family: Verdana;
font-size: 14px;
}
.expanderHead:first-child {
margin-top: 0 !important;
}
.expanderBody:last-child {
margin-bottom: 0 !important;
}
/* expanders svg arrows */
.expanderHead svg > g > path {
fill: none;
stroke: white;
stroke-width: 2;
stroke-miterlimit: 5;
pointer-events: stroke;
}
/* expanders contents divs */
.expanderBody {
border: 2px solid #1E9D8B;
border-top: 0;
background-color: white;
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
padding: 6px;
font-family: Verdana;
font-size: 12px;
}
/* widget window */
.widget {
width: 400px;
background-color: white;
padding: 9px;
border: 2px solid #1E9D8B;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
}
</style>
<div class="widget">
<div data-title="expander 1" class="expanderBody">
expander 1 content
</div>
<div data-title="expander 2" class="expanderBody">
expander 2 content
</div>
<div data-title="expander 3" class="expanderBody">
<div>
expander 3 content
</div>
<div data-title="expander 3.1" class="expanderBody">
expander 3.1 content
</div>
<div data-title="expander 3.2" class="expanderBody">
expander 3.2 content
</div>
<div data-title="expander 3.3" class="expanderBody">
expander 3.3 content
</div>
</div>
</div>
<script>
document.querySelectorAll(".expanderBody").forEach(item => {
if (item.dataset.title) {
// create expander header
let divHeader = document.createElement("div");
divHeader.className = "expanderHead";
divHeader.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 5 5 L 10 1'/><path d='M 1 1 L 5 5'/></g></svg> <span>" + item.dataset.title + "</span>";
// expander click event
divHeader.addEventListener("click", function () {
// open / close expander
for (let i = 0; i < this.parentNode.children.length; i++) {
let expander = this.parentNode.children[i];
// check if it's expander header
if (expander.className == "expanderHead") {
if (expander == this && expander.nextElementSibling.style.display == "none") {
// open expander body
expander.nextElementSibling.style.display = "";
expander.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 1 5 L 5 1'/><path d='M 5 1 L 10 5'/></g></svg> <span>" + expander.nextElementSibling.dataset.title + "</span>";
expander.style.borderBottomLeftRadius = "0";
expander.style.borderBottomRightRadius = "0";
}
else {
// close expander body
expander.nextElementSibling.style.display = "none";
expander.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 5 5 L 10 1'/><path d='M 1 1 L 5 5'/></g></svg> <span>" + expander.nextElementSibling.dataset.title + "</span>";
expander.style.borderBottomLeftRadius = "6px";
expander.style.borderBottomRightRadius = "6px";
}
}
}
}, true);
item.parentNode.insertBefore(divHeader, item);
item.style.display = "none";
}
});
</script>
Check out Jed Foster's Readmore.js library.
It's usage is as simple as:
$(document).ready(function() {
$('article').readmore({collapsedHeight: 100});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://fastcdn.org/Readmore.js/2.1.0/readmore.min.js" type="text/javascript"></script>
<article>
<p>From this distant vantage point, the Earth might not seem of any particular interest. But for us, it's different. Consider again that dot. That's here. That's home. That's us. On it everyone you love, everyone you know, everyone you ever heard of, every human being who ever was, lived out their lives. The aggregate of our joy and suffering, thousands of confident religions, ideologies, and economic doctrines, every hunter and forager, every hero and coward, every creator and destroyer of civilization, every king and peasant, every young couple in love, every mother and father, hopeful child, inventor and explorer, every teacher of morals, every corrupt politician, every "superstar," every "supreme leader," every saint and sinner in the history of our species lived there – on a mote of dust suspended in a sunbeam.</p>
<p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>
<p>Here's how it is: Earth got used up, so we terraformed a whole new galaxy of Earths, some rich and flush with the new technologies, some not so much. Central Planets, them was formed the Alliance, waged war to bring everyone under their rule; a few idiots tried to fight it, among them myself. I'm Malcolm Reynolds, captain of Serenity. Got a good crew: fighters, pilot, mechanic. We even picked up a preacher, and a bona fide companion. There's a doctor, too, took his genius sister out of some Alliance camp, so they're keeping a low profile. You got a job, we can do it, don't much care what it is.</p>
<p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>
</article>
Here are the available options to configure your widget:
{
speed: 100,
collapsedHeight: 200,
heightMargin: 16,
moreLink: 'Read More',
lessLink: 'Close',
embedCSS: true,
blockCSS: 'display: block; width: 100%;',
startOpen: false,
// callbacks
blockProcessed: function() {},
beforeToggle: function() {},
afterToggle: function() {}
},
Use can use it like:
$('article').readmore({
collapsedHeight: 100,
moreLink: 'Continue reading...',
});
I hope it helps.
Using Pure Javascript
const collapsableBtn = document.querySelectorAll('.collapsable-toggle');
for (let index = 0; index < collapsableBtn.length; index++) {
collapsableBtn[index].addEventListener('click', function(e) {
// e.preventDefault();
e.stopImmediatePropagation();
iterateElement = this;
getCollapsableParent = iterateElement.parentElement;
if(getCollapsableParent.classList.contains('show')) {
getCollapsableParent.classList.remove('show')
iterateElement.innerText = iterateElement.getAttribute('data-onCloseText');
} else {
getCollapsableParent.classList.add('show');
iterateElement.innerText = iterateElement.getAttribute('data-onOpenText');
}
})
}
.collapsable-container #expand {
display:none;
}
.collapsable-container.show #expand {
display:block;
}
<div class="collapsable-container">
Show First Content
<div id="expand">
This is some Content
</div>
</div>
<div class="collapsable-container">
Show Second Content
<div id="expand">
This is some Content
</div>
</div>
I wrote a custom swiper with alerts. Its code is in this link.
When I swipe from left to right or right to left, it gives alerts successfully.
Here, I've used only div for swiping action. Code is like this:
<div id="test" class="text-center"></div>
<script>
$(document).ready(function() {
$(".text-center").swiperight(function() {
/*$("#myCarousel").carousel('prev'); */
alert("Swiped to right");
});
$(".text-center").swipeleft(function() {
/*$("#myCarousel").carousel('next'); */
alert("Swiped to left");
});
});
</script>
If I change the id for body like this,
<style type="text/css">
#test{
position: absolute;
background-color: #0067ac;
width:100%;
height:500px;
}
.text-center{
position: relative;
margin-right: 3%;
margin-top: 5%;
}
<body id="test" class="text-center">
<script type="text/javascript">
$(document).ready(function() {
$("#test").swiperight(function() {
/*$("#myCarousel").carousel('prev'); */
alert("Swiped to right");
});
$("#test").swipeleft(function() {
/*$("#myCarousel").carousel('next'); */
alert("Swiped to left");
});
});
</script>
Then swiping works. link is here.
But if I apply it to my code, then it doesn't work for the body tag . My code is:
<div id = "mainDiv" class = "container" style="padding:0px;width:100%;height:100%">
<div id = "header">
<span id = "icons">
<span id = "menu"></span>
<span onclick="goBack()" id = "back"></span>
</span>
<span id = "title">
<span id="junos"> JUNOS </span><span id = "genius">GENIUS</span>
</span>
</div>
<div id ="body" class="container-fluid" style="position:relative;">
<!-- <div id="swiper"> -->
<div id="searchMenu" class="col-xs-4" style="height:400px; overflow-y:auto;padding:0px;display:none;min-width: 250px;background-color:transparent;">
</div>
<p class="text-center" onclick="goBack()" style="padding-top:12px;">Help</p>
<!-- Start -->
<ul class="list=unstyled text-justify" style="margin-right:20px;">
<li> JUNOS GENIUS is a fun way to improve your skills with Juniper Networks Junos operating system and prepare for technical certification. The Application is a virtual flashcard reader that includes decks of multiple choice questions for several Junos-based exams including JNCIA-Junos, JNCIS-ENT, JNCIS-SEC, and JNCIS-SP. You answer multiple-choice questions and get immediate feedback on accuracy of the answer. </li>
<li> Questions may be answered in Study Mode, Timed Test Mode, or Challenge Instructor Mode. </li>
<ul>
<li> In Study Mode, choose the question category that interests you and begin answering questions. The system will not track your score and no achievements are earned for correct answers. </li>
<li> To enter Timed Test Mode, choose any question category and then tap Timed Test. This will simulate a live exam and provide you with 60 minutes to answer 60 questions selected at random from among all categories in the deck. You will see percentage correct score on completion of 60 questions or at the end of 60 minutes (whichever comes first). </li>
<li>
To enter Challenge Instructor Mode, choose a question category then tap Challenge Instructor to challenge the ranks of instructors. Score higher on the category than the instructor to earn a device achievement. Device achievements are specific to question category. Instructors should be challenged, and beaten, repeatedly to earn higher quantities of device achievements for use in your ‘My Network’. Beating instructors becomes progressively more difficult as you work through the ranks.
</li>
</ul>
<li>My Network:
Device achievements (earned by beating instructors in Challenge Instructor Mode) are used to build network views in a handy network drawing tool called My Network. All Juniper Networks devices earned are available for addition to the My Network view. You are also able to add LAN segments, WAN segments, and end user devices including laptops, printers, and servers to the My Network view. And you have the ability to share your My Network diagram through email or social media.</li>
</ul>
<!-- End -->
</div>
</div>
#mainDiv {
background-image: url("../JunosImages/mob/junos_genius_P_960x720_question_blank_phone.jpg");
background-repeat: no-repeat;
background-size: 100% 100%;
height: 100%;
width: 100%;
}
/*custom js*/
$(document).ready(function() {
$("#mainDiv").swiperight(function() {
alert("Swiped to right");
});
$("#mainDiv").swipeleft(function() {
alert("Swiped to left");
});
});
This is the problem with your css.
I just updated the css and it worked fine :
Check out this fiddle plunker Code
Css Updations are here:
<style type="text/css">
#test{
position: absolute;
background-color: #0067ac;
width:100%;
height:500px;
}
.text-center{
position: relative;
margin-right: 3%;
margin-top: 5%;
}
</style>
I have created a list on my site. This list is created by a foreach loop that builds with information from my database. Each item is a container with different sections, so this is not a list like 1, 2, 3... etc. I am listing repeating sections with information. In each section, there is a subsection. The general build is as follows:
<div>
<fieldset class="majorpoints" onclick="majorpointsexpand($(this).find('legend').innerHTML)">
<legend class="majorpointslegend">Expand</legend>
<div style="display:none" >
<ul>
<li></li>
<li></li>
</ul>
</div>
</div>
So, I am trying to call a function with onclick="majorpointsexpand($(this).find('legend').innerHTML)"
The div I am trying to manipulate is style="display:none" by default, and I want to use javascript to make it visible on click.
The "$(this).find('legend').innerHTML" is attempting to pass, in this case, "Expand" as an argument in the function.
Here is the javascript:
function majorpointsexpand(expand)
{
if (expand == "Expand")
{
document.write.$(this).find('div').style = "display:inherit";
document.write.$(this).find('legend').innerHTML = "Collapse";
}
else
{
document.write.$(this).find('div').style = "display:none";
document.write.$(this).find('legend').innerHTML = "Expand";
}
}
I am almost 100% sure my problem is syntax, and I don't have much of a grasp on how javascript works.
I do have jQuery linked to the document with:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
In the <head></head> section.
Okay, so you've got two options here :
Use jQuery UI's accordion - its nice, easy and fast. See more info here
Or, if you still wanna do this by yourself, you could remove the fieldset (its not semantically right to use it for this anyway) and create a structure by yourself.
Here's how you do that. Create a HTML structure like this :
<div class="container">
<div class="header"><span>Expand</span>
</div>
<div class="content">
<ul>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
</ul>
</div>
</div>
With this CSS: (This is to hide the .content stuff when the page loads.
.container .content {
display: none;
padding : 5px;
}
Then, using jQuery, write a click event for the header.
$(".header").click(function () {
$header = $(this);
//getting the next element
$content = $header.next();
//open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
$content.slideToggle(500, function () {
//execute this after slideToggle is done
//change text of header based on visibility of content div
$header.text(function () {
//change text based on condition
return $content.is(":visible") ? "Collapse" : "Expand";
});
});
});
Here's a demo : http://jsfiddle.net/hungerpain/eK8X5/7/
how about:
jQuery:
$('.majorpoints').click(function(){
$(this).find('.hider').toggle();
});
HTML
<div>
<fieldset class="majorpoints">
<legend class="majorpointslegend">Expand</legend>
<div class="hider" style="display:none" >
<ul>
<li>cccc</li>
<li></li>
</ul>
</div>
</div>
Fiddle
This way you are binding the click event to the .majorpoints class an you don't have to write it in the HTML each time.
You might want to give a look at this simple Javascript method to be invoked when clicking on a link to make a panel/div expande or collapse.
<script language="javascript">
function toggle(elementId) {
var ele = document.getElementById(elementId);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
</script>
You can pass the div ID and it will toggle between display 'none' or 'block'.
Original source on snip2code - How to collapse a div in html
So, first of all, your Javascript isn't even using jQuery. There are a couple ways to do this. For example:
First way, using the jQuery toggle method:
<div class="expandContent">
Click Here to Display More Content
</div>
<div class="showMe" style="display:none">
This content was hidden, but now shows up
</div>
<script>
$('.expandContent').click(function(){
$('.showMe').toggle();
});
</script>
jsFiddle: http://jsfiddle.net/pM3DF/
Another way is simply to use the jQuery show method:
<div class="expandContent">
Click Here to Display More Content
</div>
<div class="showMe" style="display:none">
This content was hidden, but now shows up
</div>
<script>
$('.expandContent').click(function(){
$('.showMe').show();
});
</script>
jsFiddle: http://jsfiddle.net/Q2wfM/
Yet a third way is to use the slideToggle method of jQuery which allows for some effects. Such as $('#showMe').slideToggle('slow'); which will slowly display the hidden div.
Many problems here
I've set up a fiddle that works for you: http://jsfiddle.net/w9kSU/
$('.majorpointslegend').click(function(){
if($(this).text()=='Expand'){
$('#mylist').show();
$(this).text('Colapse');
}else{
$('#mylist').hide();
$(this).text('Expand');
}
});
try jquery,
<div>
<a href="#" class="majorpoints" onclick="majorpointsexpand(" + $('.majorpointslegend').html() + ")"/>
<legend class="majorpointslegend">Expand</legend>
<div id="data" style="display:none" >
<ul>
<li></li>
<li></li>
</ul>
</div>
</div>
function majorpointsexpand(expand)
{
if (expand == "Expand")
{
$('#data').css("display","inherit");
$(".majorpointslegend").html("Collapse");
}
else
{
$('#data').css("display","none");
$(".majorpointslegend").html("Expand");
}
}
Here there is my example of animation a staff list with expand a description.
<html>
<head>
<style>
.staff { margin:10px 0;}
.staff-block{ float: left; width:48%; padding-left: 10px; padding-bottom: 10px;}
.staff-title{ font-family: Verdana, Tahoma, Arial, Serif; background-color: #1162c5; color: white; padding:4px; border: solid 1px #2e3d7a; border-top-left-radius:3px; border-top-right-radius: 6px; font-weight: bold;}
.staff-name { font-family: Myriad Web Pro; font-size: 11pt; line-height:30px; padding: 0 10px;}
.staff-name:hover { background-color: silver !important; cursor: pointer;}
.staff-section { display:inline-block; padding-left: 10px;}
.staff-desc { font-family: Myriad Web Pro; height: 0px; padding: 3px; overflow:hidden; background-color:#def; display: block; border: solid 1px silver;}
.staff-desc p { text-align: justify; margin-top: 5px;}
.staff-desc img { margin: 5px 10px 5px 5px; float:left; height: 185px; }
</style>
</head>
<body>
<!-- START STAFF SECTION -->
<div class="staff">
<div class="staff-block">
<div class="staff-title">Staff</div>
<div class="staff-section">
<div class="staff-name">Maria Beavis</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Maria earned a Bachelor of Commerce degree from McGill University in 2006 with concentrations in Finance and International Business. She has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007.</p>
</div>
<div class="staff-name">Diana Smitt</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Diana joined the Diana Smitt Group to help contribute to its ongoing commitment to provide superior investement advice and exceptional service. She has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses.</p>
</div>
<div class="staff-name">Mike Ford</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Mike: A graduate of École des hautes études commerciales (HEC Montreal), Guillaume holds the Chartered Investment Management designation (CIM). After having been active in the financial services industry for 4 years at a leading competitor he joined the Mike Ford Group.</p>
</div>
</div>
</div>
<div class="staff-block">
<div class="staff-title">Technical Advisors</div>
<div class="staff-section">
<div class="staff-name">TA Elvira Bett</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Elvira has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007. Laura works directly with Caroline Hild, aiding in revising client portfolios, maintaining investment objectives, and executing client trades.</p>
</div>
<div class="staff-name">TA Sonya Rosman</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Sonya has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses through the Canadian Securities Institute. She recently completed her Wealth Management Essentials course and became an Investment Associate.</p>
</div>
<div class="staff-name">TA Tim Herson</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Tim joined his father’s group in order to continue advising affluent families in Quebec. He is currently President of the Mike Ford Professionals Association and a member of various other organisations.</p>
</div>
</div>
</div>
</div>
<!-- STOP STAFF SECTION -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript"><!--
//<![CDATA[
$('.staff-name').hover(function() {
$(this).toggleClass('hover');
});
var lastItem;
$('.staff-name').click(function(currentItem) {
var currentItem = $(this);
if ($(this).next().height() == 0) {
$(lastItem).css({'font-weight':'normal'});
$(lastItem).next().animate({height: '0px'},400,'swing');
$(this).css({'font-weight':'bold'});
$(this).next().animate({height: '300px',opacity: 1},400,'swing');
} else {
$(this).css({'font-weight':'normal'});
$(this).next().animate({height: '0px',opacity: 1},400,'swing');
}
lastItem = $(this);
});
//]]>
--></script>
</body></html>
Fiddle
Take a look at toggle() jQuery function :
http://api.jquery.com/toggle/
Also, innerHTML jQuery Function is .html().
Since you have jQuery on the page, you can remove that onclick attribute and the majorpointsexpand function. Add the following script to the bottom of you page or, preferably, to an external .js file:
$(function(){
$('.majorpointslegend').click(function(){
$(this).next().toggle().text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
This solutionshould work with your HTML as is but it isn't really a very robust answer. If you change your fieldset layout, it could break it. I'd suggest that you put a class attribute in that hidden div, like class="majorpointsdetail" and use this code instead:
$(function(){
$('.majorpoints').on('click', '.majorpointslegend', function(event){
$(event.currentTarget).find('.majorpointsdetail').toggle();
$(this).text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
Obs: there's no closing </fieldset> tag in your question so I'm assuming the hidden div is inside the fieldset.
If you used the data-role collapsible e.g.
<div id="selector" data-role="collapsible" data-collapsed="true">
html......
</div>
then it will close the the expanded div
$("#selector").collapsible().collapsible("collapse");
Pure javascript allowing only one expanded div at a time. It allows multi-level sub-expanders. The html only need the expanders contents. The javascript will create the expanders headers with the titles form the content data attribute and a svg arrow.
<style>
/* expanders headers divs */
.expanderHead {
color: white;
background-color: #1E9D8B;
border: 2px solid #1E9D8B;
margin-top: 9px;
border-radius: 6px;
padding: 3px;
padding-left: 9px;
cursor: default;
font-family: Verdana;
font-size: 14px;
}
.expanderHead:first-child {
margin-top: 0 !important;
}
.expanderBody:last-child {
margin-bottom: 0 !important;
}
/* expanders svg arrows */
.expanderHead svg > g > path {
fill: none;
stroke: white;
stroke-width: 2;
stroke-miterlimit: 5;
pointer-events: stroke;
}
/* expanders contents divs */
.expanderBody {
border: 2px solid #1E9D8B;
border-top: 0;
background-color: white;
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
padding: 6px;
font-family: Verdana;
font-size: 12px;
}
/* widget window */
.widget {
width: 400px;
background-color: white;
padding: 9px;
border: 2px solid #1E9D8B;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
}
</style>
<div class="widget">
<div data-title="expander 1" class="expanderBody">
expander 1 content
</div>
<div data-title="expander 2" class="expanderBody">
expander 2 content
</div>
<div data-title="expander 3" class="expanderBody">
<div>
expander 3 content
</div>
<div data-title="expander 3.1" class="expanderBody">
expander 3.1 content
</div>
<div data-title="expander 3.2" class="expanderBody">
expander 3.2 content
</div>
<div data-title="expander 3.3" class="expanderBody">
expander 3.3 content
</div>
</div>
</div>
<script>
document.querySelectorAll(".expanderBody").forEach(item => {
if (item.dataset.title) {
// create expander header
let divHeader = document.createElement("div");
divHeader.className = "expanderHead";
divHeader.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 5 5 L 10 1'/><path d='M 1 1 L 5 5'/></g></svg> <span>" + item.dataset.title + "</span>";
// expander click event
divHeader.addEventListener("click", function () {
// open / close expander
for (let i = 0; i < this.parentNode.children.length; i++) {
let expander = this.parentNode.children[i];
// check if it's expander header
if (expander.className == "expanderHead") {
if (expander == this && expander.nextElementSibling.style.display == "none") {
// open expander body
expander.nextElementSibling.style.display = "";
expander.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 1 5 L 5 1'/><path d='M 5 1 L 10 5'/></g></svg> <span>" + expander.nextElementSibling.dataset.title + "</span>";
expander.style.borderBottomLeftRadius = "0";
expander.style.borderBottomRightRadius = "0";
}
else {
// close expander body
expander.nextElementSibling.style.display = "none";
expander.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 5 5 L 10 1'/><path d='M 1 1 L 5 5'/></g></svg> <span>" + expander.nextElementSibling.dataset.title + "</span>";
expander.style.borderBottomLeftRadius = "6px";
expander.style.borderBottomRightRadius = "6px";
}
}
}
}, true);
item.parentNode.insertBefore(divHeader, item);
item.style.display = "none";
}
});
</script>
Check out Jed Foster's Readmore.js library.
It's usage is as simple as:
$(document).ready(function() {
$('article').readmore({collapsedHeight: 100});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://fastcdn.org/Readmore.js/2.1.0/readmore.min.js" type="text/javascript"></script>
<article>
<p>From this distant vantage point, the Earth might not seem of any particular interest. But for us, it's different. Consider again that dot. That's here. That's home. That's us. On it everyone you love, everyone you know, everyone you ever heard of, every human being who ever was, lived out their lives. The aggregate of our joy and suffering, thousands of confident religions, ideologies, and economic doctrines, every hunter and forager, every hero and coward, every creator and destroyer of civilization, every king and peasant, every young couple in love, every mother and father, hopeful child, inventor and explorer, every teacher of morals, every corrupt politician, every "superstar," every "supreme leader," every saint and sinner in the history of our species lived there – on a mote of dust suspended in a sunbeam.</p>
<p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>
<p>Here's how it is: Earth got used up, so we terraformed a whole new galaxy of Earths, some rich and flush with the new technologies, some not so much. Central Planets, them was formed the Alliance, waged war to bring everyone under their rule; a few idiots tried to fight it, among them myself. I'm Malcolm Reynolds, captain of Serenity. Got a good crew: fighters, pilot, mechanic. We even picked up a preacher, and a bona fide companion. There's a doctor, too, took his genius sister out of some Alliance camp, so they're keeping a low profile. You got a job, we can do it, don't much care what it is.</p>
<p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>
</article>
Here are the available options to configure your widget:
{
speed: 100,
collapsedHeight: 200,
heightMargin: 16,
moreLink: 'Read More',
lessLink: 'Close',
embedCSS: true,
blockCSS: 'display: block; width: 100%;',
startOpen: false,
// callbacks
blockProcessed: function() {},
beforeToggle: function() {},
afterToggle: function() {}
},
Use can use it like:
$('article').readmore({
collapsedHeight: 100,
moreLink: 'Continue reading...',
});
I hope it helps.
Using Pure Javascript
const collapsableBtn = document.querySelectorAll('.collapsable-toggle');
for (let index = 0; index < collapsableBtn.length; index++) {
collapsableBtn[index].addEventListener('click', function(e) {
// e.preventDefault();
e.stopImmediatePropagation();
iterateElement = this;
getCollapsableParent = iterateElement.parentElement;
if(getCollapsableParent.classList.contains('show')) {
getCollapsableParent.classList.remove('show')
iterateElement.innerText = iterateElement.getAttribute('data-onCloseText');
} else {
getCollapsableParent.classList.add('show');
iterateElement.innerText = iterateElement.getAttribute('data-onOpenText');
}
})
}
.collapsable-container #expand {
display:none;
}
.collapsable-container.show #expand {
display:block;
}
<div class="collapsable-container">
Show First Content
<div id="expand">
This is some Content
</div>
</div>
<div class="collapsable-container">
Show Second Content
<div id="expand">
This is some Content
</div>
</div>