How to calculate distance between 2 elements , Like this? - javascript

How to calculate distance between 2 elements , Like this ?
i want to calculate distance between id="element_bottom" and id="ref_box"
and this is fiddle for calculate distance between mouse and id="element_bottom"
how can i apply this code for calculate distance between id="element_bottom" and id="ref_box" ?
thankyou
http://jsfiddle.net/t5Kts/808/
(function() {
var mY, distance_bottom,
$distance_bottom = $('#distance_bottom span'),
$element_bottom = $('#element_bottom');
function calculatedistance_bottom(elem , mouseY) {
return Math.floor(Math.sqrt(Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
}
$(document).mousemove(function(e) {
mY = e.pageY;
distance_bottom = calculatedistance_bottom($element_bottom , mY);
$distance_bottom.text(distance_bottom);
});
})();

Assuming that the your references for distance are the tops of each element, You may try this:
DEMO
(function() {
var btm = $('#element_bottom'),
ref = $('#ref_box'),
refTop = ref.position().top;
$(window).scroll(function(){
var btmTop = btm.position().top;
$('#distance_bottom span').text(Math.abs(refTop-btmTop));
});
})();

Something like this should probably do it:
$('.foo').offset().top - $('.bar').offset().top

Related

Passing an array to feed svg.js's polyline array method throws an error

I'm using svg.js's polyline array method to draw lines from values logged by storing the cursor's x,y coordinates on a page.
The idea is to first let a user browsing the page and move the cursor around, and so feed values into the array, then when clicking on a button svg.js will draw lines based on the cursor' movement.
Being this the syntax to follow:
var polyline = draw.polyline([[0,0], [100,50], [50,100]]).fill('none').stroke({ width: 1 })
if I manually copy-paste the values in the array as in:
var polyline = draw.polyline([[475,76], [475,76], [489,75], (...)]]).fill('none').stroke({ width: 1 });
svg.js works as expected.
If I pass in a variable, it tells me this:
svg.js:2632 Error: <polyline> attribute points: Expected number, "NaN,528 NaN,531 …".
This is my code:
// movement
var array_cursor_movement = [];
$(document).mousemove(function(e) {
var cursor_movement = "["+ e.pageX +","+ e.pageY +"]";
array_cursor_movement.push(cursor_movement);
var cursor_movement = array_cursor_movement.join(', ');
console.log("movement:" + cursor_movement);
localStorage.setItem("cursor_movement_pos", JSON.stringify(array_cursor_movement));
});
// click for preview lines
$(".preview--lines, .close--button").click(function(){
$(".preview").toggleClass("show--hide");
// draw lines
var retrievedData = localStorage.getItem("cursor_movement_pos");
var array_cursor_movement_b = JSON.parse(retrievedData);
var cursor_movement = array_cursor_movement_b.join(', ');
cursor_movement = "["+cursor_movement+"]";
console.log("preview:" + cursor_movement);
var width = window.innerWidth;
var height = window.innerHeight;
var draw = SVG('drawing').size(width, height);
var polyline = draw.polyline(cursor_movement).fill('none').stroke({ width: 1 });
})
Anyone has experience?
Thanks,
André
As I already mentioned in the comments: Stop making Strings!! Just pass the array!
// movement
var array_cursor_movement = [];
$(document).mousemove(function(e) {
// var cursor_movement = "["+ e.pageX +","+ e.pageY +"]"; // NO - stop making strings!
var cursor_movement = [ e.pageX, e.pageY ];
array_cursor_movement.push(cursor_movement);
// var cursor_movement = array_cursor_movement.join(', '); // STOP
console.log("movement:", cursor_movement);
localStorage.setItem("cursor_movement_pos", JSON.stringify(array_cursor_movement));
});
// click for preview lines
$(".preview--lines, .close--button").click(function(){
$(".preview").toggleClass("show--hide");
// draw lines
var retrievedData = localStorage.getItem("cursor_movement_pos");
var array_cursor_movement_b = JSON.parse(retrievedData);
// var cursor_movement = array_cursor_movement_b.join(', '); // what did I say?
// cursor_movement = "["+cursor_movement+"]";
// console.log("preview:", cursor_movement);
var width = window.innerWidth;
var height = window.innerHeight;
var draw = SVG('drawing').size(width, height);
// just pass the array and not the string
var polyline = draw.polyline(array_cursor_movement_b).fill('none').stroke({ width: 1 });
})
PS: Corrected Codepen: http://codepen.io/anon/pen/dMjgdO
// EDIT: I guess I make things more clear:
As you said yourself the syntax to create a polyline is as follows:
var polyline = draw.polyline([[0,0], [100,50], [50,100]]).fill('none').stroke({ width: 1 })
But you tried to do this instead:
var polyline = draw.polyline("[[0,0], [100,50], [50,100]]").fill('none').stroke({ width: 1 })
^ you notice the quotes here?
So you did not pass an array to the function. You passed a string which looks like an array.
Note that there is another syntax to create a polyline which is:
var polyline = draw.polyline('0,0 100,50 50,100').fill('none').stroke({ width: 1 })
So you actually CAN pass a string. It just is a comma and space seperated list. But DONT do that. You already created your array. You dont need the string.

Mapbox sidepanel and polygon interaction

I am attempting to make an interaction between images in a sidepanel and polygons on a map, so when the sidepanel is moved via mousescroll, the corresponding polygon with same name is brought into focus.
My current attempt is not responsive to mousescrolls as needed. Is there another approach than the one I have taken?
$('.sidebar').bind('mousewheel', function(e){
$("#help").html(' ');
var winTop = $(this).scrollTop();
var $imgs = $('.sidebar').find('img');
var $midElement;
var distance = null;
var currDistance = 0;
var minHeight = $(window).scrollTop();
var maxHeight = $(window).height();
var img_h=$('.sidebar').find('img');
var img_h1=img_h.height() / 2;
var middleHeightA = (maxHeight + minHeight) / 2;
var middleHeight = middleHeightA - img_h1;
$.each($imgs, function() {
currDistance = Math.abs(middleHeight - $(this).position().top);
if ( distance == null || currDistance < distance ) {
/*$midElement = $(element);*/
distance = currDistance;
for (j=0;j<polygons1.length;j++) {
polygons1[j].setStyle({color: '#fff',fillColor:'#000', weight:'1px'});
}
var scrid=$(this).attr('id');
for (j=0;j<help.length;j++) {
id=help[j];
if(id==scrid)
{
polygons1[j].openPopup(polygons1[j].getBounds().getCenter());
map.setView(polygons1[j].getBounds().getCenter(),10);
polygons1[j].setStyle({color: '#e72f2a',fillColor:'#e72f2a',weight:'7px'});
$('.thumbnail').removeClass('active');
$('.'+scrid).addClass('active');
}
}
}
var scrid=$(this).attr('id');
for (j=0;j<help.length;j++) {
id=help[j];
if(id==scrid)
{
polygons1[j].openPopup(polygons1[j].getBounds().getCenter());
map.setView(polygons1[j].getBounds().getCenter(),10);
polygons1[j].setStyle({color: '#e72f2a',fillColor:'#e72f2a',weight:'7px'});
}
}
}*/
I would recommend you to use a debounce function. Debounce function limits the rate at which a function can fire. The idea is to make polygons focus not every time a mouse-wheel event is triggered, but focus them with a kind of cooldown.
Debounce functions are already implemented in many libraries, for example in lodash. All you have to do is to wrap your mousewheel callback in it. Something like:
$('.sidebar').bind('mousewheel', _.debounce(function(e){
$("#help").html(' ');
...
), 100});
Pay attention to options param, in lodash implementation, most probably you would like to use one of them, for example maxWait.

Applying function to a div by class

I thought I was doing this right but its not working. I think I'm being stupid...
function expand(){
var wide = $(this).css('width');
var high = $(this).css('height');
var newwide = wide * 10;
var newhigh = high * 10;
$(this).animate({'width':newwide,'height':newhigh}, 2000);
}
$('.object1').expand();
I just want to run this 'expand' function on the div with the class 'object1', what am I doing wrong?
Thanks
In jQuery, to add a custom function, you do it like this:
(function($){
$.fn.myFunction = function() {
//Custom Function
}
})(jQuery);
So, your code should look like this:
(function($){
$.fn.expand = function() {
var wide = $(this).css('width');
var high = $(this).css('height');
var newwide = wide * 10;
var newhigh = high * 10;
$(this).animate({'width':newwide,'height':newhigh}, 2000);
}
})(jQuery);
Learn More
Try to rewrite your code like this,
function expand($this){
var wide = $this.css('width');
var high = $this.css('height');
var newwide = wide * 10;
var newhigh = high * 10;
$this.animate({'width':newwide,'height':newhigh}, 2000);
}
expand($('.object1'));
How should the $ object know it has a expand() method now?
If you really want a jQuery plugin here (that's what they call it when you attach something to the jQuery object), you have to attach it to $.fn:
$.fn.expand = expand // as you defined it earlier
You almost surely don't want this. What creates what you were trying to achieve is giving the $('.object1') as a parameter to expand():
function expand($element){
var wide = $element.css('width');
var high = $element.css('height');
var newwide = wide * 10;
var newhigh = high * 10;
$element.animate({'width':newwide,'height':newhigh}, 2000);
}
expand($('.object1'));

Where in the grid the tile belongs

If I created a virtual grid 32x32 as a <div> example:
I want to fill one of the tile with a black box on click I have so far this:
var _proto = {
id:0,
x:0,
y:0
}
var objects = [];
$(".test").on("mousedown", function(e) {
var offset = $(this).offset();
var prex2 = 0, prey2 = 0;
prex2 = _proto.x = e.pageX-offset.left;
prey2 = _proto.y = e.pageY-offset.top;
_proto.id = (_objects.length)?_objects[_objects.length-1].id+1:0;
// Add to grid (not sure how to get proper cordinates)
$("<div style='display:absolute;width:32px;height:32px;background:black'></div>")
.css("top","")
.css("left","")
.appendTo("#maindiv");
});
I have the coordinates as prex2, and prey2 where the user clicked, but how do I know where to put it in the grid? I'm sure there a simple math equation but I can't figure it out.
Here's a snippet from a map editor that I was working on a few months back. It might help you grapple with your own code.
mapBlanket.addEventListener("mousedown", function(e) {
var sideWidth = document.getElementById("mapSide").offsetWidth;
var headHeight = document.getElementById("system").offsetHeight + 32;
var clickX = e.pageX - mapBlanket.offsetLeft - sideWidth + mapBlanket.parentNode.scrollLeft;
var clickY = e.pageY - mapBlanket.offsetTop - headHeight + mapBlanket.parentNode.scrollTop;
var tileX = clickX - (clickX % map.grid);
var tileY = clickY - (clickY % map.grid);
if (paintOn == 5) {
eventThis(tileX, tileY);
} else if (paintOn < 5) {
paintThis(tileX, tileY);
}
...
}
For reference, the map.grid was 32, same as yours. I just had a good bit defined in an object at the top of the file.

Javascript issue on resizing Divs

I kindly ask if someone can look at this c0de and tell me why it doesn't work.
It's fairly simple, I need to calculate the dive size because I want it to resize accordingly
With page width. Keeping Div1 and Div3 at a fixed size and make it dynamically for Div2.
The fiddle is here: http://jsfiddle.net/yMcXm/89/
Thanks a lot
$(document).ready(function() {
var cw = $('#container').width();
var d1 = $('#d1').width();
var d3 = $('#d3').width();
$(".d2").width(cw-d1-d3);
$(window).resize(function() {
var cw = $('#container').width();
var d1 = $('#d1').width();
var d3 = $('#d3').width();
$(".d2").width(cw-d1-d3);
});
});
You should change your JS to this (wrong selector (you use # (id) instead of . (class))).
$(document).ready(function() {
var cw = $('#container').width();
var d1 = $('.d1').width();
var d3 = $('.d3').width();
$(".d2").width(cw-d1-d3);
$(window).resize(function() {
var cw = $('#container').width();
var d1 = $('.d1').width();
var d3 = $('.d3').width();
$(".d2").width(cw-d1-d3);
});
});
You should also mind the margins and paddings $(".d2").width(cw-d1-d3-12);!
[EDIT]
Why not use a CSS solution: check your updated Fiddle

Categories

Resources