Jquery Slide Animation changes height while sliding - javascript

I'm trying to build a simple slider. You click left, the images slide left. You click right, the images slide right.
I have done that. It works great, with one small problem. It is hard to describe the problem so I will give you a fiddle instead. I would print all the code here but it is too much.
$(function () {
$("#oe-slide-left").on('click', function () {
SlideLeft();
});
$("#oe-slide-right").on('click', function () {
SlideRight();
});
});
function SlideLeft() {
var countLeft = $('#oe-testemonials').find('.oe-testemonial:visible').each(function () { }).length;
var countRight = $('#oe-testemonials').find('.oe-testemonial:hidden').each(function () { }).length;
if (countLeft > 3) {
$("#oe-testemonials div.oe-testemonial:visible").first().animate({ width: 'toggle' }, 350);
}
if (countLeft === 4) {
$("#oe-slide-left").hide();
}
if (countRight === 0) {
$("#oe-slide-right").show();
}
}
function SlideRight() {
var countLeft = $('#oe-testemonials').find('.oe-testemonial:visible').each(function () { }).length;
var countRight = $('#oe-testemonials').find('.oe-testemonial:hidden').each(function () { }).length;
if (countRight > 0) {
$("#oe-testemonials div.oe-testemonial:hidden").last().animate({ width: 'toggle' }, 350);
}
if (countRight <= 1) {
$("#oe-slide-right").hide();
}
if (countLeft === 3)
{
$("#oe-slide-left").show();
}
}
.oe-testemonials {
margin-top: 40px;
width: 100%;
overflow: hidden;
white-space: nowrap;
position: relative;
.slider-left-arrow, .slider-right-arrow {
position: absolute;
z-index: 1000;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
&:hover {
background: #efe5e5;
opacity: 0.8;
}
}
.slider-left-arrow {
left: 15px;
}
.slider-right-arrow {
right: 15px;
}
.oe-testemonial {
width: 33%;
display: inline-block;
margin: auto;
white-space: normal;
.image-wrapper {
width: 100px;
height: 100px;
position: relative;
overflow: hidden;
border-radius: 50%;
margin: auto;
img {
display: inline;
margin: 0 auto;
height: 100%;
width: auto;
}
}
.description, .name, .title, .location {
width: 90%;
max-width: 300px;
text-align: center;
margin: auto;
}
.description {
border-bottom: 1px solid #999;
padding-bottom: 5px;
margin-bottom: 5px;
color: #413880;
}
.name {
font-family: 'Just Another Hand', cursive;
font-size: 24px;
}
.location {
color: #B3B3B3;
}
}
}
.description{
width: 100px !important;
}
<div id="oe-testemonials" class="oe-testemonials">
<img id="oe-slide-left" src="/Images/left_arrow.png" alt="Click To Slide Left" class="slider-left-arrow">
<img id="oe-slide-right" src="/Images/right_arrow.png" alt="Click To Slide Right" class="slider-right-arrow" style="display: none;">
<div class="oe-testemonial" style="display: inline-block;"><div class="image-wrapper"><img src="/Images/people/Erin_Hartigan-6947_sm.jpg" alt="Portfolio Image"></div><div class="description"><span>I think that OrthoEvidence is wonderful. It’s great that there are new avenues for people to learn about the evidence and have it summarized, which allows for a more transparent transfer of research to both practitioners and patients.</span></div><div class="name"><span>Dr. Erin Hartigan</span></div><div class="title"><span>Assistant Professor of Physical Therapy</span></div><div class="location"><span>University of New England</span></div></div><div class="oe-testemonial"><div class="image-wrapper"><img src="/Images/people/HiteshGopalan.jpg" alt="Portfolio Image"></div><div class="description"><span>As an Editor of a book and an associated website, I have been following 20- 30 journals every month. But now I have shifted my primary focus to OrthoEvidence where I get all quality information in one place.</span></div><div class="name"><span>Dr. Hitesh Gopalan</span></div><div class="title"><span>Editor</span></div><div class="location"><span>orthopaedicprinciples.com</span></div></div><div class="oe-testemonial"><div class="image-wrapper"><img src="/Images/people/DavidGryfe_sm.jpg" alt="Portfolio Image"></div><div class="description"><span>OrthoEvidence raises the bar on timely and relevant reviews of the medical literature. This is an indispensible service for every practitioner who strives to stay current.</span></div><div class="name"><span>Dr. David Gryfe</span></div><div class="title"><span>Chiropractor</span></div><div class="location"><span>Chiropractic Sports Specialist</span></div></div><div class="oe-testemonial"><div class="image-wrapper"><img src="/Images/people/AaronKrych_sm.jpg" alt="Portfolio Image"></div><div class="description"><span>OrthoEvidence allows the busy practicing surgeon, in a short period of time, to stay up to date with what is important with the changes in the literature.</span></div><div class="name"><span>Dr. Aaron Krych</span></div><div class="title"><span>Orthopaedic Surgeon</span></div><div class="location"><span>Mayo Clinic</span></div></div><div class="oe-testemonial"><div class="image-wrapper"><img src="/Images/people/JonathanRonquillo_sm.jpg" alt="Portfolio Image"></div><div class="description"><span>OrthoEvidence has made me more critical of available papers. It has made me look back at certain existing protocols...to improve existing practice.</span></div><div class="name"><span>Dr. Jonathan Ronquillo</span></div><div class="title"><span>Orthopaedic Surgeon</span></div><div class="location"><span>Asian Hospital and Medical Center</span></div></div><div class="oe-testemonial"><div class="image-wrapper"><img src="/Images/people/FrankSmith_sm.jpg" alt="Portfolio Image"></div><div class="description"><span>OrthoEvidence is the flag ship for enabling us to keep current whilst still working 60 hour weeks.</span></div><div class="name"><span>Dr. Frank Smith</span></div><div class="title"><span>Orthopaedic Surgeon</span></div><div class="location"><span>McMaster University</span></div></div><div class="oe-testemonial"><div class="image-wrapper"><img src="/Images/people/MarcosBritto_sm.jpg" alt="Portfolio Image"></div><div class="description"><span>OE is medical information of unparalleled quality, with papers revised, and a newsletter available in my inbox. It is the fastest and easiest way to stay updated on Orthopedics.</span></div><div class="name"><span>Dr. Marcos Britto da Silva</span></div><div class="title"><span>Orthopaedic Surgeon</span></div><div class="location"><span>Federal University of Rio de Janeiro</span></div></div></div>
Please take a look at this: https://jsfiddle.net/wq96vbd5/
You will notice that when you click on "Click To Slide Left" the slider does slide left but the text gets super long and the animation just looks terrible.

