How to detect 2 overlapping div in javascript and toggle class - javascript

I mix different sources (thank's to them) to achieve what we need.
We have a div following the mouse ... it's ok ... but we need to toggle/add a class when this div overlapsing an other fixed div in the dom.
function detection(){
const animalEl = document.getElementById("animal");
const targetEl = document.getElementById("target");
const a = animalEl.getBoundingClientRect();
const b = targetEl.getBoundingClientRect();
var overlap = (
a.right == b.left || // right to left touching
a.left == b.right || // left to right touching
a.bottom == b.top || // bottom to top touching
a.top == b.bottom) // top to bottom touching
if(overlap){
console.log("overlaps");
targetEl.classList.toggle("touched");
}else{
//console.log("non");
}
}
Here is a pen
https://codepen.io/vinchoz/pen/QWdmVza
I tried with "getBoundingClientRect()" but not sure to use it the right way...
Could a javascript guru have a look at it?
Thank's

YES... I did find a solution
function detection(){
const animalEl = document.getElementById("bee");
const targetEl = document.getElementById("target");
const a = animalEl.getBoundingClientRect();
const b = targetEl.getBoundingClientRect();
/* FOR COVER
var inside = (
((b.top <= a.top) && (a.top <= b.bottom)) &&
((b.top <= a.bottom) && (a.bottom <= b.bottom)) &&
((b.left <= a.left) && (a.left <= b.right)) &&
((b.left <= a.right) && (a.right <= b.right))
)
if(inside){
targetEl.classList.toggle("inside");
}else{
}
*/
/* FOR TOUCHING */
var touched = !(
b.top > b.bottom ||
a.right < b.left ||
a.bottom < b.top ||
a.left > b.right
)
if(touched){
targetEl.classList.add("touched");
}else{
targetEl.classList.remove("touched");
}
}
https://codepen.io/vinchoz/pen/QWdmVza

Related

How to apply this function to an array without reusing all elements

I'm fairly new to programming and I'm working on a project,
HTML
<div class="textAnimation">
<span><h2 class="animatedHeader">Text1</h2></span>
<span
><h2 class="animatedHeader twoH">Text2</h2></span
>
<span
><h2 class="animatedHeader">Text3</h2></span
>
<span
><h2 class="animatedHeader">text4</h2></span
>
<span><h2 class="animatedHeader">text5</h2></span>
<span><h2 class="animatedHeader">text6</h2></span>
<span><h2 class="animatedHeader">text7</h2></span>
<span><h2 class="animatedHeader">text8</h2></span>
<span><h2 class="animatedHeader">text9</h2></span>
</div>
JavaScript
// Check if is in viewport & animate
const headers2 = document.querySelector(".twoH");
function elementInViewportTWO() {
let bounding = headers2.getBoundingClientRect();
if (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.right <=
(window.innerWidth || document.documentElement.clientWidth) &&
bounding.bottom <=
(window.innerHeight || document.documentElement.clientHeight)
) {
headers2.style.opacity = 1;
} else {
headers2.style.opacity = 0.6;
}
}
setInterval(elementInViewportTWO, 10);
My questions is, how to apply this effect, given an array of 9 headings without reusing so much code, how do I make my function work with an array of elements?
(My code highlights text when a certain element is in a viewport)
Select them all with document.querySelectorAll and loop through them each time.
// Check if is in viewport & animate
const headers = document.querySelectorAll(".animatedHeader");
function elementsInViewport() {
headers.forEach(header=>{
let bounding = header.getBoundingClientRect();
if (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.right <=
(window.innerWidth || document.documentElement.clientWidth) &&
bounding.bottom <=
(window.innerHeight || document.documentElement.clientHeight)
) {
header.style.opacity = 1;
} else {
header.style.opacity = 0.6;
}
})
}
setInterval(elementsInViewport, 10);
<div class="textAnimation">
<span><h2 class="animatedHeader">Text1</h2></span>
<span
><h2 class="animatedHeader twoH">Text2</h2></span
>
<span
><h2 class="animatedHeader">Text3</h2></span
>
<span
><h2 class="animatedHeader">text4</h2></span
>
<span><h2 class="animatedHeader">text5</h2></span>
<span><h2 class="animatedHeader">text6</h2></span>
<span><h2 class="animatedHeader">text7</h2></span>
<span><h2 class="animatedHeader">text8</h2></span>
<span><h2 class="animatedHeader">text9</h2></span>
</div>
The function you've provided evaluates the dimensions of each .animatedHeader element every 10 milliseconds. This will make your CPU work very hard and has a high chance of hurting your site's peformance. And because of setInterval it will keep on running even if you're not interacting with the site and nothing changes.
Instead, consider using the Intersection Observer API which is specifically designed to detect if elements are within a viewport whilst keeping the performance high.
const headers = document.querySelectorAll('.animatedHeader');
const intersectionCallback = entries => {
for (const { isIntersecting, target } of entries) {
if (isIntersecting) {
target.style.opacity = 1;
} else {
target.style.opacity = 0.6;
}
}
};
const observer = new IntersectionObserver(intersectionCallback);
for (const header of headers) {
observer.observe(header);
}

How to check element if outside the viewport when transform scale

I know getBoundingClientRect() gets the bounds in view but I found out this won't work if the view got transform scale. Any solution on your part.
var bounding = elem.getBoundingClientRect();
// Check if it's out of the viewport on each side
var out = {};
out.top = bounding.top >= 0;
out.left = bounding.left >= 0;
out.bottom = (bounding.bottom) > ((window.innerHeight) || (document.documentElement.clientHeight));
out.right = (bounding.right) > ((window.innerWidth) || (document.documentElement.clientWidth));
Please drag the square, it got transform scale and rotate on.
$.fn.isOnScreen = function(partial){
//let's be sure we're checking only one element (in case function is called on set)
var t = $(this).first();
//we're using getBoundingClientRect to get position of element relative to viewport
//so we dont need to care about scroll position
var box = t[0].getBoundingClientRect();
//let's save window size
var win = {
h : $(window).height(),
w : $(window).width()
};
//now we check against edges of element
//firstly we check one axis
//for example we check if left edge of element is between left and right edge of scree (still might be above/below)
var topEdgeInRange = box.top >= 0 && box.top <= win.h;
var bottomEdgeInRange = box.bottom >= 0 && box.bottom <= win.h;
var leftEdgeInRange = box.left >= 0 && box.left <= win.w;
var rightEdgeInRange = box.right >= 0 && box.right <= win.w;
//here we check if element is bigger then window and 'covers' the screen in given axis
var coverScreenHorizontally = box.left <= 0 && box.right >= win.w;
var coverScreenVertically = box.top <= 0 && box.bottom >= win.h;
//now we check 2nd axis
var topEdgeInScreen = topEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
var bottomEdgeInScreen = bottomEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
var leftEdgeInScreen = leftEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
var rightEdgeInScreen = rightEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
//now knowing presence of each edge on screen, we check if element is partially or entirely present on screen
var isPartiallyOnScreen = topEdgeInScreen || bottomEdgeInScreen || leftEdgeInScreen || rightEdgeInScreen;
var isEntirelyOnScreen = topEdgeInScreen && bottomEdgeInScreen && leftEdgeInScreen && rightEdgeInScreen;
return partial ? isPartiallyOnScreen : isEntirelyOnScreen;
};
$.expr.filters.onscreen = function(elem) {
return $(elem).isOnScreen(true);
};
$.expr.filters.entireonscreen = function(elem) {
return $(elem).isOnScreen(true);
};
$(function(){
$('#circle1').draggable({ drag: function() {
if ($("#circle1").isOnScreen()) $('.indicator').html('yes its on screen');
else $('.indicator').html('its off screen');
},});
});
.circle{
width: 50px;
height: 50px;
background-color: red;
top: 50%;
left: 50%;
}
.circle.big{
transform: scale(2,2) rotate(20deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<div class="circle big" id="circle1">drag me</div>
<div class="indicator"></div>
Press to enlarge

horizontal timeline fixed distance and centered on mobile devices

I am trying to reach a horizontal timeline like this:
https://codepen.io/ritz078/pen/LGRWjE
My problem is, that I've got no real dates (DD/MM/YYYY) but only years like 1998-2002 or just 2009. So there is a problem, I am struggling to fix, which ends up like this:
So my aims are:
Set a fixed distance between elements
Make it work just with years
When on a device less than 768px wide ensure a single element is displayed and it appears in the center
This is my solution for 3., but the other things, I couldnt solute:
if ($(window).width() < 768 {
eventsMinDistance = $('.cd-horizontal-timeline .events-wrapper').width(/2;)
}
(timelines.length > 0) && initTimeline(timelines);
$(window).resize(function(){
if ($(window).width() < 768 {
eventsMinDistance = $('.cd-horizontal-timeline .events-wrapper').width(/2;)
} else{
eventsMinDistance = 155;
}
}
Do you guys know how do adjust it, as I am struggling since hours without any success. Thank you very much for your help!
the first part of your code works fine, but it was faulty on the syntax, I fixed it and use it and also add a couple of changes to acomplished the desired fixed width amount between each date.
Actually it was pretty easy, when you debug and you know exactly what the developer wants to do.
This is the code I wrote:
jQuery(document).ready(function($){
var timelines = $('.cd-horizontal-timeline'),
eventsRelativeDistance = false;
if ($(window).width() < 768) {
eventsMinDistance = Number($('.cd-horizontal-timeline .events-wrapper').width())/2;
}else{
var eventsMinDistance = 100;
}
(timelines.length > 0) && initTimeline(timelines);
$(window).resize( function(){
if ($(window).width() < 768) {
eventsMinDistance = Number($('.cd-horizontal-timeline .events-wrapper').width())/2;
} else{
eventsMinDistance = 100;
}
});
function initTimeline(timelines) {
timelines.each(function(){
var timeline = $(this),
timelineComponents = {};
//cache timeline components
timelineComponents['timelineWrapper'] = timeline.find('.events-wrapper');
timelineComponents['eventsWrapper'] = timelineComponents['timelineWrapper'].children('.events');
timelineComponents['fillingLine'] = timelineComponents['eventsWrapper'].children('.filling-line');
timelineComponents['timelineEvents'] = timelineComponents['eventsWrapper'].find('a');
timelineComponents['timelineDates'] = parseDate(timelineComponents['timelineEvents']);
timelineComponents['eventsMinLapse'] = minLapse(timelineComponents['timelineDates']);
timelineComponents['timelineNavigation'] = timeline.find('.cd-timeline-navigation');
timelineComponents['eventsContent'] = timeline.children('.events-content');
if(!eventsRelativeDistance){
// Set up space to store the distance in pixels.
timelineComponents['distanceInPx'] = [];
}
//assign a left postion to the single events along the timeline
setDatePosition(timelineComponents, eventsMinDistance, eventsRelativeDistance);
//assign a width to the timeline
var timelineTotWidth = setTimelineWidth(timelineComponents, eventsMinDistance, eventsRelativeDistance);
//the timeline has been initialize - show it
timeline.addClass('loaded');
//detect click on the next arrow
timelineComponents['timelineNavigation'].on('click', '.next', function(event){
event.preventDefault();
updateSlide(timelineComponents, timelineTotWidth, 'next');
});
//detect click on the prev arrow
timelineComponents['timelineNavigation'].on('click', '.prev', function(event){
event.preventDefault();
updateSlide(timelineComponents, timelineTotWidth, 'prev');
});
//detect click on the a single gallery - show new gallery content
timelineComponents['eventsWrapper'].on('click', 'a', function(event){
event.preventDefault();
timelineComponents['timelineEvents'].removeClass('selected');
$(this).addClass('selected');
updateOlderEvents($(this));
updateFilling($(this), timelineComponents['fillingLine'], timelineTotWidth);
updateVisibleContent($(this), timelineComponents['eventsContent']);
});
//on swipe, show next/prev gallery content
timelineComponents['eventsContent'].on('swipeleft', function(){
var mq = checkMQ();
( mq == 'mobile' ) && showNewContent(timelineComponents, timelineTotWidth, 'next');
});
timelineComponents['eventsContent'].on('swiperight', function(){
var mq = checkMQ();
( mq == 'mobile' ) && showNewContent(timelineComponents, timelineTotWidth, 'prev');
});
//keyboard navigation
$(document).keyup(function(event){
if(event.which=='37' && elementInViewport(timeline.get(0)) ) {
showNewContent(timelineComponents, timelineTotWidth, 'prev');
} else if( event.which=='39' && elementInViewport(timeline.get(0))) {
showNewContent(timelineComponents, timelineTotWidth, 'next');
}
});
});
}
function updateSlide(timelineComponents, timelineTotWidth, string) {
//retrieve translateX value of timelineComponents['eventsWrapper']
var translateValue = getTranslateValue(timelineComponents['eventsWrapper']),
wrapperWidth = Number(timelineComponents['timelineWrapper'].css('width').replace('px', ''));
//translate the timeline to the left('next')/right('prev')
(string == 'next')
? translateTimeline(timelineComponents, translateValue - wrapperWidth + eventsMinDistance, wrapperWidth - timelineTotWidth)
: translateTimeline(timelineComponents, translateValue + wrapperWidth - eventsMinDistance);
}
function showNewContent(timelineComponents, timelineTotWidth, string) {
//go from one gallery to the next/previous one
var visibleContent = timelineComponents['eventsContent'].find('.selected'),
newContent = ( string == 'next' ) ? visibleContent.next() : visibleContent.prev();
if ( newContent.length > 0 ) { //if there's a next/prev gallery - show it
var selectedDate = timelineComponents['eventsWrapper'].find('.selected'),
newEvent = ( string == 'next' ) ? selectedDate.parent('li').next('li').children('a') : selectedDate.parent('li').prev('li').children('a');
updateFilling(newEvent, timelineComponents['fillingLine'], timelineTotWidth);
updateVisibleContent(newEvent, timelineComponents['eventsContent']);
newEvent.addClass('selected');
selectedDate.removeClass('selected');
updateOlderEvents(newEvent);
updateTimelinePosition(string, newEvent, timelineComponents);
}
}
function updateTimelinePosition(string, event, timelineComponents) {
//translate timeline to the left/right according to the position of the selected gallery
var eventStyle = window.getComputedStyle(event.get(0), null),
eventLeft = Number(eventStyle.getPropertyValue("left").replace('px', '')),
timelineWidth = Number(timelineComponents['timelineWrapper'].css('width').replace('px', '')),
timelineTotWidth = Number(timelineComponents['eventsWrapper'].css('width').replace('px', ''));
var timelineTranslate = getTranslateValue(timelineComponents['eventsWrapper']);
if( (string == 'next' && eventLeft > timelineWidth - timelineTranslate) || (string == 'prev' && eventLeft < - timelineTranslate) ) {
translateTimeline(timelineComponents, - eventLeft + timelineWidth/2, timelineWidth - timelineTotWidth);
}
}
function translateTimeline(timelineComponents, value, totWidth) {
var eventsWrapper = timelineComponents['eventsWrapper'].get(0);
value = (value > 0) ? 0 : value; //only negative translate value
value = ( !(typeof totWidth === 'undefined') && value < totWidth ) ? totWidth : value; //do not translate more than timeline width
setTransformValue(eventsWrapper, 'translateX', value+'px');
//update navigation arrows visibility
(value == 0 ) ? timelineComponents['timelineNavigation'].find('.prev').addClass('inactive') : timelineComponents['timelineNavigation'].find('.prev').removeClass('inactive');
(value == totWidth ) ? timelineComponents['timelineNavigation'].find('.next').addClass('inactive') : timelineComponents['timelineNavigation'].find('.next').removeClass('inactive');
}
function updateFilling(selectedEvent, filling, totWidth) {
//change .filling-line length according to the selected gallery
var eventStyle = window.getComputedStyle(selectedEvent.get(0), null),
eventLeft = eventStyle.getPropertyValue("left"),
eventWidth = eventStyle.getPropertyValue("width");
eventLeft = Number(eventLeft.replace('px', '')) + Number(eventWidth.replace('px', ''))/2;
var scaleValue = eventLeft/totWidth;
setTransformValue(filling.get(0), 'scaleX', scaleValue);
}
function setDatePosition(timelineComponents, min, relativeDistance) {
var distance,
distanceNorm = 0,
distancesInPx =[];
for (i = 0; i < timelineComponents['timelineDates'].length; i++) {
if (relativeDistance){
distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]);
distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
}else{
distance = 5;
distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2 + distanceNorm;
// Save am array of sizes to track the distance in pixels from the left.
timelineComponents['distanceInPx'].push(distanceNorm*min);
}
timelineComponents['timelineEvents'].eq(i).css('left', distanceNorm*min+'px');
}
}
function setTimelineWidth(timelineComponents, width, relativeDistance) {
var timeSpan = 0, timeSpanNorm, totalWidth;
if(relativeDistance){
// If relative Time Distance daydiff caclulates the first date and the last one.
timeSpan = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][timelineComponents['timelineDates'].length-1]);
timeSpanNorm = timeSpan/timelineComponents['eventsMinLapse'];
timeSpanNorm = Math.round(timeSpanNorm) + 4;
totalWidth = timeSpanNorm*width;
}else{
// However if no relative Distance we obtain the amount of distance in pixels from the last position of the array which is the farthest element on the array.
totalWidth = timelineComponents['distanceInPx'][timelineComponents['distanceInPx'].length-1];
}
timelineComponents['eventsWrapper'].css('width', totalWidth+'px');
updateFilling(timelineComponents['eventsWrapper'].find('a.selected'), timelineComponents['fillingLine'], totalWidth);
updateTimelinePosition('next', timelineComponents['eventsWrapper'].find('a.selected'), timelineComponents);
return totalWidth;
}
function updateVisibleContent(event, eventsContent) {
var eventDate = event.data('date'),
visibleContent = eventsContent.find('.selected'),
selectedContent = eventsContent.find('[data-date="'+ eventDate +'"]'),
selectedContentHeight = selectedContent.height();
if (selectedContent.index() > visibleContent.index()) {
var classEnetering = 'selected enter-right',
classLeaving = 'leave-left';
} else {
var classEnetering = 'selected enter-left',
classLeaving = 'leave-right';
}
selectedContent.attr('class', classEnetering);
visibleContent.attr('class', classLeaving).one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(){
visibleContent.removeClass('leave-right leave-left');
selectedContent.removeClass('enter-left enter-right');
});
eventsContent.css('height', selectedContentHeight+'px');
}
function updateOlderEvents(event) {
event.parent('li').prevAll('li').children('a').addClass('older-gallery').end().end().nextAll('li').children('a').removeClass('older-gallery');
}
function getTranslateValue(timeline) {
var timelineStyle = window.getComputedStyle(timeline.get(0), null),
timelineTranslate = timelineStyle.getPropertyValue("-webkit-transform") ||
timelineStyle.getPropertyValue("-moz-transform") ||
timelineStyle.getPropertyValue("-ms-transform") ||
timelineStyle.getPropertyValue("-o-transform") ||
timelineStyle.getPropertyValue("transform");
if( timelineTranslate.indexOf('(') >=0 ) {
var timelineTranslate = timelineTranslate.split('(')[1];
timelineTranslate = timelineTranslate.split(')')[0];
timelineTranslate = timelineTranslate.split(',');
var translateValue = timelineTranslate[4];
} else {
var translateValue = 0;
}
return Number(translateValue);
}
function setTransformValue(element, property, value) {
element.style["-webkit-transform"] = property+"("+value+")";
element.style["-moz-transform"] = property+"("+value+")";
element.style["-ms-transform"] = property+"("+value+")";
element.style["-o-transform"] = property+"("+value+")";
element.style["transform"] = property+"("+value+")";
}
//based on http://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript
function parseDate(events) {
var dateArrays = [];
events.each(function(){
var singleDate = $(this),
dateComp = singleDate.data('date').split('T');
if( dateComp.length > 1 ) { //both DD/MM/YEAR and time are provided
var dayComp = dateComp[0].split('/'),
timeComp = dateComp[1].split(':');
} else if( dateComp[0].indexOf(':') >=0 ) { //only time is provide
var dayComp = ["2000", "0", "0"],
timeComp = dateComp[0].split(':');
} else { //only DD/MM/YEAR
var dayComp = dateComp[0].split('/'),
timeComp = ["0", "0"];
}
var newDate = new Date(dayComp[2], dayComp[1]-1, dayComp[0], timeComp[0], timeComp[1]);
dateArrays.push(newDate);
});
return dateArrays;
}
function daydiff(first, second) {
return Math.round((second-first));
}
function minLapse(dates) {
//determine the minimum distance among events
var dateDistances = [];
for (i = 1; i < dates.length; i++) {
var distance = daydiff(dates[i-1], dates[i]);
dateDistances.push(distance);
}
return Math.min.apply(null, dateDistances);
}
/*
How to tell if a DOM element is visible in the current viewport?
http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
*/
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
function checkMQ() {
//check if mobile or desktop device
return window.getComputedStyle(document.querySelector('.cd-horizontal-timeline'), '::before').getPropertyValue('content').replace(/'/g, "").replace(/"/g, "");
}
});
Did you ever get this to work?? Have come across the same problem. If i change the default distance from 60 to 1 the gap between is not enough and the whole timeline breaks. The calculations for the distance as described in the article is as follows
First of all, in the main.js file, we set a minimum distance between two consecutive dates, using the eventsMinDistance variable; in our case, we set eventsMinDistance = 60 (so the minimum distance will be 60px). Then we evaluate all the differences between a date and the following one; to do that we use the data-date attribute added to each date. The minimum difference is then used as a reference to evaluate the distances between two consecutive dates.
For example, let's suppose the minimum found difference is 5 days; that means that the distance, along the timeline, between two dates separated by a lapse of 5days will be 60px, while the one between two events separated by a lapse of 10 days will be 120px.
source:: www.codyhouse.org
From what i read the min distance is here:~
var timelines = $('.cd-horizontal-timeline'),
eventsMinDistance = 60;
(timelines.length > 0) && initTimeline(timelines);
This creates a variable called timelines and sets it to the class .cd-hor... and sets the min distance to 60px. changing this to 1 breaks the application as the distance between the times are too small.
function setDatePosition(timelineComponents, min) {
for (i = 0; i < timelineComponents['timelineDates'].length; i++) {
var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
timelineComponents['timelineEvents'].eq(i).css('left', distanceNorm*min+'px');
}
}
I might be wrong but here is the section calculating the distance and the last distanceNorm*min+'px'. min i believe is 60 and distance norm is the calculation of the 5 days etc. if you remove distance norm the app breaks so you cant just add min+'px' this is because you remove the original distance.
All distances are calculated from the first timeline. Thats why the app breaks. Need to find the code that tells which to calc from which is the
var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
this sets distance as the first element of the index and then for each timelineDates within the loop [i].
I've been at it for days but have come to the conclusion the tutorial is good as is but it is not a library and should be used as reference to write your own from scratch which is what i am now doing.
If you did ever manage it though please update as so far i managed to manipulate the dates to get equal spacing but if you insert too many it breaks which is no good hence the rewrite!

Dont scroll the body when mouse is over child element

I'm trying to stop my main page from scrolling when the user hits the bottom of two specific sections of a page using the following code, but it's stopping the mouse wheel from working over those divs at all.
var scroller = document.querySelector('#Filters');
scroller.addEventListener('wheel', listener);
function listener(event)
{
var elem = event.currentTarget;
if ((event.deltaY < 0 && elem.scrollTop === 0) ||
(event.deltaY > 0 && elem.offsetHeight + elem.scrollTop >= elem.scrollHeight))
{
event.preventDefault();
}
else if ((event.deltaX < 0 && elem.scrollLeft === 0) ||
(event.deltaX > 0 && elem.offsetWidth + elem.scrollLeft >= elem.scrollWidth))
{
event.preventDefault();
}
}
You can use a more efficient solution than recalculating the scroll in js, disabling the body scrolling when scrolling the child element.
HTML:
<div onmouseover="disableScroll();" onmouseout="enableScroll();">
content
</div>
JS:
var body = document.getElementsByTagName('body')[0];
function enableScroll() {
body.style.overflowY = 'auto';
}
function disableScroll() {
body.style.overflowY = 'hidden';
}

How to use jquery swipe without any library?

I need to create jQuery mobile like Swipe gestures $("#slider ul li div").swipeleft(); using core jQuery without using any library or plugins not even jQuery mobile.
I know that jQuery mobile widgets are now going to be decoupled, so that we can take swipe alone from it. But I can't wait for that long.
I need some manual jQuery code similar to swipe gestures for swipe left and right functions.
I've seen this, but i couldn't understand how to get swipe gestures from it.
Can anyone help me out on that code?
This is the code for touch swipe using javascript. Finally I found it hard by searching all over the internet. Thanks to padilicious.Below is the HTML code for slider.
<div id="slider" ontouchstart="touchStart(event,'slider');" ontouchend="touchEnd(event);"
ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);">
<ul id="slideul"><li><img src="1.jpg"></li><li>....</ul>
</div>
Below is the javascript code for the touch swipe. It's bit long. But it works for me. You don't have to change anything. Only place you have to change is processingRoutine() function. I've called 2 slide function i.e previous & next using this code sliders.goToNext() & sliders.goToPrev(). You can modify as you want..
var triggerElementID = null; // this variable is used to identity the triggering element
var fingerCount = 0;
var startX = 0;
var startY = 0;
var curX = 0;
var curY = 0;
var deltaX = 0;
var deltaY = 0;
var horzDiff = 0;
var vertDiff = 0;
var minLength = 72; // the shortest distance the user may swipe
var swipeLength = 0;
var swipeAngle = null;
var swipeDirection = null;
// The 4 Touch Event Handlers
// NOTE: the touchStart handler should also receive the ID of the triggering element
// make sure its ID is passed in the event call placed in the element declaration, like:
// <div id="picture-frame" ontouchstart="touchStart(event,'picture-frame');" ontouchend="touchEnd(event);" ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);">
function touchStart(event,passedName) {
// disable the standard ability to select the touched object
event.preventDefault();
// get the total number of fingers touching the screen
fingerCount = event.touches.length;
// since we're looking for a swipe (single finger) and not a gesture (multiple fingers),
// check that only one finger was used
if ( fingerCount == 1 ) {
// get the coordinates of the touch
startX = event.touches[0].pageX;
startY = event.touches[0].pageY;
// store the triggering element ID
triggerElementID = passedName;
} else {
// more than one finger touched so cancel
touchCancel(event);
}
}
function touchMove(event) {
event.preventDefault();
if ( event.touches.length == 1 ) {
curX = event.touches[0].pageX;
curY = event.touches[0].pageY;
} else {
touchCancel(event);
}
}
function touchEnd(event) {
event.preventDefault();
// check to see if more than one finger was used and that there is an ending coordinate
if ( fingerCount == 1 && curX != 0 ) {
// use the Distance Formula to determine the length of the swipe
swipeLength = Math.round(Math.sqrt(Math.pow(curX - startX,2) + Math.pow(curY - startY,2)));
// if the user swiped more than the minimum length, perform the appropriate action
if ( swipeLength >= minLength ) {
caluculateAngle();
determineSwipeDirection();
processingRoutine();
touchCancel(event); // reset the variables
} else {
touchCancel(event);
}
} else {
touchCancel(event);
}
}
function touchCancel(event) {
// reset the variables back to default values
fingerCount = 0;
startX = 0;
startY = 0;
curX = 0;
curY = 0;
deltaX = 0;
deltaY = 0;
horzDiff = 0;
vertDiff = 0;
swipeLength = 0;
swipeAngle = null;
swipeDirection = null;
triggerElementID = null;
}
function caluculateAngle() {
var X = startX-curX;
var Y = curY-startY;
var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
var r = Math.atan2(Y,X); //angle in radians (Cartesian system)
swipeAngle = Math.round(r*180/Math.PI); //angle in degrees
if ( swipeAngle < 0 ) { swipeAngle = 360 - Math.abs(swipeAngle); }
}
function determineSwipeDirection() {
if ( (swipeAngle <= 45) && (swipeAngle >= 0) ) {
swipeDirection = 'left';
} else if ( (swipeAngle <= 360) && (swipeAngle >= 315) ) {
swipeDirection = 'left';
} else if ( (swipeAngle >= 135) && (swipeAngle <= 225) ) {
swipeDirection = 'right';
} else if ( (swipeAngle > 45) && (swipeAngle < 135) ) {
swipeDirection = 'down';
} else {
swipeDirection = 'up';
}
}
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
sliders.goToNext();
} else if ( swipeDirection == 'right' ) {
sliders.goToPrev();
} else if ( swipeDirection == 'up' ) {
sliders.goToPrev();
} else if ( swipeDirection == 'down' ) {
sliders.goToNext();
}
}

Categories

Resources