Now that Bootstrap 3 is out, what is the recommended option for enabling touch? As before, there aren't many touch events in the bootstrap.js, though it is supposed to be a mobile first framework.
The last thing I've found on github suggests using fastclick.js, but that was before the v3.0 release.
My recommendation is to use Bootstrap alongside JQuery mobile, TouchSwipe, or Hammer.js . An example of a bootstrap touch carousel can be found here.
Start working on another fully working Touch Carousel on GitHub. This also includes drag events...
Despite I believe bootstrap is a joke of a css framework (especially due to no multileveled navigation), I would probably agree with others to go with some different carousel if you have a choice.
From my experience JQuery mobile will work rather smoothly but my site was not built alongside jquery mobile and the css belonging to it really messed the things up.
<script>
$(document).ready(function() {
$('.carouselresp').carousel({'data-interval': 6000, 'data-pause': "hover"});
var clicking = false;
var currentMousePos = 0;
var newMousePos = 0;
$('.carouselresp img').on('mousedown', function(event) {
clicking = true;
currentMousePos = event.pageX;
});
$('.carouselresp img').on('touchstart', function(event) {
clicking = true;
var touchstart = event.originalEvent.touches[0];
currentMousePos = touchstart.pageX;
});
$(document).on('mouseup', function(event) {
clicking = false;
});
$('.carouselresp img').on('touchend', function(event) {
clicking = false;
});
$(document).on('mousemove', function(event) {
if (!clicking) {
return;
}else {
if (event.pageX < currentMousePos) {
if ((currentMousePos - event.pageX) > 50) {
$('.carouselresp').carousel('next');
clicking = false;
}
} else {
if ((event.pageX - currentMousePos) > 50) {
$('.carouselresp').carousel('prev');
clicking = false;
}
}
}
});
$('.carouselresp img').on('touchmove', function(event) {
var touch = event.originalEvent.touches[0];
if (!clicking) {
return;
}else {
if (touch.pageX < currentMousePos) {
if ((currentMousePos - touch.pageX) > 50) {
$('.carouselresp').carousel('next');
clicking = false;
}
} else {
if ((touch.pageX - currentMousePos) > 50) {
$('.carouselresp').carousel('prev');
clicking = false;
}
}
}
event.preventDefault();
});
});
</script>
It works fine for me on android and iphone too, plus I am allowing the move event in browsers with no touch support.
I hope it helped.
TomHre
Related
I have created a simple slider. I want it also for smartphones and not only for desktops. So in this case it should be possible to let it slide when you move your finger from left to right or from right to left. For now it only works when you click on buttons.
I have no idea how to start with it. How can I do this?
var i = 0;
$('.next').bind('click', function() {
if (i < 4) {
$('li').animate({'left': '-=600px'}, 300).delay(600);
i++;
}
console.log($('li:first').position().left);
console.log(i);
});
$('.back').bind('click', function() {
if (i > 0) {
if ($('li:first').position().left < 0) {
$('li').animate({'left': '+=600px'}, 300).delay(600);
i--;
}
}
console.log(i);
});
https://jsfiddle.net/6t1wx95f/11/
PS: It should work without using a plugin.
I updated your fiddle: https://jsfiddle.net/6t1wx95f/13/
Tested in chrome (in responsive view to have the touch events working). Credit goes to this answer.
Basically, you just need to use touchstart and touchmove events. When you touchmove you just take your X position and compare it to where it was when touch-started.
See the touch events docs. It's all in vanilla javascript so you won't have to include any plugin.
// Set up events
var slider = document.getElementsByClassName('slider')[0];
slider.addEventListener('touchstart', handleTouchStart, false);
slider.addEventListener('touchmove', handleTouchMove, false);
..and
if ( xDiff > 0 ) {
/* left swipe */
slideRight();
} else {
/* right swipe */
slideLeft();
}
when dragging horizontal carousel left to right on touch device it also allows it to be dragged up and down which jiggles the whole page around. How can I disable vertical scrolling on owl carousel.
I can post the js file if anyone can help
Thanks in advance
Awesome css3 :)
.owl-carousel
{
-ms-touch-action: pan-y;
touch-action: pan-y;
}
This seems to work for me, at least on iOS, haven't tested on Android.
When you start sliding with mouse or touch I saw that Owl Carousel adds the class .owl-grab to the slider. I then found this code from #Turnerj and just put .owl-grab in the code.
Disable scrolling when touch moving certain element
It also works with multiple sliders on same page. Hope this helps! (I'm new to jQuery so there could probably be flaws to this solution)
window.blockMenuHeaderScroll = false;
$(window).on('touchstart', function(e) {
if ($(e.target).closest('.owl-grab').length == 1) {
blockMenuHeaderScroll = true;
}
});
$(window).on('touchend', function() {
blockMenuHeaderScroll = false;
});
$(window).on('touchmove', function(e) {
if (blockMenuHeaderScroll) {
e.preventDefault();
}
});
Use hammer.js with addEventListner for Classes.
I have tested with iOS (iphoneX) and Android (Nexus 5X) and work like a charme.
I hope can help!
window.blockMenuHeaderScroll = true;
var mc = new Hammer(document);
var classname = document.getElementsByClassName("elenco_image");
mc.on("swipeleft swiperight panleft panright", function(ev) {
console.log(ev.type + " gesture detected.");
window.blockMenuHeaderScroll = true;
});
mc.on("swipeup swipedown panup pandown", function(ev) {
console.log(ev.type + " gesture detected.");
window.blockMenuHeaderScroll = false;
});
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('touchmove', function(evt) {
if (blockMenuHeaderScroll) {
evt.preventDefault();
}
}, {
passive: false
});
}
.owl-carousel
{
-ms-touch-action: pan-x;
touch-action: pan-x;
}
This worked for me as I need only horizontal scroll. Above code restricts the vertical scroll.
This will block vertical scrolling while dragging the image horizontally,
or prevent the horizontal pan while trying to v-scroll the page itself.
Important: Attach the event directly to the IMG element.
let blockScroll = false;
let blockPan = false;
$('.owl-carousel img').on('touchstart', '', ots);
$('.owl-carousel img').on('touchmove', '', otm);
let p0 = [0,0];
function ots(ev) { //save the first touch point
p0 = [ev.touches[0].screenX, ev.touches[0].screenY];
blockScroll = false;
blockPan = false;
}
function otm(event){
if(blockScroll)
event.preventDefault(); //don't let the window v-scroll
else if(blockPan)
{ //don't let OWL get the event and pan-x.
event.stopPropagation();
event.stopImmediatePropagation();
}
else
{ //calculate distance from the first touch point on every move
let t = event.touches[0];
let dx = t.screenX - p0[0];
let dy = t.screenY - p0[1];
if( Math.abs(dx) > Math.abs(dy) )
{
blockScroll = true;
event.preventDefault();
}
else
{
blockPan = true;
event.stopPropagation();
event.stopImmediatePropagation();
}
}
}
Tested on android (Chrome) and ios(Safari).
Some improvements on #Giovanni Locombi's answer to make the touch actions smoother. Works on iOS
Using Hammer.js from https://hammerjs.github.io/
window.blockMenuHeaderScroll = false;
var mc = new Hammer(document);
var classname = document.getElementsByClassName("owl-carousel");
mc.on("swipeleft swiperight panleft panright", function(ev) {
window.blockMenuHeaderScroll = true;
});
mc.on("panend swipeend", function (ev){
window.blockMenuHeaderScroll = false;
});
mc.on("swipeup swipedown panup pandown", function(ev) {
window.blockMenuHeaderScroll = false;
});
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('touchmove', function(evt) {
if (blockMenuHeaderScroll) {
evt.preventDefault();
}
}, {
passive: false
});
}
None of the above worked for me.
but this worked.
.owl-carousel .owl-stage, .owl-carousel.owl-drag .owl-item{
-ms-touch-action: auto;
touch-action: auto;
}
Is there a way to get the mouse wheel events (not talking about scroll events) in jQuery?
$(document).ready(function(){
$('#foo').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta /120 > 0) {
console.log('scrolling up !');
}
else{
console.log('scrolling down !');
}
});
});
Binding to both mousewheel and DOMMouseScroll ended up working really well for me:
$(window).bind('mousewheel DOMMouseScroll', function(event){
if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
// scroll up
}
else {
// scroll down
}
});
This method is working in IE9+, Chrome 33, and Firefox 27.
Edit - Mar 2016
I decided to revisit this issue since it's been a while. The MDN page for the scroll event has a great way of retrieving the scroll position that makes use of requestAnimationFrame, which is highly preferable to my previous detection method. I modified their code to provide better compatibility in addition to scroll direction and position:
(function() {
var supportOffset = window.pageYOffset !== undefined,
lastKnownPos = 0,
ticking = false,
scrollDir,
currYPos;
function doSomething(scrollPos, scrollDir) {
// Your code goes here...
console.log('scroll pos: ' + scrollPos + ' | scroll dir: ' + scrollDir);
}
window.addEventListener('wheel', function(e) {
currYPos = supportOffset ? window.pageYOffset : document.body.scrollTop;
scrollDir = lastKnownPos > currYPos ? 'up' : 'down';
lastKnownPos = currYPos;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(lastKnownPos, scrollDir);
ticking = false;
});
}
ticking = true;
});
})();
See the Pen Vanilla JS Scroll Tracking by Jesse Dupuy (#blindside85) on CodePen.
This code is currently working in Chrome v50, Firefox v44, Safari v9, and IE9+
References:
https://developer.mozilla.org/en-US/docs/Web/Events/scroll
https://developer.mozilla.org/en-US/docs/Web/Events/wheel
As of now in 2017, you can just write
$(window).on('wheel', function(event){
// deltaY obviously records vertical scroll, deltaX and deltaZ exist too.
// this condition makes sure it's vertical scrolling that happened
if(event.originalEvent.deltaY !== 0){
if(event.originalEvent.deltaY < 0){
// wheeled up
}
else {
// wheeled down
}
}
});
Works with current Firefox 51, Chrome 56, IE9+
There's a plugin that detects up/down mouse wheel and velocity over a region.
Answers talking about "mousewheel" event are refering to a deprecated event. The standard event is simply "wheel". See https://developer.mozilla.org/en-US/docs/Web/Reference/Events/wheel
This worked for me:)
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
from stackoverflow
Here is a vanilla solution. Can be used in jQuery if the event passed to the function is event.originalEvent which jQuery makes available as property of the jQuery event. Or if inside the callback function under we add before first line: event = event.originalEvent;.
This code normalizes the wheel speed/amount and is positive for what would be a forward scroll in a typical mouse, and negative in a backward mouse wheel movement.
Demo: http://jsfiddle.net/BXhzD/
var wheel = document.getElementById('wheel');
function report(ammout) {
wheel.innerHTML = 'wheel ammout: ' + ammout;
}
function callback(event) {
var normalized;
if (event.wheelDelta) {
normalized = (event.wheelDelta % 120 - 0) == -0 ? event.wheelDelta / 120 : event.wheelDelta / 12;
} else {
var rawAmmount = event.deltaY ? event.deltaY : event.detail;
normalized = -(rawAmmount % 3 ? rawAmmount * 10 : rawAmmount / 3);
}
report(normalized);
}
var event = 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll';
window.addEventListener(event, callback);
There is also a plugin for jQuery, which is more verbose in the code and some extra sugar: https://github.com/brandonaaron/jquery-mousewheel
This is working in each IE, Firefox and Chrome's latest versions.
$(document).ready(function(){
$('#whole').bind('DOMMouseScroll mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
alert("up");
}
else{
alert("down");
}
});
});
I was stuck in this issue today and found this code is working fine for me
$('#content').on('mousewheel', function(event) {
//console.log(event.deltaX, event.deltaY, event.deltaFactor);
if(event.deltaY > 0) {
console.log('scroll up');
} else {
console.log('scroll down');
}
});
use this code
knob.bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
moveKnob('down');
} else {
moveKnob('up');
}
return false;
});
The plugin that #DarinDimitrov posted, jquery-mousewheel, is broken with jQuery 3+. It would be more advisable to use jquery-wheel which works with jQuery 3+.
If you don't want to go the jQuery route, MDN highly cautions using the mousewheel event as it's nonstandard and unsupported in many places. It instead says that you should use the wheel event as you get much more specificity over exactly what the values you're getting mean. It's supported by most major browsers.
my combination looks like this. it fades out and fades in on each scroll down/up. otherwise you have to scroll up to the header, for fading the header in.
var header = $("#header");
$('#content-container').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta > 0) {
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
else{
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
}
});
the above one is not optimized for touch/mobile, I think this one does it better for all mobile:
var iScrollPos = 0;
var header = $("#header");
$('#content-container').scroll(function () {
var iCurScrollPos = $(this).scrollTop();
if (iCurScrollPos > iScrollPos) {
if (!header.data('faded')) header.data('faded', 1).stop(true).fadeTo(800, 0);
} else {
//Scrolling Up
if (header.data('faded')) {
header.data('faded', 0).stop(true).fadeTo(800, 1);
}
}
iScrollPos = iCurScrollPos;
});
If using mentioned jquery mousewheel plugin, then what about to use the 2nd argument of event handler function - delta:
$('#my-element').on('mousewheel', function(event, delta) {
if(delta > 0) {
console.log('scroll up');
}
else {
console.log('scroll down');
}
});
I think many key things are a bit all over the place and I needed to read all the answers to make my code work as I wanted, so I will post my findings in just one place:
You should use "wheel" event over the other deprecated or browser specific events.
Many people here is getting something wrong: the opposite of x>0 is x<=0 and the opposite of x<0 is x>=0, many of the answers in here will trigger scrolling down or up incorrectly when x=0 (horizontal scrolling).
Someone was asking how to put sensitivity on it, for this you can use setTimeout() with like 50 ms of delay that changes some helper flag isWaiting=false and you protect yourself with if(isWaiting) then don't do anything. When it fires you manually change isWaiting=true and just below this line you start the setTimeout again who will later change isWaiting=false after 50 ms.
I got same problem recently where
$(window).mousewheel was returning undefined
What I did was $(window).on('mousewheel', function() {});
Further to process it I am using:
function (event) {
var direction = null,
key;
if (event.type === 'mousewheel') {
if (yourFunctionForGetMouseWheelDirection(event) > 0) {
direction = 'up';
} else {
direction = 'down';
}
}
}
I've been working on this jQuery effect heres the fiddle:
http://jsfiddle.net/abtPH/26/
Everything's pretty good so far, however when I click on the elements too fast it seems to get buggy and get weird behavior. If you take your time and click on the elements it works fine.
I've tried using :animate
stuff to make sure the animation ends before the user can click on the next one. I do not like this approach though because from a end user it seems like the effects are laggy. I want the user to be able to click on the elements fast and have the desired effect.
Here's my jQuery so far:
$('li').on('click', function (e) {
e.preventDefault();
var active = $(this).siblings('.active');
var posTop = ($(this).position()).top;
if (active.length > 0) {
var activeTop = (active.position()).top;
if (activeTop == posTop) {
$(this).find('.outer').fadeIn('medium', function () {
active.toggleClass('active', 400).find('.outer').fadeOut('medium');
});
} else {
$(this).siblings('.active').toggleClass('active', 400).find('.outer').slideToggle();
$(this).find('.outer').slideToggle();
}
} else {
$(this).find('.outer').slideToggle();
}
$(this).toggleClass('active', 400);
});
$('.outer').on('click', function (e) {
return false;
});
Use .finish() complete all the queued animation before beginning a new one
$('li').on('click', function(e){
e.preventDefault();
var active = $(this).siblings('.active');
var posTop = ($(this).position()).top;
if (active.length > 0) {
var activeTop = (active.position()).top;
if (activeTop == posTop) {
$(this).find('.outer').finish().fadeIn('medium', function(){
active.finish().toggleClass('active', 400).find('.outer').finish().fadeOut('medium');
});
} else {
$(this).siblings('.active').finish().toggleClass('active', 400).find('.outer').finish().slideToggle();
$(this).find('.outer').finish().slideToggle();
}
} else {
$(this).find('.outer').finish().slideToggle();
}
$(this).finish().toggleClass('active', 400);
});
$('.outer').on('click', function(e){
return false;
});
Demo: Fiddle
I'm creating a responsive template and I want to remove the listeners on an element when screen is being resized or is smaller than the specified width.
Imagine an menu which when you hover on it's items, it shows you the sub-menus in normal displays but the same menu in mobile devices will show the sub-menus only by tapping or clicking on the items.
I can't make the undelegate work. In resized screen I still have the mouseover and mouseout event-listeners. I'm not getting any errors in console and I've tried both:
.off('mouseover', 'li')
.off('mouseover')
.undelegate('li', 'mouseover')
.undelegate('li')
and none of them works.
var $window = $(window);
function handleSidenav() {
$(".nav-list").delegate('li', 'mouseover', function(e) {
$(this).find("a").addClass('active');
$(this).find("div.sub-items").toggle();
}).delegate('li', 'mouseout', function(e) {
$(this).find('a').removeClass('active');
$(this).find("div.sub-items").toggle();
});
}
function checkWidth() {
var windowsize = $window.width();
if (windowsize < 767) {
smallScreenDelegation();
} else {
SmallScreenUndelegation();
}
}
checkWidth();
handleSidenav();
$window.resize(checkWidth());
function smallScreenDelegation() {
$(".nav-list").undelegate('li'); //It's not working
$(".nav-list").undelegate('li'); //It's not working
$(".nav-list").delegate('li a:first', 'click', function(event) {
if ($(this).next().is(':hidden')) {
$(this).addClass('active');
$(this).next().slideDown('slow');
} else {
$(this).removeClass('active').next().slideUp('slow');
}
event.preventDefault();
});
}
You need to wrap window in the jQuery object. I'm not sure if you set $window = $(window), but it seems here that $window.width() and $window.resize(checkWidth) are missing parenthesis. I was able to get it working fine once I changed those to $(window). You have to define which event you want to undelegate. I used:
$('.nav-list').undelegate('li', 'mouseover');
Open up console and you can see that it works: http://jsbin.com/efonut/6/edit
Also, it's really best to use .on() and off() vs .delegate() and .undelegate(), but at least this works...
I still don't know what was wrong with undelegate which I couldn't make it work, but I managed to fix my code by using on and off.
As adeneo said I was delegating and undelegating on each window resize which was quiet a bug and I think I fixed that but holding the last state on device variable.
var $window = $(window);
var device;
function desktopSidenav() {
$(".nav-list > li").off('click');
$(".nav-list > li").on('mouseover', function(e) {
$(this).find("a").addClass('active');
$(this).find("div.sub-items").toggle();
}).on('mouseout', function(e) {
$(this).find('a').removeClass('active');
$(this).find("div.sub-items").toggle();
});
}
function handheldSidenav() {
$(".nav-list > li").off('mouseover').off('mouseout');
$(".nav-list > li").on('click', function(e) {
if ($(this).find("div.sub-items").is(':hidden')) {
$(this).find("a:first").addClass('active').next().slideDown('slow');
} else {
$(this).find("a:first").removeClass('active').next().slideUp('slow');
}
e.preventDefault();
});
}
Now I check the window size before doing anything else an I'll hold the device type in device variable. If window is resized, I'm gonna check the device state and do the things based on device type.
if ($window.width() > 767) {
device = 'desktop';
desktopSidenav();
} else {
device = 'handheld';
handheldSidenav();
}
$window.resize(function() {
if ($window.width() > 767) {
if (device == 'handheld') {
device = 'desktop';
desktopSidenav();
}
} else {
if (device == 'desktop') {
device = 'handheld';
handheldSidenav();
}
}
});
If I use delegate and undelegate instead of on and off, the code won't work and I still don't know why, so this cannot be count as a real answer, but I wanted to tell everyone who has a similar problem to use jQuery's on and off instead on delegate.