I have a conatiner div with a set height and width positioned relatively. I'd like to figure out in Javascript by how much, if any, it's children extend beyond the container div's edge in the top, right, bottom and left directions. Any help would be much appreciated!
Here's the code for top:
var myDivEl = document.getElementById("my-div");
var divTop = myDivEl.getBoundingClientRect().top;
var descendants = myDivEl.getElementsByTagName("*");
var tops = [];
for (var i = 0, descendant; descendant = descendants[i]; ++i) {
tops.push(descendant.getBoundingClientRect().top);
}
var minTop = Math.min.apply(Math, tops);
var diff = divTop - minTop;
More generally:
function getBoundingClientRectDiff(el, propName, minOrMax) {
var propValue = el.getBoundingClientRect()[propName];
var descendants = myDivEl.getElementsByTagName("*");
var descendantPropValues = [];
for (var i = 0, descendant; descendant = descendants[i]; ++i) {
descendantPropValues.push(descendant.getBoundingClientRect()[propName]);
}
var extremePropValue = Math[minOrMax].apply(Math, descendantPropValues);
return minOrMax === "Max" ? extremePropValue - propValue
: propValue - extremePropValue;
}
function getBoundingClientRectDiffs(el) {
return {
top: getBoundingClientRectDiff(el, "top", "Min"),
right: getBoundingClientRectDiff(el, "right", "Max"),
bottom: getBoundingClientRectDiff(el, "bottom", "Max"),
left: getBoundingClientRectDiff(el, "left", "Min")
};
}
// use like so:
var diffs = getBoundingClientRectDiffs(myDivEl);
console.log(diffs.top, diffs.right, diffs.bottom, diffs.left);
You could also get the difference between an element's width and scrollWidth or height and scrollHeight properties.
Related
To fully understand this note this; `when the page loads it gets the area of the image (width * height) and creates all the x,y positions for all the positions in the area.
This works fine.
When I have another area from pos x,y and with also an area (width * height) should pop the positions from the first list so it can separate the two areas.
Little bug I noticed is I get little lines that are horizontal to the selected area and they don't extend far from that. I believe the reason is instead of making a clean square inside the image every line is offseted by a pixel or two.
Here's a video of the behaviour https://youtu.be/v1b6dEmfxQw
so since there's already an all positions list this code created a clone of the array and removes the positions.
var drop_boxes = $('.drop-box');
var area_grid = [];
var image_width = $('.img-class')[0].naturalWidth;
var image_height = $('.img-class')[0].naturalHeight;
drop_boxes.each(function() {
var position = $(this).position();
var width = $(this).width();
var height = $(this).height();
var positions_clone = positions.slice(0);
//console.log(positions_clone.length);
var top_offset = parseInt((position['top'] * image_width)/img_width);
var left_offset = parseInt((position['left'] * image_height)/img_height);
position['top'] = top_offset;
position['left'] = left_offset;
var width_offset = parseInt((width * image_width)/img_width);
var height_offset = parseInt((height * image_height)/img_height);
var width_counter = 0;
var height_counter = 0;
var area = width_offset * height_offset;
console.log(position);
console.log(width_offset);
console.log(height_offset);
if (position['top'] < image_height-1 && position['left'] < image_width) {
for (counter = 0; counter < area; counter++) {
var pos = [parseInt(position['left']+width_counter), parseInt(position['top']+height_counter)];
var index = positions.findIndex(function(item) {
// return result of comparing `data` with `item`
// This simple implementation assumes that all `item`s will be Arrays.
return pos.length === item.length && item.every(function(n, i) { return n === pos[i] });
});
//console.log(pos);
if (index > -1) {
positions_clone.splice(index, 1);
}
//area_grid.push(pos);
if (width_counter == width_offset) {
width_counter = 0;
height_counter += 1;
}
if (counter%100 == 0) {
var percentage = Math.round((counter/area)*100, 2);
console.log("Percentage: "+percentage+"%" + " "+counter);
}
width_counter += 1;
}
console.log(positions_clone.length);
console.log(area_grid.length);
areas[area_counter] = {'area': area_grid, 'positions': positions_clone};
parent.find('.area').text(area_counter);
area_counter += 1;
}
any clues in fixing it will be appreciated. I've showed how it behaves after commenting out certain parts of the code in the video.
Change
var index = positions.findIndex(function(item) {
to
var index = positions_clone.findIndex(function(item) {
Because after each splice, the indices of the original positions doesn't change but you are still using those indices to splice the clone.
If I have an element styled with scrollbar pseudoclasses (eg in chrome), is it possible to find a css property of that pseudoclass? An example:
<body><div #a></div></body>
<style>
#a::-webkit-scrollbar {
width: 10px
}
</style>
I've tried using getComputedStyle(domNode,'::-webkit-scrollbar').width, but its not returning the correct value.
You can subtract the element's offset by its client size which will give the scroll bar size.
var myDiv = document.getElement...
var verticalScrollBarWidth = myDiv.offsetWidth - myDiv.clientWidth;
var horizontalScrollBarHeight = myDiv.offsetHeight - myDiv.clientHeight;
Here are two properties:
Object.defineProperty(HTMLElement, "verticalScrollBarWidth", {
get: function() {
var tmpWidth = HTMLElement.offsetWidth - HTMLElement.clientWidth;
if (tmpWidth > 0)
return tmpWidth;
return -1;
},
set: undefined
});
Object.defineProperty(HTMLElement, "horizontalScrollBarHeight", {
get: function() {
var tmpHeight = HTMLElement.offsetHeight - HTMLElement.clientHeight;
if (tmpHeight > 0)
return tmpHeight;
return -1;
},
set: undefined
});
Usage:
var myDiv = document.getElement...
var vScrollBarWidth = myDiv.verticalScrollBarWidth;
var hScrollBarWidth = myDiv.horizontalScrollBarHeight;
I'm using the plugin imagefill (http://johnpolacek.github.io/imagefill.js/).
You can see when the site loads it initially loads the image at the top then the plugin fires and the image repositions itself to where it should be. Any idea how i can get this happening as soon as the page loads without any lag?
I've tried to lower the resolution of the image down to 70kb but still happens so don't think it has anything to do with image size.
Code below...
Thanks!
Javascipt for imagefill
var $container = this,
imageAspect = 1/1,
containersH = 0,
containersW = 0,
defaults = {
runOnce: false,
target: 'img',
throttle : 200 // 5fps
},
settings = $.extend({}, defaults, options);
var $img = $container.find(settings.target).addClass('loading').css({'position':'absolute'});
// make sure container isn't position:static
var containerPos = $container.css('position');
$container.css({'overflow':'hidden','position':(containerPos === 'static') ? 'relative' : containerPos});
// set containerH, containerW
$container.each(function() {
containersH += $(this).outerHeight();
containersW += $(this).outerWidth();
});
// wait for image to load, then fit it inside the container
$container.imagesLoaded().done(function(img) {
imageAspect = $img.width() / $img.height();
$img.removeClass('loading');
fitImages();
if (!settings.runOnce) {
checkSizeChange();
}
});
function fitImages() {
containersH = 0;
containersW = 0;
$container.each(function() {
imageAspect = $(this).find(settings.target).width() / $(this).find(settings.target).height();
var containerW = $(this).outerWidth(),
containerH = $(this).outerHeight();
containersH += $(this).outerHeight();
containersW += $(this).outerWidth();
var containerAspect = containerW/containerH;
if (containerAspect < imageAspect) {
// taller
$(this).find(settings.target).css({
width: 'auto',
height: containerH,
top:0,
left:-(containerH*imageAspect-containerW)/2
});
} else {
// wider
$(this).find(settings.target).css({
width: containerW,
height: 'auto',
top:-(containerW/imageAspect-containerH)/2,
left:0
});
}
});
}
function checkSizeChange() {
var checkW = 0,
checkH = 0;
$container.each(function() {
checkH += $(this).outerHeight();
checkW += $(this).outerWidth();
});
if (containersH !== checkH || containersW !== checkW) {
fitImages();
}
setTimeout(checkSizeChange, settings.throttle);
}
return this;
Function to run it - $('.header-image').imagefill();
Container it sits in - div class="header-image"
Css for header-image(before javascript styles get added) - height: 285px; overflow: hidden; margin-top: 170px;
I developed this interaction / script that scales whatever element is passed to it and if that element is pinched in on, it scales down / less.
This is how the script is initialised ( passing two arguments the container and the item to be scaled / transformed:
$(function(){
var zoom = new collapse('#zoom','#zoom :first');
var zoom2 = new collapse('#zoom2','#zoom2 :first');
var zoom3 = new collapse('#zoom3','#zoom3 :first');
});
It works fine as above on single IDs, but I need it to work on a class.
I tried this:
$(function(){
var zoom = new collapse('#zoom','.polaroid');
});
But that causes the whole script not to work because all the elements in that class are being passed instead of one as with an id.
This would only select the first item in the class so it won't work:
$(function(){
var zoom = new collapse('#zoom','.polaroid :first');
});
How can I change my script so that it is applied to all members of the .polaroid class in the #main container?
Here is my script:
function collapse(container, element){
container = $(container).hammer({
prevent_default: true,
scale_threshold: 0
});
element = $(element);
var displayWidth = container.width();
var displayHeight = container.height();
var MIN_ZOOM = 0;
var MAX_ZOOM = 1;
var scaleFactor = 1;
var previousScaleFactor = 1;
var startX = 0;
var startY = 0;
var translateX = 0;
var translateY = 0;
var previousTranslateX = 0;
var previousTranslateY = 0;
var time = 1;
var tch1 = 0,
tch2 = 0,
tcX = 0,
tcY = 0,
toX = 0,
toY = 0,
cssOrigin = "";
container.bind("transformstart", function(event){
e = event;
tch1 = [e.touches[0].x, e.touches[0].y],
tch2 = [e.touches[1].x, e.touches[1].y];
tcX = (tch1[0]+tch2[0])/2,
tcY = (tch1[1]+tch2[1])/2;
toX = tcX;
toY = tcY;
var left = $(element).offset().left;
var top = $(element).offset().top;
cssOrigin = (-(left) + toX)/scaleFactor +"px "+ (-(top) + toY)/scaleFactor +"px";
});
container.bind("transform", function(event){
scaleFactor = previousScaleFactor * event.scale;
scaleFactor = Math.max(MIN_ZOOM, Math.min(scaleFactor, MAX_ZOOM));
transform(event);
});
container.bind("transformend", function(event){
previousScaleFactor = scaleFactor;
if(scaleFactor > 0.42){
$(element).css('-webkit-transform', 'scaleY(1.0)').css('transform', 'scaleY(1.0)');
}
});
function transform(e){
var cssScale = "scaleY("+ scaleFactor +")";
element.css({
webkitTransform: cssScale,
webkitTransformOrigin: cssOrigin,
transform: cssScale,
transformOrigin: cssOrigin,
});
if(scaleFactor <= 0.42){
$(element).animate({height:0}, function(){
$(this).remove();
});
}
}
}
Wrap it as a jquery plugin:
$.fn.collapse = function(filter) {
return this.each(function(){
collapse(this,filter);
});
}
$("#zoom,#zoom1,#zoom2").collapse(".polaroid");
or if each of the zoom elements had a common class,
$(".zoomel").collapse(".polaroid");
You have to run collapse for each element.
element = $(element);
element.each(function(){
//each element would be this here
var $this= $(this);
//do whatever you want with $this
})
I need to adjust the script from http://javascript.about.com/library/blcvert.htm to change direction of scrolling to DOWN.
Could anybody help?
Of course, it would be also helpful if anybody knows/have some other script which produces the same effect.
Thanx
P.S. the script (in readable format is):
var imgAry1 = ['img1.png','img2.png'];
function startCloud() {
new mq('clouds', imgAry1, 380);
mqRotate(mqr);
}
$(document).ready(function() {
startCloud();
});
var mqr = [];
function mq(id, ary, heit) {
this.mqo=document.getElementById(id);
var wid = this.mqo.style.width;
this.mqo.onmouseout=function() { mqRotate(mqr); };
this.mqo.onmouseover=function() { clearTimeout(mqr[0].TO); };
this.mqo.ary=[];
var maxw = ary.length;
for (var i=0;i<maxw;i++) {
this.mqo.ary[i]=document.createElement('img');
this.mqo.ary[i].src=ary[i];
this.mqo.ary[i].style.position = 'absolute';
this.mqo.ary[i].style.top = (heit*i)+'px';
this.mqo.ary[i].style.height = heit+'px';
this.mqo.ary[i].style.width = wid;
this.mqo.appendChild(this.mqo.ary[i]);
}
mqr.push(this.mqo);
}
function mqRotate(mqr) {
if (!mqr) return;
for (var j=mqr.length - 1; j > -1; j--) {
maxa = mqr[j].ary.length;
for (var i=0;i<maxa;i++) {
var x = mqr[j].ary[i].style;
x.top=(parseInt(x.top,10)-1)+'px';
}
var y = mqr[j].ary[0].style;
if (parseInt(y.top,10)+parseInt(y.height,10)<0) {
var z = mqr[j].ary.shift();
z.style.top = (parseInt(z.style.top) + parseInt(z.style.height)*maxa) + 'px';
mqr[j].ary.push(z);
}
}
mqr[0].TO=setTimeout('mqRotate(mqr)',10);
}
On this line:
x.top=(parseInt(x.top,10)-1)+'px';
it says that you take x.top in pixels, parse out the number, subtract one and add the 'px' again. The element's position from top is decreased by 1 each time, so it goes up. All you need to do for it to go down is to add the one.
x.top=(parseInt(x.top,10)+1)+'px';
I also tested this hypothesis on the page you linked :)