CSS floats with maximizing widths? - javascript

I have 5 divs and I'm trying to structure them in the following way:
The divs have a minimum size of 100px
The parent has to show as much of these as possible on the first row; the remaining divs should be wrapped to a new row (or more rows if necessary)
If the first row has a non optimal size the divs should be distributed equally (ie. parent size is 250px - there are 2 divs on the first row having a width of 125px).
Some examples of what I'm trying to achieve:
200px: http://s22.postimg.org/5hj8m5qrl/es3.png
250px: http://s22.postimg.org/ikev5fgzl/es1.png
300px: http://s22.postimg.org/jy6i0qg8x/es2.png
If the size of the parent is 450px, there should be 4 divs, having a width of 112.5px each.
This is what I've tried, but I only got the wrapping done. I have no idea on how to resize them:
HTML:
<div class="parent">
<div class="child">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget vulputate justo. Phasellus non mi metus.</div>
<div class="child">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget vulputate justo. Phasellus non mi metus.</div>
<div class="child">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget vulputate justo. Phasellus non mi metus.</div>
<div class="child">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget vulputate justo. Phasellus non mi metus.</div>
<div class="child">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis eget vulputate justo. Phasellus non mi metus.</div>
<div class="clear"></div>
CSS
.parent{
width: 250px;
border: 2px solid red;
}
.parent .child {
width: 96px;
border: 2px solid black;
float: left;
}
.parent .clear {
clear: both;
}
There is the link to jfiddle: http://jsfiddle.net/Vbjv5/
I'm looking for a possibile CSS solution, however if it's not possible to achieve this in CSS, javascript is still welcome :)

use jquery simply like this.
jQuery(document).ready(function($) {
var parent_width=$('.parent').width();
var count=$('.item').length();
var param=parent_width/count;
$('.item').width(param);
});

Related

Fade in / out text when it enters a specific position in the viewport

