I'm trying to figure out how to solve the tapped class being assigned to the elements when scrolling, but it's taking effect too quick which I need to delay it a bit when it's actually touched instead of touched while scrolling, this is my code of how it works:
$('div, a, span').filter('[tappable][data-tappable-role]').bind('touchstart', function()
{
var self = $(this);
self.addClass(self.data('tappable-role'));
}).bind('touchend', function()
{
var self = $(this);
self.removeClass(self.data('tappable-role'));
}).bind('click', function()
{
var self = $(this),
goTo = self.data('goto');
if(typeof goTo !== 'undefined')
{
window.location = goTo;
}
});
When scrolling, it will assign the class to the element when I've barely touched it, I want to prevent this from happening unless it's properly touched (not clicked). Although I tried experimenting with the setTimeout, but that doesn't work well as it delays but it will still assign the class later on.
This is how I did it with the setTimeout:
var currentTapped;
$('div, a, span').filter('[tappable][data-tappable-role]').bind('touchstart', function()
{
clearTimeout(currentTapped);
var self = $(this);
var currentTapped = setTimeout(function()
{
self.addClass(self.data('tappable-role'));
}, 60);
}).bind('touchend', function()
{
clearTimeout(currentTapped);
var self = $(this);
self.removeClass(self.data('tappable-role'));
}).bind('click', function()
{
clearTimeout(currentTapped);
var self = $(this),
goTo = self.data('goto');
if(typeof goTo !== 'undefined')
{
window.location = goTo;
}
});
How can I do this the effective way?
Demo #1 (with setTimeout).
Demo #2 (with no setTimeout)
You need to view it on your iPhone/iPod/iPad or an emulator to test the fiddle.
UPDATE:
function nextEvent()
{
$(this).on('touchend', function(e)
{
var self = $(this);
self.addClass(self.data('tappable-role')).off('touchend');
})
.on('touchmove', function(e)
{
var self = $(this);
self.removeClass(self.data('tappable-role')).off('touchend');
})
.click(function()
{
var self = $(this),
goTo = self.data('goto');
if(typeof goTo !== 'undefined')
{
window.location = goTo;
}
});
}
$('div, a, span').filter('[tappable][data-tappable-role]').on('touchstart', this, nextEvent);
Here's how I did it:
Essentially, when you navigate a page you're going to tap or scroll. (Well there are other things like pinch and slide put you can figure them out later)...
So on a tap your 'touchstart' will be followed by a 'touchend'
On a scroll your 'touchstart' will be followed by a 'touchmove'
Using Jq 1.7... on other versions you can use .bind()
function nextEvent() {
//behaviour for end
$(this).on('touchend', function(e){
/* DO STUFF */
$(this).off('touchend');
});
//behaviour for move
$(this).on('touchmove', function(e){
$(this).off('touchend');
});
}
$('div, a, span').filter('[tappable][data-tappable-role]').on('touchstart', this, nextEvent);
Basically, when a 'touchstart' happens, I bind actions to 'touchend' and 'touchmove'.
'Touchend' does whatever I would want a tap to do and then unbinds itself
'Touchmove' basically does nothing except unbind 'touchend'
This way if you tap you get action, if you scroll nothing happens but scrolling..
RESPONSE TO COMMENT: If I understand your comment properly, try this:
function nextEvent() {
var self = $(this);
self.addClass(self.data('tappable-role'))
//behaviour for move
$(this).on('touchmove', function(e){
self.removeClass(self.data('tappable-role'));
});
}
$('div, a, span').filter('[tappable][data-tappable-role]').on('touchstart', this, nextEvent);
Despite this is a relatively old question with a best answer already selected, I want to share my solution.
I achieved this by triggering the events just on click.
$("div, a, span").on("click", function() {
// Your code here
}
Maybe is not the best way to do it, but this worked for me.
Related
I am very new to Javascript.
I am trying to write this baby jQuery plugin that I will use to make dropdown lists. What I am failing to achieve (beyond things that I do not notice) is to neatly exit or deactivate my active instance as I click on another instance. I tried to illustrate my problem in the following fiddle (keeping the structure I am using):
https://jsfiddle.net/andinse/m0kwfj9d/23/
What the Javascript looks like:
$(document).ready(function() {
$.fn.activator = function() {
var Activator = function(el) {
this.html = $('html');
this.el = el;
this.is_active = false;
this.initialize();
};
Activator.prototype.initialize = function() {
var self = this;
self.el.on('click', function(e) {
if (self.is_active === false) {
self.toggle('activate');
} else {
self.toggle('deactivate');
}
});
};
Activator.prototype.toggle = function(action) {
var self = this;
if (action === 'activate') {
console.log('activating ' + self.el[0].className);
self.is_active = true;
self.el.addClass('red');
self.html.on('click', function(e) {
if (e.target != self.el[0]) {
self.toggle('deactivate');
}
});
}
if (action === 'deactivate') {
console.log('deactivating ' + self.el[0].className);
self.is_active = false;
self.el.removeClass('red');
self.html.off('click');
}
};
if (typeof this !== 'undefined') {
var activator = new Activator(this);
}
return this;
};
$('.a').activator();
$('.b').activator();
$('.c').activator();
});
My idea was:
To watch for clicks on html as soon as the instance is active (thus ready to be deactivated). On click, to check if the event.target is the same as the active instance. If not, to deactivate this instance.
To stop watching for clicks as soon as the instance is inactive. So that we're not doing unnecessary work.
When it is set like this, it seems to work for only one cycle (click on A activates A then click on B activates B and deactivates A then click on C activates C but doesn't deactivate B).
If I get rid of the "self.html.off('click')" it seems to work kind of ok but if I look at the log I can see the "toggle" function is sometimes triggered multiple times per click. There must be a cleaner way.
Any piece of help greatly appreciated.
With your logic, when clicking any element you should deactivate any current activated element. Either do it globally:
$('.your_activation_class').removeClass('.your_activation_class');
or in some parent scope
$('some_parent_selector .your_activation_class').removeClass('.your_activation_class');
I have a function which creates a div via createElement() in JavaScript.
The problem is that the scroll event is not fired on this div. The weird thing is that the click event fires but not the scroll event. This worked well when I created the div via $.html() on jQuery.
Also my two other functions that scroll the div on hovering on .direction_left and . direction_right don't work either. Also these worked well when I created the div via $.html(). What is the problem here? Thanks.
this is the scroll function to load data via ajax.
var scroll = true;
$(document).on('scroll', '#infinited', function() {
alert('scroll');
var div = $(this);
if(div[0].scrollWidth - div.scrollLeft() == div.width()) {
if(scroll == true) {
$.post('ajax/user/get_infinited.php', {'start': div.children().length}, function(data) {
if(data == '')
scroll = false;
div.append(data);
});
}
}
});
this is the function which creates the infinited div.
create_infinited: function() {
if(!document.getElementById("i")) {
var i = document.createElement("div");
i.id = 'i';
i.style.position = 'relative';
var infinited = document.createElement("div");
infinited.id = 'infinited';
var direction_left = document.createElement("div");
direction_left.className = 'direction_left';
var direction_right = document.createElement("div");
direction_right.className = 'direction_right';
i.appendChild(direction_left);
i.appendChild(infinited);
i.appendChild(direction_right);
$('#search_form').after(i);
}
}
It isn't working because the scroll event doesn't bubble up in the DOM (if you check for example the click event, it will work and that proves that the problem is not in your code - or at least not the way you'd expect).
However, in modern browsers you can capture the scroll event on the document level via the addEventListener, like this:
document.addEventListener(
'scroll',
function(event){
var $elm = $(event.target);
if( $elm.is('#infinited')){
// put your code here
}
},
true
);
Or you can move your "data loader logic" to a function (let's call it getInfinited) that can be accessed in create_infinited, and subscribe there:
$('#search_form').after(i);
$('#infinited').on('scroll', getInfinited);
How can I make the softkeyboard come up with the bootstrap modal when auto focusing a field?
It sounds easy, but I am unable to do so as of yet.
The focus part works but not the keyboard.
I am trying to save the user a tap.
I can leverage 'shown.bs.modal' and set the focus but the softkeyboard will not show up automatically. The user still needs to retap the field. How can I force the softkeyboard to come up.
The code I am currently playing with (pretty much):
this.$container.on('shown.bs.modal', function () {
console.log('shown.bs.modal');
setTimeout(function () {
var $ctrl = $(jqselector);
$ctrl.addClass('active').focus();
}, 500);
});
this.$container.modal({
backdrop: (this.config.showModal ? 'static' : true)
})
.on('hidden.bs.modal', function () {
$(this).remove();
});
SE question related to just focus
another question
Edit:
After looking at the bootstrap code a bit, it looks like it ads focus to the modal control after all of the processing. I assumed something like this was happening which is why I added the setTimeout, but even with a large delay, no luck. I will look at the bootsrap code a little more closely this weekend
Bounty edit:
Bootstrap code:
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.$body.addClass('modal-open')
this.setScrollbar()
this.escape()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(300) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
I have been playing with code in a timout on the show and shown custom modal events. The code pretty much looks like the following.
setTimeout(function (e) {
$(':focus').trigger('blur');
$(document).off('focusin.bs.modal');
var $ctrl = $(jqSelect);
$ctrl.trigger('focus');
$ctrl.trigger('click');
}, 750);
I think that this doesn't have to do with Bootstrap, but with the limitations of auto-focusing form fields on mobile devices. For example, Mobile Safari will only let you programmatically focus() an element if it is executed synchronously inside a click event handler (see this SO question for more information).
If you really want the keyboard to automatically show up, perhaps what will work is if you bind to the click/touchend event instead of bs.modal.show
var self = this;
$('.some-btn-that-triggers-the-modal').on('click', function() {
$(jqSelector).addClass('active').focus();
});
var toogleDelay = 500;
var closeTimeout = null;
$(">ul>li", $nav).hover(function () {
var $this = $(this);
if(closeTimeout) {
clearTimeout(closeTimeout);
}
var openMenuCallback = function() {
$this.addClass("hover");
};
window.setTimeout(openMenuCallback, toogleDelay);
}, function () {
var $this = $(this);
var closeMenuCallback = function() {
$this.removeClass("hover");
};
closeTimeout = window.setTimeout(closeMenuCallback, toogleDelay);
});
I use this snippet to open and close a multidropdown-menu and I want the menu to fade in and out with a 0.5s delay. I also added a cleartimeout to the mouseover part of the jquery hover function, so that the menu does not close if somebody (accidently) leaves the menuarea and enters it again within the 0.5s. This all works fine, but I now have the problem, because there is more than just one dropdown, that the closeTimeout of lets say the first dropdown gets cleared, if I move the mouse from the first directly to the second dropdown and I now have both dropdown-elements open. How must I rewrite the code, so that every dropdown has its own closeTimeout and at the same time I am still able to clear the timeout in the mouseover part of the hover function.
thx
sub
You could store the timer's id in the element's data. Something like
var $this = $(this);
var closeMenuCallback = function() {
$this.removeClass("hover");
$this.removeData("timerid");
};
var closeTimeout = window.setTimeout(closeMenuCallback, toogleDelay);
$this.data("timerid", closeTimeout);
and then check it with
var $this = $(this);
var closeTimeout = $this.data("timerid");
if(closeTimeout) {
clearTimeout(closeTimeout);
$this.removeData("timerid");
}
I know this isn't part of the question but I like the CSS approach to this.
http://webdesignerwall.com/tutorials/css3-dropdown-menu
there are a number of examples for this. some multilevel some not.
I have an element on my page that I need to attach onclick and ondblclick event handlers to. When a single click happens, it should do something different than a double-click. When I first started trying to make this work, my head started spinning. Obviously, onclick will always fire when you double-click. So I tried using a timeout-based structure like this...
window.onload = function() {
var timer;
var el = document.getElementById('testButton');
el.onclick = function() {
timer = setTimeout(function() { alert('Single'); }, 150);
}
el.ondblclick = function() {
clearTimeout(timer);
alert('Double');
}
}
But I got inconsistent results (using IE8). It would work properly alot of times, but sometimes I would get the "Single" alert two times.
Has anybody done this before? Is there a more effective way?
Like Matt, I had a much better experience when I increased the timeout value slightly. Also, to mitigate the problem of single click firing twice (which I was unable to reproduce with the higher timer anyway), I added a line to the single click handler:
el.onclick = function() {
if (timer) clearTimeout(timer);
timer = setTimeout(function() { alert('Single'); }, 250);
}
This way, if click is already set to fire, it will clear itself to avoid duplicate 'Single' alerts.
If you're getting 2 alerts, it would seem your threshold for detecing a double click is too small. Try increasing 150 to 300ms.
Also - I'm not sure that you are guaranteed the order in which click and dblclick are fired. So, when your dblclick gets fired, it clears out the first click event, but if it fires before the second 'click' event, this second event will still fire on its own, and you'll end up with both a double click event firing and a single click event firing.
I see two possible solutions to this potential problem:
1) Set another timeout for actually firing the double-click event. Mark in your code that the double click event is about to fire. Then, when the 2nd 'single click' event fires, it can check on this state, and say "oops, dbl click pending, so I'll do nothing"
2) The second option is to swap your target functions out based on click events. It might look something like this:
window.onload = function() {
var timer;
var el = document.getElementById('testButton');
var firing = false;
var singleClick = function(){
alert('Single');
};
var doubleClick = function(){
alert('Double');
};
var firingFunc = singleClick;
el.onclick = function() {
// Detect the 2nd single click event, so we can stop it
if(firing)
return;
firing = true;
timer = setTimeout(function() {
firingFunc();
// Always revert back to singleClick firing function
firingFunc = singleClick;
firing = false;
}, 150);
}
el.ondblclick = function() {
firingFunc = doubleClick;
// Now, when the original timeout of your single click finishes,
// firingFunc will be pointing to your doubleClick handler
}
}
Basically what is happening here is you let the original timeout you set continue. It will always call firingFunc(); The only thing that changes is what firingFunc() is actually pointing to. Once the double click is detected, it sets it to doubleClick. And then we always revert back to singleClick once the timeout expires.
We also have a "firing" variable in there so we know to intercept the 2nd single click event.
Another alternative is to ignore dblclick events entirely, and just detect it with the single clicks and the timer:
window.onload = function() {
var timer;
var el = document.getElementById('testButton');
var firing = false;
var singleClick = function(){
alert('Single');
};
var doubleClick = function(){
alert('Double');
};
var firingFunc = singleClick;
el.onclick = function() {
// Detect the 2nd single click event, so we can set it to doubleClick
if(firing){
firingFunc = doubleClick;
return;
}
firing = true;
timer = setTimeout(function() {
firingFunc();
// Always revert back to singleClick firing function
firingFunc = singleClick;
firing = false;
}, 150);
}
}
This is untested :)
Simple:
obj.onclick=function(e){
if(obj.timerID){
clearTimeout(obj.timerID);
obj.timerID=null;
console.log("double")
}
else{
obj.timerID=setTimeout(function(){
obj.timerID=null;
console.log("single")
},250)}
}//onclick
Small fix
if(typeof dbtimer != "undefined"){
dbclearTimeout(timer);
timer = undefined;
//double click
}else{
dbtimer = setTimeout(function() {
dbtimer = undefined;
//single click
}, 250);
}
, cellclick :
function(){
setTimeout(function(){
if (this.dblclickchk) return;
setTimeout(function(){
click event......
},100);
},500);
}
, celldblclick :
function(){
setTimeout(function(){
this.dblclickchk = true;
setTimeout(function(){
dblclick event.....
},100);
setTimeout(function(){
this.dblclickchk = false;
},3000);
},1);
}
I found by accident that this works (it's a case with Bing Maps):
pushpin.clickTimer = -1;
Microsoft.Maps.Events.addHandler(pushpin, 'click', (pushpin) {
return function () {
if (pushpin.clickTimer == -1) {
pushpin.clickTimer = setTimeout((function (pushpin) {
return function () {
alert('Single Clic!');
pushpin.clickTimer = -1;
// single click handle code here
}
}(pushpin)), 300);
}
}
}(pushpin)));
Microsoft.Maps.Events.addHandler(pushpin, 'dblclick', (function (pushpin) {
return function () {
alert('Double Click!');
clearTimeout(pushpin.clickTimer);
pushpin.clickTimer = -1;
// double click handle here
}
}(pushpin)));
It looks like the click event masks the dblclick event, and this usage is clearing it when we add a timeout. So, hopefully, this will work also with non Bing Maps cases, after a slight adaptation, but I didn't try it.