The best and easiest way to do this, is with a plugin, I recommend the slick slider, because it's free, easy to learn and have a big community
To do that you'll need jquery, download the js and the css file from the slick page, and start using
Here is your example with the plugin in jsfiddle
HTML
<div id="oe-testemonials" class="oe-testemonials">
<div id="oe-slide">
<div class="oe-testemonial" style="display: inline-block;">
<div class="image-wrapper"><img src="/Images/people/Erin_Hartigan-6947_sm.jpg" alt="Portfolio Image"></div>
<div class="description"><span>I think that OrthoEvidence is wonderful. It’s great that there are new avenues for people to learn about the evidence and have it summarized, which allows for a more transparent transfer of research to both practitioners and patients.</span></div>
<div class="name"><span>Dr. Erin Hartigan</span></div>
<div class="title"><span>Assistant Professor of Physical Therapy</span></div>
<div class="location"><span>University of New England</span></div>
</div>
<div class="oe-testemonial">
<div class="image-wrapper"><img src="/Images/people/HiteshGopalan.jpg" alt="Portfolio Image"></div>
<div class="description"><span>As an Editor of a book and an associated website, I have been following 20- 30 journals every month. But now I have shifted my primary focus to OrthoEvidence where I get all quality information in one place.</span></div>
<div class="name"><span>Dr. Hitesh Gopalan</span></div>
<div class="title"><span>Editor</span></div>
<div class="location"><span>orthopaedicprinciples.com</span></div>
</div>
<div class="oe-testemonial">
<div class="image-wrapper"><img src="/Images/people/DavidGryfe_sm.jpg" alt="Portfolio Image"></div>
<div class="description"><span>OrthoEvidence raises the bar on timely and relevant reviews of the medical literature. This is an indispensible service for every practitioner who strives to stay current.</span></div>
<div class="name"><span>Dr. David Gryfe</span></div>
<div class="title"><span>Chiropractor</span></div>
<div class="location"><span>Chiropractic Sports Specialist</span></div>
</div>
<div class="oe-testemonial">
<div class="image-wrapper"><img src="/Images/people/AaronKrych_sm.jpg" alt="Portfolio Image"></div>
<div class="description"><span>OrthoEvidence allows the busy practicing surgeon, in a short period of time, to stay up to date with what is important with the changes in the literature.</span></div>
<div class="name"><span>Dr. Aaron Krych</span></div>
<div class="title"><span>Orthopaedic Surgeon</span></div>
<div class="location"><span>Mayo Clinic</span></div>
</div>
<div class="oe-testemonial">
<div class="image-wrapper"><img src="/Images/people/JonathanRonquillo_sm.jpg" alt="Portfolio Image"></div>
<div class="description"><span>OrthoEvidence has made me more critical of available papers. It has made me look back at certain existing protocols...to improve existing practice.</span></div>
<div class="name"><span>Dr. Jonathan Ronquillo</span></div>
<div class="title"><span>Orthopaedic Surgeon</span></div>
<div class="location"><span>Asian Hospital and Medical Center</span></div>
</div>
<div class="oe-testemonial">
<div class="image-wrapper"><img src="/Images/people/FrankSmith_sm.jpg" alt="Portfolio Image"></div>
<div class="description"><span>OrthoEvidence is the flag ship for enabling us to keep current whilst still working 60 hour weeks.</span></div>
<div class="name"><span>Dr. Frank Smith</span></div>
<div class="title"><span>Orthopaedic Surgeon</span></div>
<div class="location"><span>McMaster University</span></div>
</div>
<div class="oe-testemonial">
<div class="image-wrapper"><img src="/Images/people/MarcosBritto_sm.jpg" alt="Portfolio Image"></div>
<div class="description"><span>OE is medical information of unparalleled quality, with papers revised, and a newsletter available in my inbox. It is the fastest and easiest way to stay updated on Orthopedics.</span></div>
<div class="name"><span>Dr. Marcos Britto da Silva</span></div>
<div class="title"><span>Orthopaedic Surgeon</span></div>
<div class="location"><span>Federal University of Rio de Janeiro</span></div>
</div>
</div>
</div>
Javascript
$(document).ready(function(){
$('#oe-slide').slick({
slidesToShow: 3,
prevArrow: "<img id='oe-slide-left' src='/Images/left_arrow.png' alt='Click To Slide Left' class='slider-left-arrow'>",
nextArrow: "<img id='oe-slide-right' src='/Images/right_arrow.png' alt='Click To Slide Right' class='slider-right-arrow' style='display: none'>"
});
});
CSS
The same