I'm trying to fade in / out text when the user scrolls to a specific position within the viewport. It should look like what you can see on a website from apple. They used this effect at the bottom of the page in the section that says
"New Apple Originals every month.
Always ad-free and on demand."
Here's a video of the effect
I've found a snippet that does in some kind of way what I am trying but the div that is holding the text always has a height of xxvh.
Here's what I have:
function isElementInViewport(element) {
var rect = element.getBoundingClientRect();
return (
rect.top >= -160 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
var elements = document.querySelectorAll(".greyline");
function callbackFunc() {
for (var i = 0; i < elements.length; i++) {
if (isElementInViewport(elements[i])) {
elements[i].classList.add("blackline");
}
else {
elements[i].classList.remove("blackline");
}
}
}
window.addEventListener("load", callbackFunc);
window.addEventListener("scroll", callbackFunc);
.greyline {
color:rgba(0, 0, 0, 0.3);
height:65vh;
}
.blackline {
color: black;
transition: 0.7s;
}
.textline {
line-height: 2em;
max-width: 500px;
margin:0 auto;
margin-bottom:2em;
font-size: 30px;
}
<div class="greyline">
<div class="textline">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.</div></div>
<div class="greyline">
<div class="textline">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.</div></div>
<div class="greyline">
<div class="textline">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.</div></div>
<div class="greyline">
<div class="textline">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.</div></div>
<div class="greyline">
<div class="textline">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.</div></div>
Here's a Fiddle
I hope you can help me. If you need any further information let me know.
Thanks in advance!
Edit: Hope this graphic shows the effect I want to reach
sketch of the effect

Accessing updated CSS values from previously animated elements in a Greensock timeline

I have a TimelineLite() which performs a series of .to() tweens in sequential order. I'd like to be able to use the value that results from one of the early tweens in the construction of one of the later tweens.
Is there anyway to access the values of elements that have previously completed their animation in a timeline?
UPDATED:
The example that I provided originally was quite crude. I've updated it to more accurately reflect what I'm running into.
The size of the colored div are dependent on the viewport, and the content within them flows based on that size. Clicking on one of them begins an animation which expands the clicked div to fill the viewport and removes the non-clicked divs. This resizing causes the text to reflow to adjust for the new space.
Then div.status (that was previously absolutely positioned off the bottom of the page) animates up to be below the selected colored div. Unfortunately, the height that is used to calculate its new top value is what the selected colored div's height was prior to the animation and subsequent reflow of it's content.
var timeline = new TimelineLite();
$('.clickable').click(function(){
var $selected = $(this);
var $notSelected = $('.clickable').not($(this));
$selected.addClass('selected');
$notSelected.addClass('not-selected');
timeline
.add("optionSelected")
.to(
$selected,
0.5,
{ "width":"96%" },
"optionSelected"
)
.to(
$notSelected,
0.5,
{
"width":"0%",
"padding":"0"
},
"optionSelected"
)
.to(
$(".status"),
0.5,
{
"top":$('.selected').height()
}
)
})
body{
position:relative;
height:100vh;
overflow:hidden;
background-color:cornsilk;
}
section{
background-color:#ddd;
display:flex;
align-items: flex-start;
}
div{
width: 30%;
padding:2%;
color: #FFF;
display:inline-block;
}
.clickable{cursor:pointer;}
.status{
width:96%;
position:absolute;
top:100%;
left:0;
background-color:#FFF;
color:black;
border:1px solid black;
}
.blue{background-color:blue;}
.green{background-color:green;}
.purple{background-color:purple;}
.not-selected{
white-space: nowrap;
overflow:hidden;
}
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.0/TweenMax.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section>
<div class="blue clickable"><strong>Clickable</strong> - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Dignissim tortor, sit amet vulputate augue lectus vel felis. Cras ac ex vel ligula porta laoreet.
</div>
<div class="green clickable"><strong>Clickable</strong> - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ultrices, est ut sollicitudin gravida, velit erat dignissim tortor, sit amet vulputate augue lectus vel felis. Cras ac ex vel ligula porta laoreet. Mauris lorem tellus, convallis ac tincidunt eu, efficitur consequat turpis.</div>
<div class="purple clickable"><strong>Clickable</strong> - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ultrices, est ut sollicitudin gravida, velit erat dignissim tortor, sit amet vulputate augue lectus vel felis. Cras ac ex vel ligula porta laoreet.</div>
<div class="status">Status</div>
</section>
</body>
Try returning the desired height from a function as a callback. I think then it won't be executed until after the animation of the .selected element has reached that to() in the chain.
Also height() does not include padding or margins, so you end up with the .status overlapping, try .outerHeight() instead.
Working example:
http://codepen.io/jonwheeler/pen/jAvRZZ?editors=0110

Showing a div only when a certain div's height is > than set height?

I have a tabbing module I created that has scrollable content areas. I made a quick blinking arrow style to let the users know that this box is scrollable. I would like to make it so this div is only visible if my content (scrollable text box area) is above a certain height.
For example, my scrollable area is always set to height:450px. So I need a way to figure out how to get the height of the content area, then if is less than 450px height, to not show my div more-info.
Here is a jsfiddle with a working demo.
HTML Structure
<div class="tabs-left app-about-page">
<div class="more-info"></div>
<ul class="nav nav-tabs">
<li class="active"><span class="glyphicon glyphicon-heart">Donor Acquisition</span></li>
<li><span class="glyphicon glyphicon-star">Donor Cultivation</span></li>
<li><span class="glyphicon glyphicon-headphones">Donor Retention</span></li>
<li><span class="glyphicon glyphicon-time">Donor Blogging</span></li>
<li><span class="glyphicon glyphicon-calendar">Donor Engagement</span></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="a">
</div>
<div class="tab-pane" id="b">
</div>
<div class="tab-pane" id="c">
</div>
<div class="tab-pane" id="d">
</div>
<div class="tab-pane" id="e">
</div>
</div><!-- /tab-content -->
</div><!-- /tabbable -->
From some searching and piecing together, I found something like this, so assume this is the starting point.
$(document).ready(function () {
if ($(".tab-pane").height() > 450 {
jQuery(".more-info").fadeIn(200);
} else {
jQuery(".more-info").hide(100);
});
Just make use of the shown.bs.tab event, to show and hide your arrow div.
Togglable tabs Events
shown.bs.tab
This event fires on tab show after a tab has been shown. Use event.target and event.relatedTarget to target the active tab and the previous active tab (if available) respectively.
$('.more-info').css('display', 'none');
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var activeContentElem = $($(e.target).attr('href'));
if (activeContentElem[0].scrollHeight > activeContentElem.height()) {
$('.more-info').css('display', 'block');
} else {
$('.more-info').css('display', 'none');
}
})
.nav-tabs {
float: left;
border-bottom: 0;
}
.nav-tabs li {
float: none;
margin: 0;
width: 106px;
height: 106.5px;
left: -30px;
top: -20px;
position: relative;
display: block;
background-color: #F2F2F0;
margin-top: 0;
border-bottom: #FFF 2px solid;
text-align: center;
-webkit-transition: all 0.3s linear 0s;
-moz-transition: all 0.3s linear 0s;
-ms-transition: all 0.3s linear 0s;
-o-transition: all 0.3s linear 0s;
transition: all 0.3s linear 0s;
}
.nav-tabs li:last-child{
border:none;
}
.nav-tabs li a{
display: block;
height: 75px;
position: relative;
padding-top: 31px;
font-size: 14px;
color:rgb(51, 51, 51);
text-decoration: none;
}
.nav-tabs li:hover {
background-color: #DBDBDA;
cursor:pointer;
}
.nav-tabs > li.active, .nav-tabs > li.active a, .nav-tabs > li a:active, .nav-tabs > li.active > li:focus, .nav-tabs >li a:focus {
background:rgba(51, 181, 229, 0.45);
color:#FFF;
text-decoration: none;
}
.tab-content {
margin-left: 45px;
}
.tab-content .tab-pane {
display: none;
background-color: #fff;
padding: 0;
overflow-y: auto;
}
.tab-pane p{
margin: 0 0 16px 0;
}
.tab-pane p:first-child{
margin:5px 0 16px;
}
.tab-pane h1{
padding-bottom: 5px;
border-bottom: 1px solid #DBDBDA;
margin-bottom: 16px;
}
.tab-pane img{
max-width: 70%;
}
.tab-content .active {
display: block;
overflow: scroll;
height: 450px !important;
padding: 0px 15px 0 0px;
}
.list-group {
width: 100%;
}
.list-group .list-group-item {
height: 50px;
}
.list-group .list-group-item h4, .list-group .list-group-item span {
line-height: 11px;
}
#-webkit-keyframes circleBounce {
0% {-webkit-transform: scale(0.9); opacity: 0;}
20% {opacity: 0.5;}
50% {opacity: 1;}
80% {opacity: 0.5;}
100% {-webkit-transform: scale(1.1); opacity:0;}
}
.more-info {
position: absolute;
bottom: 30px;
left: calc(50% - 3px);
width: 6px;
height: 6px;
border: 2px solid rgb(51, 181, 229);
border-top: none;
border-left: none;
-webkit-transform: rotate(45deg);
-webkit-transform-origin: 50% 50%;
}
.more-info:after {
content: "";
display: block;
position: absolute;
top: calc(50% - 17px);
left: calc(50% - 17px);
width: 35px;
height: 35px;
border: 1px solid rgba(255,255,255,.8);
border: 1px solid rgb(51, 181, 229);
border-radius: 50%;
-webkit-animation: circleBounce 2.5s linear infinite;
}
.more-info:hover:after {
background-color: rgba(51, 181, 229, .15);
cursor:inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<div class="tabs-left app-about-page">
<div class="more-info"></div>
<ul class="nav nav-tabs">
<li class="active"><span class="glyphicon glyphicon-heart">Donor Acquisition</span></li>
<li><span class="glyphicon glyphicon-star">Donor Cultivation</span></li>
<li><span class="glyphicon glyphicon-headphones">Donor Retention</span></li>
<li><span class="glyphicon glyphicon-time">Donor Blogging</span></li>
<li><span class="glyphicon glyphicon-calendar">Donor Engagement</span></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="a">
<h1>Donor Acquisition</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet.</p>
</div>
<div class="tab-pane" id="b">
<h1>Donor Cultivation</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet.</p>
</div>
<div class="tab-pane" id="c">
<h1>Donor Retention</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet.</p>
</div>
<div class="tab-pane" id="d">
<h1>Nonprofit Blogging</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet.</p>
</div>
<div class="tab-pane" id="e">
<h1>Nonprofit Engagement</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet. Phasellus id est lacus. Pellentesque a elementum velit, a tempor nulla. Mauris mauris lectus, tincidunt et purus rhoncus, eleifend convallis turpis.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce convallis consectetur ligula. Morbi dapibus tellus a ipsum sollicitudin aliquet.</p>
</div>
</div><!-- /tab-content -->
</div><!-- /tabbable -->
First, start your .more-info class as hidden in css.
Then, you could check the height of the content of your tab every time the visible tab changes, and if it is greater than 450px, swap visibility of your more info button.
This is the jQuery snippet:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var div = $($(e.target).attr('href'));
$('.more-info').hide();
if (div.get(0).scrollHeight > 450)
$('.more-info').show();
});
I'm not sure here, but I looked around some more and came up with this.
var clientHeight = document.getElementById('myDiv').clientHeight;
and some combination of this..
[DIV].style.visibility='visible'
[DIV].style.visibility='hidden'
then use an if statement?
Kind of new to coding, but maybe this is on the right track.
You could bind an event to your menu anchors that checks the height of your active div against the scroll height of that div and show or hides the blinking arrow.
Using JQuery, something like this so that it triggers after your bootstrap finishes:
$(document).ready(function(){
$('a[data-toggle="tab"]').on('shown.bs.tab', function (){
ToggleMoreInfoArrow();
//Call the toggle every time the content changes.
});
ToggleMoreInfoArrow(); //Call it the first time the page loads.
});
function ToggleMoreInfoArrow()
{
if( $('div.active').prop('scrollHeight') < $('div.active').height())
{
$('.more-info').hide();
}
else
{
$('.more-info').show();
}
}
Edit: I'm not sure how your "active" class gets set, but you'd want to run the height check code after that happens. This could be on page load or wherever, the if statement is the important bit.
Edit: See this working fiddle: http://jsfiddle.net/9hkpzagz/7/
Hello multinumbered user, I didn't like the script there was in example, and I changed the CSS a bit, moving "more" button to the right bottom corner, but I did the following:
1. you should always have .tab-pane to be of the set height on start and not scrolled, so I changed the CSS to be "overflow: hidden"
I wrote a function that checks the height of tab content and either activate or desactivate "more"
If "more" button is clicked, the tab content CSS 'overflow-y' option is changed to 'auto' - this adds vertical scrollbar.
http://jsfiddle.net/9hkpzagz/8/
here is my js code:
function checkHeightAndSetMore(clickedMore){
var activeTabH=$('.tab-content .active').height();
if(activeTabH >450){
$('div.more-info').fadeIn();
}
else{
$('div.more-info').fadeOut();
}
if(clickedMore == 1){
$('.tab-content .active').css('overflow-y', 'auto');
$('div.more-info').fadeOut();
}
}
$(document).ready(function(){
checkHeightAndSetMore(0);
$('.more-info').click(function(){
checkHeightAndSetMore(1);
});
});

