Drag event with Hammer.js - javascript

Here is my js where i already did a swipeleft and swiperight events in order to show a toolbar on the left. (it is for a smartphone app, with touch events)
I wanted to add the drag event on it, to keep control on the bar (like on menu bar of Facebook, Tinder..
Do you know how i can do it ?
$(function(){
var page = document.getElementById("page");
var sidebar = 0;
Hammer(page).on("swipeleft", function(e) {
if (!sidebar){
return true;
}
$(page).animate({left: "-=300"}, 500);
sidebar = 0;
});
Hammer(page).on("swiperight", function(e) {
if (sidebar){
return true;
}
$(page).animate({left: "+=300"}, 500) ;
sidebar=1;
});
})
I already tried this but it doesn't recognize drag and e.gesture.direction...
Hammer(page).on("drag", function(e) {
if ( e.gesture.direction === "right" && !sidebar){
$(page).animate({left : e.gesture.deltaX + "px"}, 0);
}
});

The event is called pan not drag. See the docs.
Hammer(page).on("panright", function(e) {
if (!sidebar){
$(page).animate({left : e.gesture.deltaX + "px"}, 0);
}
});

Ok, I found it! You were right, #Cristy :)
Here is the working answer:
$(function(){
var page = document.getElementById("page");
var sidebar = 0;
Hammer(page).on("swipeleft", function(e) {
if (!sidebar){
return true;
}
$(page).animate({left: "-=300"}, 500);
sidebar = 0;
});
Hammer(page).on("panleft", function(e) {
if (!sidebar){
$(page).animate({left : e.deltaX + "px"}, 0);
}
});
Hammer(page).on("swiperight", function(e) {
if (sidebar){
return true;
}
$(page).animate({left: "+=300"}, 500) ;
sidebar=1;
});
Hammer(page).on("panright", function(e) {
if (!sidebar){
$(page).animate({left : e.deltaX + "px"}, 0);
}
});
})

Related

how to drop one element from one div to another

I have the following div
<div class="npwfu-inspiration">
<div class="npwfu-inspiration-inner">
<h1>Looking for inspiration?</h1>
<p>Pick a category to see examples of what you can create with Spark.</p>
<ul class="inspiration-category-list"></ul>
</div>
</div>
<div class="div2"></div>
I need to take out the inspiration-category-list list ul and drop it into another div with a CSS transition. So it slides down and locks to position 80px from the top in div2.
How can I do this using JQUERY?
why you do not use drag effect instead of css transition?
if you would like you can add draggable effect to every element that you want to move it
you can use dragable.js from link below
then in javascript code you should set $(".inspiration-category-list").draggable ()
then instead of using css transition just drag it and drop it in any div element
/*--------------------------------------------------------------
Draggable
alternative to jQuery UI’s draggable
based on comments from: http://css-tricks.com/snippets/jquery/draggable-without-jquery-ui/
usage example: $('.post-thumbnail, article header').draggable();
--------------------------------------------------------------*/
(function ($) {
if (!jQuery().draggable) {
$.fn.draggable = function () {
var _fixMobileEvent = function (e) {
if (e.originalEvent && e.originalEvent.targetTouches && e.originalEvent.targetTouches[0]) {
var t = e.originalEvent.targetTouches[0];
e.pageX = t.clientX;
e.pageY = t.clientY;
return true;
} else {
return false;
}
};
this
.css('cursor', 'move')
.on('mousedown touchstart', function (e) {
_fixMobileEvent(e);
var $dragged = $(this);
var startOffset = $dragged.offset();
var x = startOffset.left - e.pageX,
y = startOffset.top - e.pageY,
z = $dragged.css('z-index');
if (!$.fn.draggable.stack) {
$.fn.draggable.stack = 999;
}
stack = $.fn.draggable.stack;
var firstMove = true;
var $preventClick = null;
$(window)
.on('mousemove.draggable touchmove.draggable', function (e) {
_fixMobileEvent(e);
//$("#log").text("x: " + e.pageX + "; y: " + e.pageY);
if (firstMove) {
firstMove = false;
$dragged
.css({
'z-index': stack, 'transform': 'scale(1.1)', 'transition': 'transform .3s',
'bottom': 'auto', 'right': 'auto'
});
/*.find('a').one('click.draggable', function(e) {
e.preventDefault();
e.stopImmediatePropagation();
$("#log").text("link: click prevented " + stack);
});*/
var $target = $(e.target);
if ($target.is('a')) {
$preventClick = $target;
$target.one('click.draggable', function (e) {
e.preventDefault();
e.stopImmediatePropagation();
//$("#log").text("link: click prevented " + stack);
});
} else if ($dragged.is('a')) {
$preventClick = $dragged;
$dragged.one('click.draggable', function (e) {
e.preventDefault();
e.stopImmediatePropagation();
//$("#log").text("dragged: click prevented " + stack);
});
}
}
$dragged.offset({
left: x + e.pageX,
top: y + e.pageY
});
e.preventDefault();
})
.one('mouseup touchend touchcancel', function () {
$(this).off('mousemove.draggable touchmove.draggable');
$dragged.css({ 'z-index': z, 'transform': 'scale(1)' })
$.fn.draggable.stack++;
if (_fixMobileEvent(e)) {
if ($preventClick) $preventClick.off('click.draggable');
var endOffset = $dragged.offset();
//$("#log").text("left :" + startOffset.left + "; top: " + startOffset.top
// + "; newLeft: " + endOffset.left + "; newTop: " + endOffset.top);
if (Math.abs(endOffset.left - startOffset.left) <= 3
&& Math.abs(endOffset.top - startOffset.top) <= 3) {
if ($preventClick) {
$preventClick[0].click();
} else {
var $target = $(e.target);
if ($target.is('a')) {
e.target.click();
} else if ($dragged.is('a')) {
$dragged[0].click();
}
}
}
}
});
e.preventDefault();
});
return this;
};
}
})(jQuery);

Vertical Scrolling Issues on Mobile

So I'm having scrolling issues on my site when viewing on mobile browsers. For some reason, scrolling is sometimes stopped or frozen and there is a weird vertical scrolling bar line that appears randomly in the middle of the browser. I have no idea what this could be, I figure it's a js issue between the menu and the project container but not sure if it may be css overflow issue. The link is johnavent.net/projects if you want to view yourself.
Here's my JS for the menu:
var isLateralNavAnimating = false;
//open/close lateral navigation
$('.cd-nav-trigger').on('click', function(event){
event.preventDefault();
//stop if nav animation is running
if( !isLateralNavAnimating ) {
if($(this).parents('.csstransitions').length > 0 ) isLateralNavAnimating = true;
$('body').toggleClass('navigation-is-open');
$('.cd-navigation-wrapper').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
//animation is over
isLateralNavAnimating = false;
});
}
});
And here it is for my project contianers:
$('.cd-single-project').bgLoaded({
afterLoaded : function(){
showCaption($('.projects-container li').eq(0));
}
});
$('.cd-single-project').on('click', function(){
var selectedProject = $(this),
toggle = !selectedProject.hasClass('is-full-width');
if(toggle) toggleProject($(this), $('.projects-container'), toggle);
});
$('.projects-container .cd-close').on('click', function(){
toggleProject($('.is-full-width'), $('.projects-container'), false);
});
$('.projects-container .cd-scroll').on('click', function(){
$('.projects-container').animate({'scrollTop':$(window).height()}, 500);
});
$('.projects-container').on('scroll', function(){
window.requestAnimationFrame(changeOpacity);
});
function toggleProject(project, container, bool) {
if(bool) {
container.addClass('project-is-open');
project.addClass('is-full-width').siblings('li').removeClass('is-loaded');
} else {
var mq = window.getComputedStyle(document.querySelector('.projects-container'), '::before').getPropertyValue('content').replace(/"/g, "").replace(/'/g, ""),
delay = ( mq == 'mobile' ) ? 100 : 0;
container.removeClass('project-is-open');
project.animate({opacity: 0}, 800, function(){
project.removeClass('is-loaded');
$('.projects-container').find('.cd-scroll').attr('style', '');
setTimeout(function(){
project.attr('style', '').removeClass('is-full-width').find('.cd-title').attr('style', '');
}, delay);
setTimeout(function(){
showCaption($('.projects-container li').eq(0));
}, 300);
});
}
}
function changeOpacity(){
var newOpacity = 1- ($('.projects-container').scrollTop())/300;
$('.projects-container .cd-scroll').css('opacity', newOpacity);
$('.is-full-width .cd-title').css('opacity', newOpacity);
$('.is-full-width').hide().show(0);
}
function showCaption(project) {
if(project.length > 0 ) {
setTimeout(function(){
project.addClass('is-loaded');
showCaption(project.next());
}, 150);
}
}
});
(function($){
$.fn.bgLoaded = function(custom) {
var self = this;
var defaults = {
afterLoaded : function(){
this.addClass('bg-loaded');
}
};
var settings = $.extend({}, defaults, custom);
self.each(function(){
var $this = $(this),
bgImgs = window.getComputedStyle($this.get(0), '::before').getPropertyValue('content').replace(/'/g, "").replace(/"/g, "").split(', ');
$this.data('loaded-count',0);
$.each( bgImgs, function(key, value){
var img = value.replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
$('<img/>').attr('src', img).load(function() {
$(this).remove();
$this.data('loaded-count',$this.data('loaded-count')+1);
if ($this.data('loaded-count') >= bgImgs.length) {
settings.afterLoaded.call($this);
}
});
});
});
};
Will post CSS if the issue does not lie within the JS but everything is what you would think and how it behaves on desktop.

Animation ( bar fills up over time ) with Jquery (Suggestion)

I would like to replicate the same functionality as at ign.com, where the indicator bar fills up over time. I got it working but I got some sync issues after a while. So i'm open to suggestions to do it from scratch (I'm beginner with all this animation stuff).
This is the code.
function GoProgressBar() {
var $lineStatus = $('.featured-articles-line-status');
$lineStatus.css('width', '0px');
$lineStatus.animate({ width: '694px' }, 12000, 'linear', GoProgressBar);
};
function GoOverlay(width, isLast, currentWidth) {
var $overlayLine = $('.status-overlay');
if (isLast) {
$overlayLine.css('width', '0px');
return;
}
if (currentWidth) {
$overlayLine.css('width', currentWidth);
$overlayLine.animate({ width: width }, 700);
} else {
$overlayLine.css('width', '0px');
$overlayLine.animate({ width: width }, 700);
}
};
function ShowNextElement() {
var $elements = $('.element'),
$overlayLine = $('.status-overlay'),
$liElements = $('#elements li'),
width;
if (currentElement === elements[elements.length - 1]) {
currentWidth = $overlayLine.width() + 'px',
width = currentWidth + $($liElements[(elements.length - 1)]).outerWidth() + 'px';
GoOverlay(width, true, currentWidth);
currentElement = elements[0];
$elements.hide();
$(currentElement).fadeIn(1000);
return;
}
i = elements.indexOf(currentElement) + 1;
var currentTab = $liElements[(i - 1)],
currentWidth = $overlayLine.width();
if (currentWidth) {
width = currentWidth + $(currentTab).outerWidth() + 'px';
GoOverlay(width, false, currentWidth);
} else {
width = $(currentTab).outerWidth() + 'px';
GoOverlay(width, false, false);
}
currentElement = elements[i];
$elements.hide();
$(currentElement).fadeIn(1000);
}
Thanks!
http://jqueryui.com/progressbar/
You could try this..
There are more features in addition to this,check it out.
Might come useful :)
There are a wealth of ways in which you could do this.
You should have some kind of controller to manage the show and hide.
var Application = {
show : function() {
jQuery('.application-overlay').stop().animate({ top: 40 }, 500);
jQuery('.cf-ribbon').stop().animate({height: 1000},500);
},
hide : function() {
jQuery('.application-overlay').stop().animate({ top: -1200 }, 500);
jQuery('.cf-ribbon').stop().animate({height: 200},500);
}
};
Then you have your triggers : Application.show();
jQuery(document).ready(function() {
jQuery('.cf-speakers .span2 a').hover(function() {
jQuery('span',this).stop().animate({ opacity: 1.0 },100);
}, function() {
jQuery('span',this).stop().animate({ opacity: 0.0 },100);
});;
jQuery('.apply-now').click(function(e) {
Application.show();
e.stopPropagation();
e.preventDefault();
});
jQuery('body').click(function(e) {
var application = jQuery('.application-overlay');
if( application.has(e.target).length === 0)
Application.hide();
});
jQuery('.gallery a').click(function(e) {
var src = jQuery(this).attr('href');
jQuery('.main-container img').hide().attr('src', src).fadeIn('fast');
jQuery('.gallery a').each(function() {
jQuery(this).removeClass('active');
});
jQuery(this).addClass('active');
e.stopPropagation();
e.preventDefault();
});
});
Your css would of course come into play also but that can be left to you!
This should give you an example of what you need .. But you're already on the right track, sometimes there is merit in reusing other people code too you know! :)

Image follows the cursor

I need help trying to do following:
One: Click once to begin the image to follow
Two: Click again to stop the image
Three: It will notify which of the two states the user is in
My jfiddle code example is below.
$(document).mousemove(function (e) {
$("#giraffeImg").stop().animate({
left: e.pageX,
top: e.pageY
});
});
http://jsfiddle.net/sure1thing/5q8zH/4/
Thanks
What about this:
var follow = false;
$(document).on('mousemove', function(e)
{
//console.log(e.pageX);
if(follow)
{
//alert('follow true');
$('#image').animate({
left: e.pageX,
top: e.pageY
}, 0)
}
})
$(document).click(function()
{
if(follow)
{
follow = false;
}
else
{
follow = true;
}
})
jsFiddle
I just use a "flag" to start and stop the animation.
Try this code:-
Fiddle link
$(document).ready(function(){
var count = 0,
anim = function(e){
$("#giraffeImg").stop().animate({left:e.pageX, top:e.pageY});
}
$(this).click(function(e){
count += 1;
if(count % 2){
console.log('Animation started')
$(this).on('mousemove',anim);
}else{
$(this).off('mousemove', anim);
console.log('Animation finished')
}
})
})

Making click events into touch events when run on tablets

I have made a spelling game for primary school children. I want to make the click events in my game touch events so it can be compatible on tablets. Is there a way I can put them alongside my click events so that one program is compatible to both, or will I have to make a tablet version?
Here I have the code for one of my click events as an example
$('.drag').on('click', function(e) {
e.preventDefault();
if (animation) return;
animation = true;
setTimeout(function() {
animation = false;
}, 700);
$(".minibutton").css('visibility', 'hidden');
$('.next').css('visibility', 'hidden');
var target = $('.drop-box.spellword:not(.occupied):first');
var targetPos = target.position();
var currentPos = $(this).offset();
var b = $(this);
if (target.length) {
target.addClass("occupied");
b.clone().addClass(
b.data("letter") == target.data("letter") ? "wordglow3" : "wordglow").appendTo("table").css({
background: "transparent",
position: "absolute",
top: currentPos.top,
left: currentPos.left
}).animate({
top: targetPos.top,
left: targetPos.left
}, "slow", function() {
$(this).css({
top: 0,
left: 0
}).appendTo(target);
var spellWord = $('.drop-box.spellword');
if (!spellWord.filter(':not(.occupied)').length) {
var wordIsCorrect = 0;
spellWord.each(function() {
if ($(this).data("letter") == $(this).find("div").data("letter")) {
wordIsCorrect++;
}
});
if (spellWord.length == wordIsCorrect) {
spellWord.addClass('wordglow2');
$(right).val('Right!');
$(right).show();
success.play();
$(wrong).hide();
score.right++;
score.attempts++;
if (score.right == 3) {
$('.answers').css('visibility', 'visible');
$('.answers').html("Well done! </br> You correctly spelt " + score.right + ". </br> Keep it up.").show();
$('table').fadeOut(3000);
$('.right').hide();
$('.box-style2').hide();
$('.box-style').hide();
$('.picstyle').hide();
$('.play').hide();
$('.minibutton2').hide();
$("#mysoundclip").attr('src', listOfWords[rndWord].audio);
audio.stop();
$("#mypic").attr('src', listOfWords[rndWord].pic);
pic.hide();
}
setTimeout(function() {
jQuery('.minibutton').trigger('click');
}, 1500);
setTimeout(function() {
jQuery(right).hide();
}, 1500);
} else {
//spellWord.addClass("wordglow4").css('color', 'transparent');
$(wrong).val('Wrong!');
$(wrong).show();
failure.play();
$(right).hide();
score.wrong++;
score.attempts++;
if (score.wrong == 3) {
$(".minibutton").css('visibility', 'visible');
$('.next').css('visibility', 'visible');
}
$('.drop-box.spellword').animate({
'opacity': 1
}, 1500, function() {
$(this).removeClass('wordglow4').removeClass('occupied').html('')
});
setTimeout(function() {
jQuery(wrong).hide();
}, 1500);
}
}
});
}
});
Can someone point me in the right direction as I have never done this before.
Here is a fiddle to help (Sound warning!!) http://jsfiddle.net/smilburn/7Y7A5/8/
You could add the tap event and include jQuery Mobile in your mobile version.
$('.drag').on('click tap', function(e) {...}

Categories

Resources