Related

add class when click in choice word

I have class "selected" it has background color red I want when click in word in the sidebar give the class "selected" to the same company have this name on the right-hand side and at the same time another company that not select be hidden
code: https://codepen.io/El7raq/pen/VwWjjgK
I, mean something like this in the dashboard we select name some me this section only -> https://drive.google.com/drive/folders/1DzLg26BWmMpMhlQ-lS08UK4r74GTiDut?usp=sharing
HTML
<section class="business-partners">
<div class="container">
<div class="row">
<div class="col-12">
<h2 class="col-12 business-partners-header">Business Partners</h2>
</div>
</div>
<div class="row">
<!-- Start slider -->
<div class="col-lg-3 col-md-5 col-sm-12">
<div class="slide">
<h4 class="slid-header">| Partners</h4>
<p id="zoom" class="partners partner-selected"><span>Zoom</span></p>
<p id="jabra" class="partners"><span>Jabra</span></p>
<p id="epos" class="partners"><span>EPOS</span></p>
<p id="dten" class="partners"><span>DTEN</span></p>
<p id="ttec" class="partners"><span>TTec</span></p>
</div>
</div>
<!-- End slider -->
<div class="col-lg-8 col-md-7 col-sm-12">
<div id="zoom" class="partners-content selected">
<h2 class="partners-name">Zoom</h2>
<img class="partners-img" src="../images/business-partners/zoom.jpg" alt="zoom" srcset="">
<p class="partners-description">
Zoom Video Communications, Inc. brings teams together to get more done in a frictionless video environment. easy, reliable, and innovative video-first unified communications platform provides video meetings, voice, webinars, and chat across desktops, phones, mobile devices, and conference room systems. Zoom helps enterprises create elevated experiences with leading business app integrations and developer tools to create customized workflows.
</p>
<p>
Zoom’s value is to care. We care for our customers, employees, company, community, and selves. Our culture of delivering happiness stems from this value.
</p>
</div>
<div id="jabra" class="partners-content">
<h2 class="partners-name">Jabra</h2>
<img class="partners-img" src="../images/business-partners/jabra_logo.jpg" alt="zoom" srcset="">
<p class="partners-description">
a global brand with a serious passion for sound. Thanks to our expertise in consumer, professional and medical audio technology, our passion is backed up by unrivaled knowledge of the human ear. We’re in the business of helping you hear what you want to hear – from letting the right sound in, to filtering disruptive noise out – but our products are about so much more than that, packed with intuitive features to make life sound better.
</p>
</div>
<div id="epos" class="partners-content">
<h2 class="partners-name">EPOS</h2>
<img class="partners-img" src="../images/business-partners/EPOS_Logo_-_Black_-_Large.jpg" alt="zoom" srcset="">
<p class="partners-description">
EPOS delivers high-end audio solutions designed for enterprise and gaming. Based on pioneering audio technology, EPOS strives to unleash human potential by perfecting audio experiences and delivering innovative design and performance with all of our audio solutions. <p>
Zoom’s value is to care. We care for our customers, employees, company, community, and selves. Our culture of delivering happiness stems from this value.
</p>
<p>
EPOS headquarters is located in Copenhagen, Denmark, and is a key hub for our business. EPOS builds on more than 115 years of experience in audio innovation. We operate in a global market with offices and partners in more than 60 countries.
</p>
<p>
EPOS Name is derived from Latin and ancient Greek and is used to describe epic stories, speech, and poetry. The name encapsulates our dedication to creating solutions that enable ways of communication through the Power of Audio. </p>
<p>
EPOS is part of the Demant group – a world-leading audio and hearing technology group that offers solutions and services to help people connect and communicate with the world around them. The Demant Group operates in a global market with companies in more than 30 countries, employs more than 16,000 employees, and generates annual revenue of DKK 14.5 billion.
</p>
</div>
<div id="dten" class="partners-content">
<h2 class="partners-name">DTEN</h2>
<img class="partners-img" src="../images/business-partners/DIC_i_Yi_400x400.jpg" alt="zoom" srcset="">
<p class="partners-description">
DTEN builds innovative communications technology creating the ideal environment to communicate and collaborate.
</p>
<p>
DTN develops award-winning collaboration solutions that combine all-in-one cutting- edge features, plug-and-play ease, high quality performance and affordability.
</p>
<p>
DTEN's Zoom certified appliances and integrated service subscriptions revolutionize the way teams around the world connect, communicate and collaborate.
</p>
<p>
Founded in 2015, DTEN is rapidly becoming a recognized international leader for innovation and accessibility in communication.
</p>
<h4>
DTEN D7
Wins 2019 Red Dot Best Of The Best Award
</h4>
<p>
DTEN is a 2019 recipient of the prestigious Red Dot: Best of the Best Award for D7. The Red Dot Award recognizes D7 for innovative product design, including breakthrough technology, inherent functionality and streamlined aesthetics.
</p>
</div>
<div id="ttec" class="partners-content">
<h2 class="partners-name">TTec</h2>
<img class="partners-img" src="../images/business-partners/ttec.jpg" alt="zoom" srcset="">
<p class="partners-description">
Zoom Video Communications, Inc. brings teams together to get more done in a frictionless video environment. easy, reliable, and innovative video-first unified communications platform provides video meetings, voice, webinars, and chat across desktops, phones, mobile devices, and conference room systems. Zoom helps enterprises create elevated experiences with leading business app integrations and developer tools to create customized workflows. </p>
<p>
Zoom’s value is to care. We care for our customers, employees, company, community, and
selves. Our culture of delivering happiness stems from this value.
</p>
</div>
</div>
</div>
</div>
</section>
CSS
.business-partners-body{
position: relative;
}
.business-partners-body .top-svg{
position: absolute;
z-index: -1;
width: 100%;
top: 40px;
}
.business-partners {
margin-top: 100px;
margin-bottom: 100px;
}
.business-partners .business-partners-header {
margin-bottom: 50px;
font-size: 45px;
}
.business-partners .business-partners-header:after {
background-color: #000;
content: "";
display: inline-block;
height: 4px;
position: relative;
vertical-align: middle;
width: 40px;
}
.business-partners .business-partners-header:after {
left: 0.5em;
margin-right: -50%;
}
/*Partners slider*/
.slide {
border: 2px solid #000;
min-height: 445px;
border-radius: 15px;
}
.slide .slid-header {
padding: 20px;
border-bottom: 2px solid #000;
}
.slide .partners {
padding: 15px 10px 10px 15px;
margin: 0;
font-size: 18px;
}
.slide .partner-selected {
color: var(--primary-color);
}
.slide .partners span:hover {
color: var(--hover-color)
}
/* Partners content*/
.partners-content {
margin-left: 80px;
/* display: none; */
}
.partners-content .partners-name {
margin-bottom: 30px;
}
.partners-content .partners-img{
width: 100%;
height: 300px;
margin-bottom: 50px;
}
.selected {
display:block;
background-color: red;
}
thank's for the help
You can try with below code :
$(document).ready(function(){
$('.partners').click(function(){
$('.partners').removeClass('partner-selected');
$('.partners-content').removeClass('selected');
$(this).addClass('partner-selected');
var side_id = $(this).attr('id');
$('partners-content').hide();
if($('div#' + side_id).hasClass('partners-content')){
$("div#" + side_id).addClass("selected");
$("div#" + side_id).show();
}
});
});
.business-partners-body{
position: relative;
}
.business-partners-body .top-svg{
position: absolute;
z-index: -1;
width: 100%;
top: 40px;
}
.business-partners {
margin-top: 100px;
margin-bottom: 100px;
}
.business-partners .business-partners-header {
margin-bottom: 50px;
font-size: 45px;
}
.business-partners .business-partners-header:after {
background-color: #000;
content: "";
display: inline-block;
height: 4px;
position: relative;
vertical-align: middle;
width: 40px;
}
.business-partners .business-partners-header:after {
left: 0.5em;
margin-right: -50%;
}
/*Partners slider*/
.slide {
border: 2px solid #000;
min-height: 445px;
border-radius: 15px;
}
.slide .slid-header {
padding: 20px;
border-bottom: 2px solid #000;
}
.slide .partners {
padding: 15px 10px 10px 15px;
margin: 0;
font-size: 18px;
}
.slide .partner-selected {
color: var(--primary-color);
}
.slide .partners span:hover {
color: var(--hover-color)
}
/* Partners content*/
.partners-content {
margin-left: 80px;
/* display: none; */
}
.partners-content .partners-name {
margin-bottom: 30px;
}
.partners-content .partners-img{
width: 100%;
height: 300px;
margin-bottom: 50px;
}
.partners-content{
display:none;
}
.selected {
display:block;
background-color: red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<section class="business-partners">
<div class="container">
<div class="row">
<div class="col-12">
<h2 class="col-12 business-partners-header">Business Partners</h2>
</div>
</div>
<div class="row">
<!-- Start slider -->
<div class="col-lg-3 col-md-5 col-sm-12">
<div class="slide">
<h4 class="slid-header">| Partners</h4>
<p id="zoom" class="partners partner-selected"><span>Zoom</span></p>
<p id="jabra" class="partners"><span>Jabra</span></p>
<p id="epos" class="partners"><span>EPOS</span></p>
<p id="dten" class="partners"><span>DTEN</span></p>
<p id="ttec" class="partners"><span>TTec</span></p>
</div>
</div>
<!-- End slider -->
<div class="col-lg-8 col-md-7 col-sm-12">
<div id="zoom" class="partners-content selected">
<h2 class="partners-name">Zoom</h2>
<img class="partners-img" src="../images/business-partners/zoom.jpg" alt="zoom" srcset="">
<p class="partners-description">
Zoom Video Communications, Inc. brings teams together to get more done in a frictionless video environment. easy, reliable, and innovative video-first unified communications platform provides video meetings, voice, webinars, and chat across desktops, phones, mobile devices, and conference room systems. Zoom helps enterprises create elevated experiences with leading business app integrations and developer tools to create customized workflows.
</p>
<p>
Zoom’s value is to care. We care for our customers, employees, company, community, and
selves. Our culture of delivering happiness stems from this value.
</p>
</div>
<div id="jabra" class="partners-content">
<h2 class="partners-name">Jabra</h2>
<img class="partners-img" src="../images/business-partners/jabra_logo.jpg" alt="zoom" srcset="">
<p class="partners-description">
a global brand with a serious passion for sound. Thanks to our expertise in consumer, professional and medical audio technology, our passion is backed up by unrivaled knowledge of the human ear. We’re in the business of helping you hear what you want to hear – from letting the right sound in, to filtering disruptive noise out – but our products are about so much more than that, packed with intuitive features to make life sound better.
</p>
</div>
<div id="epos" class="partners-content">
<h2 class="partners-name">EPOS</h2>
<img class="partners-img" src="../images/business-partners/EPOS_Logo_-_Black_-_Large.jpg" alt="zoom" srcset="">
<p class="partners-description">
EPOS delivers high-end audio solutions designed for enterprise and gaming. Based on pioneering audio technology, EPOS strive to unleash human potential by perfecting audio experiences and delivering innovative design and performance with all of our audio solutions. <p>
Zoom’s value is to care. We care for our customers, employees, company, community, and
selves. Our culture of delivering happiness stems from this value.
</p>
<p>
EPOS headquarters is located in Copenhagen, Denmark, and is a key hub for our business. EPOS builds on more than 115 years of experience in audio innovation. We operate in a global market with offices and partners in more than 60 countries.
</p>
<p>
EPOS Name is derived from Latin and ancient Greek and is used to describe epic stories, speech and poetry. The name encapsulates our dedication to create solutions that enable ways of communication through the Power of Audio. </p>
<p>
EPOS is part of the Demant group – a world-leading audio and hearing technology group that offers solutions and services to help people connect and communicate with the world around them. The Demant Group operates in a global market with companies in more
than 30 countries, employs more than 16,000 employees and generates an annual revenue of DKK 14.5 billion.
</p>
</div>
<div id="dten" class="partners-content">
<h2 class="partners-name">DTEN</h2>
<img class="partners-img" src="../images/business-partners/DIC_i_Yi_400x400.jpg" alt="zoom" srcset="">
<p class="partners-description">
DTEN builds innovative communications technology creating the ideal environment to communicate and collaborate.
</p>
<p>
DTEN develops award-winning collaboration solutions that combine all-in-one cutting- edge features, plug-and-play ease, high quality performance and affordability.
</p>
<p>
DTEN's Zoom certified appliances and integrated service subscriptions revolutionize the way teams around the world connect, communicate and collaborate.
</p>
<p>
Founded in 2015, DTEN is rapidly becoming a recognized international leader for innovation and accessibility in communication.
</p>
<h4>
DTEN D7
Wins 2019 Red Dot Best Of The Best Award
</h4>
<p>
DTEN is a 2019 recipient of the prestigious Red Dot: Best of the Best Award for D7. The Red Dot Award recognizes D7 for innovative product design, including breakthrough technology, inherent functionality and streamlined aesthetics.
</p>
</div>
<div id="ttec" class="partners-content">
<h2 class="partners-name">TTec</h2>
<img class="partners-img" src="../images/business-partners/ttec.jpg" alt="zoom" srcset="">
<p class="partners-description">
Zoom Video Communications, Inc. brings teams together to get more done in a frictionless video environment. easy, reliable, and innovative video-first unified communications platform provides video meetings, voice, webinars, and chat across desktops, phones, mobile devices, and conference room systems. Zoom helps enterprises create elevated experiences with leading business app integrations and developer tools to create customized workflows. </p>
<p>
Zoom’s value is to care. We care for our customers, employees, company, community, and
selves. Our culture of delivering happiness stems from this value.
</p>
</div>
</div>
</div>
</div>
</section>
</body>
</html>

Divs appearing all at once rather than individually

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>

trying to collapse text [duplicate]

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>

adding an active state to menu link with javascript

I am trying to add an active state to my fadetoggle menu.
When the user clicks on one of the menu options, the menu fades in and with it an arrow appears under the active menu item. The menu fades in and out when the user clicks on it, what I cant get right is the active state. I have seen a couple of examples online. I want simple to understand code and I have come up with the following javascript code:
$(function() {
$('.menu-item-recovery a').live('click', function(event) {
$('.recovery-bg').show();
$('.recovery-bg').addClass('active');
return false;
});
});
When the user clicks on any of the links below:
<!--Logo & Second Nav-->
<div class="container hidden-phone">
<div class="row">
<div class="span9 second-nav">
<div class="menu-wrapper">
<div class="menu-item-recovery recovery trigger" data-target=".recovery-bg">
Recovery
</div>
<div class="menu-item-forensic trigger" data-target=".forensic-bg">
Forensics
</div>
<div class="menu-item-erasure trigger" data-target=".erasure-bg">
Erasure
</div>
<div class="menu-item-training trigger" data-target=".training-bg">
Training
</div>
<div class="menu-item-products trigger" data-target=".product-bg">
Products
</div>
</div>
</div>
</div>
</div>
<!--/Logo & Second Nav-->
The following menu fades in and an active state needs to be added to it:
<!--Expanding Recovery Menu-->
<div class="recovery-bg arrow_box_recovery toggle hidden-phone">
<div class="container expand">
<div class="row">
<div class="span12">
<div class="menu-item menu-item-1 menu-first-rec">
<a href="http://dev.disklabs.com/html/data-recovery.html">
<p>Data <br/> Recovery</p></a>
</div>
<div class="menu-item menu-item-2">
<a href="">
<p>Raid <br/> Recovery</p></a>
</div>
<div class="menu-item menu-item-3">
<a href="">
<p>Forensic <br/> Data Recovery</p></a>
</div>
<div class="menu-item menu-item-4">
<a href="">
<p>Tape <br/> Recovery</p></a>
</div>
</div>
</div>
</div>
</div>
<!--/Expanding Recovery Menu-->
css for the active state, not sure where I need to put it:
.active {
width: 40px;
height: 20px;
background: url(../img/menu-arrow-recovery.png) no-repeat;
}
I ended up using the cssarrowplease code I found through the stackoverflow forums. I have added a link to it cssarrowplease Its a great tool and I customised it a little because the site is responsive I changed the css so that I could add a different active arrow for every dropdown arrow. Here is the code I ended up with to achieve this.
/*------------------------------------
/ Recovery Navigation Arrow
/-----------------------------------*/
.arrow_box_recovery {
position: relative;
background: #05f397;
/*border: 4px solid $recovery;*/
}
.arrow_box_recovery:after {
content: url("http://dev.disklabs.com/html/assets/img/menu-arrow-recovery.png") no-repeat;
height: 20px;
width: 40px;
position: absolute;
top: -13%;
margin-left: -80px;
bottom: 100%;
border: solid transparent;
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.arrow_box_recovery:after {
border-color: rgba(5, 243, 151, 0);
border-bottom-color: #05f397;
}
.arrow_box_recovery:before {
border-color: rgba(5, 243, 151, 0);
border-bottom-color: #05f397;
}
Here is a link to my fiddle gives an example of what I wanted to achieve.
working fiddle
Hopefully it might help someone else looking to achieve the same thing.

How can I expand and collapse a <div> using javascript?

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>

Categories

Resources