Force text in the child div fit into parent

I have two div tags in my HTML code like this
<div id="parent">
<div id="child">
<p class="child-text"> ..... </p>
<a class="child-link"> ..... </a>
<p class="child-text"> ..... </p>
</div>
</div>
#parent{ height: 400px; width:100px}
How can force the content of #child div vertically fit into the parent div ?
I am looking for some thing that can take child div ID and resize its content dynamically. I have worked with jQuery.fittext. However, it get the child-text class id instead of child div id. In other words, it is not intelligent enough to identify what is in the child div and then rescale them.
Is there any other alternative for this ?
You could do something like:
var fontsize = 10;
while($('#child').height() <= $('#parent').height()){
fontsize = fontsize +1;
$('#child').css('font-size',fontsize+'px');
}
#parent{ height: 400px; width:100px;background:red;}
#child{padding-bottom:5px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="parent">
<div id="child">
<p class="child-text"> Once upon a time </p>
<a class="child-link"> there lived a monkey</a>
<p class="child-text"> who loved to eat oranges </p>
</div>
</div>
While #child height is less then #parent then it adds 1px until it is not. In the css, I gave #child a padding bottom of 5px, so it would not overflow
JSFiddle
Add a display property value of table to #parent and display property value of table-cell to the elements you want to measure the height of #parent
#parent, #child {
width: 100%;
height: 100%;
position: relative;
display: table;
}
.child-link, .child-text { /* ID/Class of whatever element you want to measure the #parent */
display: inline-block;
height: 100%;
width: 150px;
vertical-align: top;
background-color: green;
bottom: 0;
display: table-cell;
border-left: solid 5px white; /* Just for Division sake */
}
<div id="parent">
<div id="child"><p class="child-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sagittis felis nec est iaculis, id rhoncus eros efficitur. Aliquam justo felis, semper in placerat non, facilisis sed elit. </p>
<a class="child-link"> Lorem </a>
<p class="child-text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sagittis felis nec est iaculis, id rhoncus eros efficitur. Aliquam justo felis, semper in placerat non, facilisis sed elit.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sagittis felis nec est iaculis, id rhoncus eros efficitur. Aliquam justo felis, semper in placerat non, facilisis sed elit.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque sagittis felis nec est iaculis, id rhoncus eros efficitur. Aliquam justo felis, semper in placerat non, facilisis sed elit.</p>
</div>
</div>
To make it dependent on the screen size, do something like below:
#media screen and (max-width: 768px) { /* Adjust as needed */
enter code here
}

