Creating / Removing a Row in a series of float: left divs - javascript

I have a list of div elements, all with float:left one after another like so
<div id="container">
<div id=0" style="float:left;> Stuff </div>
<div id=1" style="float:left;> Stuff </div>
<div id=2" style="float:left;> Stuff </div>
...
<div id=n" style="float:left;> Stuff </div>
</div>
What I am trying to achieve is the following:
If I click on one of the divs, it will push the surrounding divs away (the ones on its left up and the ones on its right down) and populate its own row. Then when clicked again it returns to the original configuration.
My Attempts:
Add a brute force separator: just use jQuery to stack before and after the div
Toggle the CSS property: clear: both for the desired div
It may be because it is rather late, but neither of these approaches seem reliable. What would be a more reasonable means of attaining this functionality?
Thanks for your time!

I think you want to achieve this, please check this Fiddle
var parentWidth = $("#container").css("width");
var originalWidth = $($("#container div")[0]).css("width");
$("#container div").click(function(){
if($(this).css("width") != parentWidth) {
$(this).css("width",parentWidth);
}
else {
$(this).css("width",originalWidth);
}
});

var divWidth = 250;
var n= 5; //this will be no of inner divs
$(function(){
$('#container div').each(function(index, element) {
$(this).click(function(e) {
if($(this).width() == divWidth)
{
var dt = divWidth;
if(index != 0)
{
$(this).prev().hide();
dt += divWidth;
}
else if(index < n)
{
$(this).next().hide();
dt += divWidth;
}
$(this).width(dt);
}
else
{
$(this).width(divWidth);
if(index != 0)
{
$(this).prev().show();
}
else if(index < n)
{
$(this).next().show();
}
}
});
});
});

Related

Addclass when div width is greater than 80%

How to addclass when div width is greater than 80% ?
This is what I just tried
<div class="wrap_bar">
<div class="bar" style="width:50%;"></div>
</div>
<div class="box"></div>
<script>
var barTotal = $(".bar");
var box= $(".box");
var width = barTotal.width();
if (width > 80%)
box.addClass('type2')
</script>
This code is not working well. Please help
If you need this dimension detection only one time (when DOM loaded) then you can just following approach.
function addWhenResized(element){
var parentWidth = $(element).parent().width();
var elementWIdth = $(element).width();
if( (elementWIdth / parentWidth)*100 > 79){
$('.box').addClass('type2');
}
else {
$('.box').removeClass('type2');
}
}
$(document).ready(function(){
addWhenResized('.bar');
})
But main challenge will be there if you want detect the run time dimension change. Then need to take help from here: http://marcj.github.io/css-element-queries/
After added the plugins from above given link you should follow the following approach:
function addWhenResized(element){
var parentWidth = $(element).parent().width();
var elementWIdth = $(element).width();
if( (elementWIdth / parentWidth)*100 > 79){
$('.box').addClass('type2');
}
else {
$('.box').removeClass('type2');
}
}
new ResizeSensor(jQuery('.bar'), function(){
addWhenResized('.bar');
});
Try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var barTotal = $(".bar");
var barTotalWidth = barTotal.width();
var box= $(".box");
var boxWidth = box.width();
var widthPercent = boxWidth / barTotalWidth;
console.log(widthPercent);
if (widthPercent > 0.8)
box.addClass('type2');
});
</script>
<div class="bar" style="width:200px;height:100px;background-color:red"> </div>
<div class="box" style="width:190px;height:80px;background-color:blue"> </div>
your codes don't work because you've just called javascript once when the page loaded , you have to wrap it into an event !
Take a look
that answer
or that answer
jQuery(document).ready(function($) {
if ($(this).width() > 768) {
$('#service-1').addClass('row text-center');
} else {
$('#service-1').removeClass('row text-center');
}
});
this will work fantastic when width is less than or more than will add or remove the class

Javascript - Mouse Wheel Go to Class

Every time I use the mouse wheel (you know normal scrolling) I want the JS (jquery or whatever) to scroll to a specific class (or id doesn't matter).
I have multiple divs so code like $('body').scrollTo($nextdiv) is not an option.
I just want to make every wheel cycle to move to a next div with a specific class/id. The same for the reverse scroll. To move one div (with a specific class) up.
I found mouse wheel event and how to move to a specific div but can't manage to make it work together.
Animated scroll would be cool.
Simple question. Can I have class AND id in the same div? ex <div class="a" id="b"> ?
Quick example, this code can be improved. Better to test on jsfiddle. Point mouse over list and scroll.
Note: I didn't use class but if you understand what I did it's easy to use classes.
Note 2: I just change color but logic can be replace with anything you want.
demo
demo 2 (with classes)
var i = 0;
var list = document.getElementById("list"), length = list.children.length;
list.addEventListener("wheel", ColorLi);
function ColorLi(e) {
//reset colors
for(var j = 0; j < length; j++)
list.children[j].style.color = "black";
//calculate index
if(e.wheelDelta > 0)
i++;
else
i--;
//fix index out of range
i = i < 0 ? 0 : i;
i = i > length-1 ? length-1 : i;
//set color
list.children[i].style.color = "red";
}
<ul id="list">
<li style="color: red">A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
You could use the following plugins: jquery.mousewheel and jquery.scrollTo plugin, like:
/*!
* jQuery Mousewheel 3.1.13
*
* Copyright 2015 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a:a(jQuery)}(function(a){function b(b){var g=b||window.event,h=i.call(arguments,1),j=0,l=0,m=0,n=0,o=0,p=0;if(b=a.event.fix(g),b.type="mousewheel","detail"in g&&(m=-1*g.detail),"wheelDelta"in g&&(m=g.wheelDelta),"wheelDeltaY"in g&&(m=g.wheelDeltaY),"wheelDeltaX"in g&&(l=-1*g.wheelDeltaX),"axis"in g&&g.axis===g.HORIZONTAL_AXIS&&(l=-1*m,m=0),j=0===m?l:m,"deltaY"in g&&(m=-1*g.deltaY,j=m),"deltaX"in g&&(l=g.deltaX,0===m&&(j=-1*l)),0!==m||0!==l){if(1===g.deltaMode){var q=a.data(this,"mousewheel-line-height");j*=q,m*=q,l*=q}else if(2===g.deltaMode){var r=a.data(this,"mousewheel-page-height");j*=r,m*=r,l*=r}if(n=Math.max(Math.abs(m),Math.abs(l)),(!f||f>n)&&(f=n,d(g,n)&&(f/=40)),d(g,n)&&(j/=40,l/=40,m/=40),j=Math[j>=1?"floor":"ceil"](j/f),l=Math[l>=1?"floor":"ceil"](l/f),m=Math[m>=1?"floor":"ceil"](m/f),k.settings.normalizeOffset&&this.getBoundingClientRect){var s=this.getBoundingClientRect();o=b.clientX-s.left,p=b.clientY-s.top}return b.deltaX=l,b.deltaY=m,b.deltaFactor=f,b.offsetX=o,b.offsetY=p,b.deltaMode=0,h.unshift(b,j,l,m),e&&clearTimeout(e),e=setTimeout(c,200),(a.event.dispatch||a.event.handle).apply(this,h)}}function c(){f=null}function d(a,b){return k.settings.adjustOldDeltas&&"mousewheel"===a.type&&b%120===0}var e,f,g=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],h="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],i=Array.prototype.slice;if(a.event.fixHooks)for(var j=g.length;j;)a.event.fixHooks[g[--j]]=a.event.mouseHooks;var k=a.event.special.mousewheel={version:"3.1.12",setup:function(){if(this.addEventListener)for(var c=h.length;c;)this.addEventListener(h[--c],b,!1);else this.onmousewheel=b;a.data(this,"mousewheel-line-height",k.getLineHeight(this)),a.data(this,"mousewheel-page-height",k.getPageHeight(this))},teardown:function(){if(this.removeEventListener)for(var c=h.length;c;)this.removeEventListener(h[--c],b,!1);else this.onmousewheel=null;a.removeData(this,"mousewheel-line-height"),a.removeData(this,"mousewheel-page-height")},getLineHeight:function(b){var c=a(b),d=c["offsetParent"in a.fn?"offsetParent":"parent"]();return d.length||(d=a("body")),parseInt(d.css("fontSize"),10)||parseInt(c.css("fontSize"),10)||16},getPageHeight:function(b){return a(b).height()},settings:{adjustOldDeltas:!0,normalizeOffset:!0}};a.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})});
// The actual code:
$(document).ready(function () {
var targets = $('.scroll'); // List of elements to scroll to
var index = 0;
var duration = 500;
var canScroll = true;
var cache;
function limit(x, min, max) {
return Math.min(max, Math.max(min, x));
}
$(window).mousewheel(function (ev) {
if (canScroll) {
cache = index;
if (ev.deltaY < 0) {
index = index + 1; // Scrolling down, so increase index
} else {
index = index - 1; // Scrolling up, so decrease index
}
// Make sure the index is between 0 and (targets.length - 1)
index = limit(index, 0, targets.length - 1);
console.log(index);
// Make sure to scroll if and only if the value has changed
if (index !== cache) {
// Scroll to the target element:
$(window).scrollTo(targets.get(index), {
duration: duration,
easing: 'swing'
});
canScroll = false;
setTimeout(function () {
canScroll = true;
}, duration);
}
}
ev.preventDefault();
return false;
});
});
div {
content: ' ';
height: 500px;
background-color: #f2f2f2;
}
div:nth-child(even) {
background-color: #d0d0d0;
}
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//cdn.jsdelivr.net/jquery.scrollto/2.1.0/jquery.scrollTo.min.js"></script>
<div class="scroll">div1</div>
<div class="scroll">div2</div>
<div class="scroll">div3</div>
<div class="scroll">div4</div>
<div class="scroll">div5</div>
<div class="scroll">div6</div>

Split a big ul list

I have a big ul list. With a lot of li items. I want split this big list in parts of 10. I make a script, but the script is not working. What do i wrong:
var maxItems = 10;
var ul = $('.list-thumbnails');
var current;
ul.find('li').each(function(i, el) {
  if (i < maxItems) {
    // leave first 10 in the original list
    return;
  }
  if (i % maxItems == 0) {
    current =
        $(el)
            .closest('ul')
            .clone()
            .after($(el).closest('ul'));
  }
.append(current);
});
I have modified the code block as below. Please check it
Since your looping the $.each though you use append method it won't get reflected in the ul and so we need to remove the element.
var maxItems = 10;
var ul = $('.list-thumbnails');
var currentul;
var elements = ul.find('li');
elements.each(function (i, el) {
if (i < maxItems) {
// leave first 10 in the original list
return;
}
if (i % maxItems == 0) {
currentul = $("<ul></ul>").addClass("new");
$(el).closest('ul').parent().append((currentul.append(el)));
}
else {
currentul.append(el)
}
});
$('.list-thumbnails').find("li:gt(9)").remove();
Please check the below jsfiddle
http://jsfiddle.net/aQ5K8/13/
Thanks
Sridhar

Making a dropdown menu thats width is decided upon the amount of sections within it

I am building a dropdown menu for a site and i am trying to change the width of the parent div (.drop-down) depending on how many sections that instance of the element has within it. There are a total of 7 instances of .drop-down each containing different amounts of sections no more than 3 but at least 1. Here is my code where am i going wrong?
$('.drop-down').each(function(index) {
var numSections = $(this).find('section').length;
if (numSections = 1) {
$('.drop-down').css('width','300px');
}
else if (numSections = 2) {
$('.drop-down').css('width','600px');
}
else
$('.drop-down').css('width','840px');
});
any help would be greatly appreciated.
$('.drop-down').each(function(index)
{
var numSections = $(this).find('section').length;
if (numSections == 1) {
$(this).css('width', 300);
}
else if (numSections == 2) {
$(this).css('width', 600);
}
else if (numSections == 3){
$(this).css('width', 840);
}
});
You don't specify which class of .drop-down you are targetting. Try $(this):
$('.drop-down').each(function(index) {
var numSections = $(this).find('section').length;
if (numSections = 1) {
$(this).css('width','300px');
}
else if (numSections = 2) {
$(this).css('width','600px');
}
else
$(this).css('width','840px');
});
You may also declare the new width as an integer instead of a string, like so:
$(this).css('width',840);
EDIT: Here's a basic jsFiddle: http://jsfiddle.net/MFfgj/

Jquery + HTML Thumbnail scroll

I want to create a list of thumbnails with a button previous and another next, showing 10 thumbnails at a time and hiding the rest, and when you reach the 10th tumbnail and click the next button, the 1st disappear and appear the 11th.
I've tried with:
Javascript
jQuery(document).ready(function() {
var count = 0;
var images = 11;
var page = 1;
var current = 1;
jQuery('.ice-navigator li').each(function(index) {
count++;
jQuery(this).attr('id', 'menu-item-' + count);
jQuery(this).attr('class', 'menu-page-' + page);
if(count >= (page * images)) {
page++;
}
jQuery(this).hide();
})
jQuery('.ice-navigator li.menu-page-1').show();
jQuery('.ice-next').click(function() {
if(current >= count) {
current = 1;
} else {
current++;
}
item = jQuery('.ice-navigator li#menu-item-' + current);
if(jQuery(item).hasClass('active')) {
jQuery(item).removeClass('active');
page = jQuery('.ice-navigator li#menu-item-' + current).attr('class');
jQuery(item).addClass('active');
} else {
page = jQuery('.ice-navigator li#menu-item-' + current).attr('class');
}
jQuery('.ice-navigator li').hide();
jQuery('.ice-navigator li.' + page).show();
})
jQuery('.ice-previous').click(function() {
current--;
if(current <= 0) {
current = count;
}
item = jQuery('.ice-navigator li#menu-item-' + current);
if(jQuery(item).hasClass('active')) {
jQuery(item).removeClass('active');
page = jQuery('.ice-navigator li#menu-item-' + current).attr('class');
jQuery(item).addClass('active');
} else {
page = jQuery('.ice-navigator li#menu-item-' + current).attr('class');
}
})
jQuery('.ice-navigator li').click(function() {
current = jQuery(this).attr('id').replace('menu-item-', '');
})
})
HTML
<div class="ice-previous">Previous</div>
<div class="ice-navigator-wrapper clearfix">
<div class="ice-navigator-outer">
<ul class="ice-navigator">
<li>THUMBNAIL 1</li>
<li>THUMBNAIL 2</li>
[...]
<li>THUMBNAIL 11</li>
<li>THUMBNAIL 12</li>
</ul>
</div>
</div>
<div class="ice-next">Next</div>
Thanks!
Edit: I now understand it is like a circular ref. I have made some changes accordingly.
See my updated DEMO here
Below is for regular nav which stops when you reach the end.
Check my old DEMO here.
I used 2 pointers to manage the start and end position. Implemented adjustNav function to show/hide div based on start and end position.
This looks like a job for jCarousel:
http://sorgalla.com/jcarousel/
There are other plugins that provide this functionality. I just used jCarousel on another project and it was the first thing I thought of.
EDIT
I didn't realize you don't want to use a plugin. You could do this with hand-coded jQuery, but you're going to be writing a lot of code.

Categories

Resources