Is there a better way to write this jQuery script?

So the script works, but it seems pretty long. I think there may be some shortcuts I could take, maybe use an array? But I'm new at JS, and really new at jQuery.
What it does:
I have a list of ten questions, and I want to take a graphic (plus sign) and toggle it when clicked to a minus sign. It will also reveal the answer by using a slide toggle.
Here's the code:
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".divOne").hide();
$(".divTwo").hide();
$(".divThree").hide();
$(".divFour").hide();
$(".divFive").hide();
$(".divSix").hide();
$(".divSeven").hide();
$(".divEight").hide();
$(".divNine").hide();
$(".divTen").hide();
$(".bbone").click(function(){
$(".divOne").slideToggle("slow");
$("#button1").toggleClass("down");
});
$(".bbtwo").click(function(){
$(".divTwo").slideToggle("slow");
$("#button2").toggleClass("down");
});
$(".bbthree").click(function(){
$(".divThree").slideToggle("slow");
$("#button3").toggleClass("down");
});
$(".bbfour").click(function(){
$(".divFour").slideToggle("slow");
$("#button4").toggleClass("down");
});
$(".bbfive").click(function(){
$(".divFive").slideToggle("slow");
$("#button5").toggleClass("down");
});
$(".bbsix").click(function(){
$(".divSix").slideToggle("slow");
$("#button6").toggleClass("down");
});
$(".bbseven").click(function(){
$(".divSeven").slideToggle("slow");
$("#button7").toggleClass("down");
});
$(".bbeight").click(function(){
$(".divEight").slideToggle("slow");
$("#button8").toggleClass("down");
});
$(".bbnine").click(function(){
$(".divNine").slideToggle("slow");
$("#button9").toggleClass("down");
});
$(".bbten").click(function(){
$(".divTen").slideToggle("slow");
$("#button10").toggleClass("down");
});
});
</script>
Here's the CSS:
<style type="text/css">
body
{
font-family:Verdana, Arial, Helvetica, sans-serif;
}
.divOne, .divTwo, .divThree, .divFour, .divFive, .divSix, .divSeven, .divEight, .divNine, .divTen
{
border:1px solid #CC0000;
background-color:#efefef;
width:580px;
margin-top:5px;
font-size:10px;
padding:5px;
clear:left;
}
.one, .two, .three, .four, .five, .six, .seven, .eight, .nine, .ten
{
padding-left:10px;
text-decoration:none;
color:#CC0000;
font-variant:small-caps;
font-size:14px;
}
.bbone, .bbtwo, .bbthree, .bbfour, .bbfive, .bbsix,.bbseven,.bbeight,.bbnine,.bbten
{
vertical-align:middle;
}
.question
{
height:auto;
background-color:#fff;
margin-bottom:10px;
width:800px;
}
p {
margin:0;
padding:0;
float:left;
width:16px;
height:16px;
background-image:url(images/add.png);
background-repeat:no-repeat;
}
p.down {
float:left;
width:16px;
height:16px;
background-image:url(images/delete.png);
background-repeat:no-repeat;
}
.wwwLink
{
padding-left:20px;
background: transparent url(images/world_go.png) no-repeat center left;
}
</style>
Here's the HTML:
<body>
<div class="question">
<p id="button1" class="bbone"> </p>Myth No. 1: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam egestas. . <br/>
<div class="divOne">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum purus porta urna aliquet consectetur. Maecenas tempus tellus sed augue tincidunt molestie fermentum lorem porttitor. Nam tincidunt elit vitae quam.
Lorem ipsum dolor sit amet, consectetur adipiscing.
</div>
</div>
<div class="question">
<p id="button2" class="bbtwo"> </p>Myth No. 2: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam egestas. <br/>
<div class="divTwo">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum purus porta urna aliquet consectetur. Maecenas tempus tellus sed augue tincidunt molestie fermentum lorem porttitor. Nam tincidunt elit vitae quam. <br/><br/>
Lorem ipsum dolor sit amet, consectetur adipiscing.
</div>
</div>
<div class="question">
<p id="button3" class="bbthree"> </p>Myth No. 3: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam egestas. <br/>
<div class="divThree">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum purus porta urna aliquet consectetur. Maecenas tempus tellus sed augue tincidunt molestie fermentum lorem porttitor. Nam tincidunt elit vitae quam. <br/><br/>
Lorem ipsum dolor sit amet, consectetur adipiscing.
</div>
</div>
<div class="question">
<p id="button4" class="bbfour"> </p>Myth No. 4: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam egestas. <br/>
<div class="divFour">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum purus porta urna aliquet consectetur. Maecenas tempus tellus sed augue tincidunt molestie fermentum lorem porttitor. Nam tincidunt elit vitae quam. <br/><br/>
Lorem ipsum dolor sit amet, consectetur adipiscing.
</div>
</div>
<div class="question">
<p id="button5" class="bbfive"> </p>Myth No. 5: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam egestas. <br/>
<div class="divFive">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum purus porta urna aliquet consectetur. Maecenas tempus tellus sed augue tincidunt molestie fermentum lorem porttitor. Nam tincidunt elit vitae quam. <br/><br/>
Lorem ipsum dolor sit amet, consectetur adipiscing.
</div>
</div>
<div class="question">
<p id="button6" class="bbsix"> </p>Myth No. 6: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam egestas. <br/>
<div class="divSix">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum purus porta urna aliquet consectetur. Maecenas tempus tellus sed augue tincidunt molestie fermentum lorem porttitor. Nam tincidunt elit vitae quam. <br/><br/>
Lorem ipsum dolor sit amet, consectetur adipiscing.
</div>
</div>
<div class="question">
<p id="button7" class="bbseven"> </p>Myth No. 7: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam egestas. <br/>
<div class="divSeven">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum purus porta urna aliquet consectetur. Maecenas tempus tellus sed augue tincidunt molestie fermentum lorem porttitor. Nam tincidunt elit vitae quam.
</div>
</div>
<div class="question">
<p id="button8" class="bbeight"> </p>Myth No. 8: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam egestas. <br/>
<div class="divEight">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum purus porta urna aliquet consectetur. Maecenas tempus tellus sed augue tincidunt molestie fermentum lorem porttitor. Nam tincidunt elit vitae quam.
</div>
</div>
<div class="question">
<p id="button9" class="bbnine"> </p>Myth No. 9: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam egestas. <br/>
<div class="divNine">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum purus porta urna aliquet consectetur. Maecenas tempus tellus sed augue tincidunt molestie fermentum lorem porttitor. Nam tincidunt elit vitae quam. <br/><br/>
Lorem ipsum dolor sit amet, consectetur adipiscing.
</div>
</div>
<div class="question">
<p id="button10" class="bbten"> </p>Myth No. 10: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam egestas. <br/>
<div class="divTen">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum purus porta urna aliquet consectetur. Maecenas tempus tellus sed augue tincidunt molestie fermentum lorem porttitor. Nam tincidunt elit vitae quam. <br/><br/>
Lorem ipsum dolor sit amet, consectetur adipiscing.
</div>
</div>
<body>
Use this instead of any of the jQuery you posted:
$(document).ready(function() {
$('div.question')
.children('div').hide().end()
.children('p').click(function(){
$(this).toggleClass('down').next().slideToggle("slow");
});
});
Also, you really should consolidate your classes. I would use this updated HTML pattern for all your questions:
<div class="question">
<p class="button"> Myth No. 2: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam egestas. </p>
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque interdum purus porta urna aliquet consectetur. Maecenas tempus tellus sed augue tincidunt molestie fermentum lorem porttitor. Nam tincidunt elit vitae quam. <br/><br/>
Lorem ipsum dolor sit amet, consectetur adipiscing.
</div>
</div>
Your CSS would follow this form:
.question { }
.button { } /* Instead of bbOne, bbTwo, etc*/
.question div { } /* Instead of divOne, divTwo, etc */
.question div a { } /* Instead of wwwLink */
And then I would use this slightly updated jQuery:
$(document).ready(function() {
$('div.question')
.children('div').hide().end()
.find('p > a').click(function(e){
$(this)
.parent().toggleClass('down')
.next().slideToggle("slow");
e.preventDefault();
});
});
something like
$(document).ready(function(){
$('.question div').hide();
$('.question p').click(function(){
$(this).next('div').slideToggle("slow");
$(this).addClass('down');
});
});
you could also modify your markup some and use the jquery ui accordion:
http://docs.jquery.com/UI/Accordion
Give your DIVs a common class and use id's for identification, i.e. instead of all the ids on everything, just have one id on the top-level div, and then generic class names on child Ids. Also avoid using and <br/> tags, but do it with CSS padding/margins instead. Something along these lines:
<div class="question" id="question1">
<div class="questionText">
<p class="questionButton"></span>
Myth No. 1: ...
</div>
<div class="questionAnswer">
...
</div>
</div>
This will also simplify your CSS. Just use the common class names instead of enumerating all the questions.
In general you just need to use jQuery on the class names and it will attach itself to all your elements. Also in a jQuery click handler you rarely need to use the ids of elements, you can use $(this) to get the current element and then use traversing functions to get associated elements. Like this:
$(document).ready(function() {
$(".questionAnswer").hide();
$(".questionButton").click(function(){
$(this).parent().find(".questionAnswer").slideToggle("slow");
$(this).toggleClass("down");
});
});
Fred

Categories

Resources