http://jsfiddle.net/uTV5k/19/
Hello,
I am using the below script on my mobile site. Please see the jsfiddle of simulated script and markup.
The script below is exactly what's on my mobile site, and the js fiddle is a replicate of it.
In the jsfiddle, the click alternations work fine. The first click opens the animation, and the second click closes the animation.
The problem on my mobile site, the first click opens the animation, and the second animation runs immediately after with-out a second click. But in the fiddle it runs OK.
$(window).load(function(){
$(window).bind("orientationchange resize", function(e) {
$('.home-mod').each(function() {
var homeModule = $(this).height(),
homeTitle = $(this).find('.home-title-button').outerHeight(),
homeStart = homeModule - homeTitle,
homeOpen = false;
$(this).find('.mod-info').css("top", homeStart + "px");
$(this).on('click', function () {
if (homeOpen) {
// second click alternation
$(this).find('.mod-info').animate({ top: homeStart + "px" });
homeOpen = false;
} else {
// first click alternation
$(this).find('.mod-info').animate({ top: 0 });
homeOpen = true;
}
});
});
}).trigger("resize");
});
I'm really not sure why this would be happening. Using this in iScroll shouldnt cause any problems should it?
Thanks in advance
firstly : window load happens
you are calling
.trigger("resize");
which activates the bind on click.
later on - if the window load happens again - it retrigger the code which again - re bind the click
The difference between your fiddle code and your live code is the presence of the resize/orientation handler.
All your other code is inside that meaning that it will get run every time your run your resize handler. http://jsfiddle.net/uTV5k/20/ is a variant of your fiddle with that handler back in. It misbehaves badly.
You can fix this by removing the old click handlers before adding the new ones using .off('click').
This fiddle includes this update and seems to behave again: http://jsfiddle.net/uTV5k/21/
The other (and possibly better) way of fixing this issue is to just recalculate the values you need to in the on resize and store them more globally. Then your click functions can be added once and refer to these global values. This is a much bigger code rewrite and I just went for the very simple fix to highlight your problem.
Related
Currenlty when a page is posting back or something else is going on I display a big grey div over the top of the whole page so that the user can't click the same button multiple times. This works fine 99% of the time, the other 1% is on certain mobile devices where the user can scroll/zoom away from the div.
Instead of trying to perfect the CSS so that it works correctly (this will be an on going battle with new devices) I've decided to just stop the user from being able to click anything. Something like $('a').click(function(e){e.preventDefault();}); would stop people from clicking anchor tags and navigating to the link but it wouldn't stop an onclick event in the link from firing.
I want to try to avoid changing the page too radically (like removing every onclick attribute) since the page will eventually have to be changed back to its original state. What I would like to do is intercept clicks before the onclick event is executed but I don't think that this is possible. What I do instead is hide the clicked element on mouse down and show it on mouseup of the document, this stops the click event firing but doesn't look very nice. Can anyone think of a better solution? If not then will this work on every device/browser?
var catchClickHandler = function(){
var $this = $(this);
$this.attr('data-orig-display', $this.css('display'));
$this.css({display:'none'});
};
var resetClickedElems = function(){
$('[data-orig-display]').each(function(){
$(this).css({display:$(this).attr('data-orig-display')}).removeAttr('data-orig-display');
});
};
$('#btn').click(function(){
$('a,input').on('mousedown',catchClickHandler);
$(document).on('mouseup', resetClickedElems);
setTimeout(function(){
$('a,input').off('mousedown',catchClickHandler);
$(document).off('mouseup', resetClickedElems);
}, 5000);
});
JSFiddle: http://jsfiddle.net/d4wzK/2/
You could use the jQuery BlockUI Plugin
http://www.malsup.com/jquery/block/
You can do something like this to prevent all actions of the anchor tags:
jQuery('#btn').click(function(){
jQuery('a').each(function() {
jQuery(this).attr('stopClick', jQuery(this).attr('onclick'))
.removeAttr('onclick')
.click(function(e) {
e.preventDefault();
});
});
});
That renames the onclick to stopclick if you need to revert later and also stops the default behavior of following the href.
document.addListener('click',function(e){e.preventDefault()})
Modified-
Its your duty to remove the click event from the document after you are done accomplishing with your task.
Eg -
function prevent(e){
e.preventDefault()
}
//add
document.addListener('click',prevent)
//remove
document.removeListener('click',prevent)
People!
This is the first time I come here to ask something, so far, always when I had a problem, I could find a good answer here. So, in first place, thanks for this amazing community!
Now let's go to the problem:
I'm doing a responsive menu that check the window.resize event and, when it fits the minimum browser width, a click function for a button is allowed. If the browser width is greater, then the click function is unbound. I need to do this because the same element that is the button on the mobile version, is a visual element on the desktop version.
The problem is that, with the code that I have now, when the page is loaded, the click function works fine. But, if I resize the browser and click on the element again, it triggers more than once the state, sometimes leaving the impression that the function isn't triggered. And, if I resize the browser again, it triggers the click function more than the last time I clicked. Really annoying.
To help understand what is happening, I've made a simple example. Here's is the simple code (just to check the click function issue):
HTML:
<ul>
<li><span class="sub-toggle">Testing 01</span></li>
<li><span class="sub-toggle">Testing 02</span></li>
<li><span class="sub-toggle">Testing 03</span></li>
</ul>
CSS:
.sub-toggle{
display:block;
padding: 20px;
}
.sub-toggle.active{
background-color: #ffcc00;
color: #fff;
}
Javascript (jQuery):
jQuery(function($){
var i = 1;
// check if browser size is compatible with click event
onResize = function() {
// if browser size is ok, do the click function
if($(window).width() <= 480){
// click function
$('.sub-toggle').click(function(){
alert('click');
if($(this).hasClass('active')){
alert('active');
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});
} else{
// if browser size is greater than expected, unbind the click function
$('.sub-toggle').removeClass('active').unbind('click');
}
// just checking how many times the resize function is triggered
console.log('resize: '+ i);
i++;
}
$(document).ready(onResize);
var timer;
$(window).bind('resize', function(){
timer && clearTimeout(timer);
timer = setTimeout(onResize, 500);
});
});
(Edited to remove some unnecessary code)
If you want to see it in action, I've made a Fiddle (try resize the output frame to see it working): http://jsfiddle.net/C7ppv/1/
Maybe I've missing something really stupid, since I don't have a huge knowledge in JavaScript. But what I want to do is just trigger the click event once, even if multiple resizes.
I hope I could explain well my problem. I've searched and didn't found a solution for this issue (or maybe I just didn't know really well what to look for).
Any help would be appreciated!
Your code currently binds a new click events every time the method onResize is called and the window width is less than or equal to 480px.
Simply unbind any existing click events on the .sub-toggle element before binding a new one.
$('.sub-toggle').unbind('click').click(function() {
...
});
DEMO
The resize event is triggered multiple times during resizing, and each time you're binding a new click handler. My suggestion: bind only once, from outside the resize handler, and set a flag while resizing to let the click handler know if it should do something or not.
Then you won't even need to defer the handling of resize with setTimeout as you're doing.
DEMO
jQuery(function($){
var i = 1;
// flag to allow clicking
var clickAllowed = true;
// click function
$('.sub-toggle').click(function(){
if(clickAllowed) {
alert('click');
if($(this).hasClass('active')){
alert('active');
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
}
});
// check if browser size is compatible with click event
onResize = function() {
//if browser size is ok, do the click function
if($(window).width() <= 480){
clickAllowed = true;
}
else{
// if browser size is greater than expected, disallow clicking
clickAllowed = false;
}
// just checking how many times the resize function is triggered
console.log('resize: '+ i);
i++;
}
$(document).ready(onResize);
var timer;
$(window).bind('resize', onResize);
});
Move $('.sub-toggle').click(function(){...} outside the onResize event handler and move if($(window).width() <= 480){...} into the click handler.
I'm trying to simulate two click to open a menu. The first one opens the menu and the second the submenu but after the first click() the function stops.
This is my JS code:
function open_menu(id_menu, id_sub_menu) {
$('.sous-domaines a#lien-domaine-'+id_menu).click();
$('a#lien-menu-'+id_sub_menu).click();
}
I call my function in HTML with this code:
<span onClick="open_menu('0', '116')">Open sub-menu</span>
You're doing it too fast maybe.
Wrap the second one in a window.setTimeout()
can you do something like this ? set a bool after first click
var IsClick = false;
function open_menu(id_menu, id_sub_menu) {
$('.sous-domaines a#lien-domaine-'+id_menu).click();
if (IsClick){ fnSecondClick();}
}
function fnSecondClick() {
//open submenu
}
or something like this - on click check if menu is visible:
function open_menu(id_menu, id_sub_menu) {
$('.sous-domaines a#lien-domaine-'+id_menu).click();
if ($(element).is(":visible")){ fnSecondClick();}
}
Well you can give this a try, it is pretty much waht you had, other than the fact i don't have menu open somewhere
http://jsfiddle.net/tRg3e/2/
I think the .click() only works if you have a handler attached, it does not trigger the native click on the element.. I tried it without handler and the link does not go
You should stray away from 'onClick' declared in elements like that, it's bad practice if I do recall. Nonetheless, it still works.
If you could provide some HTML code it would help clarify the idea but you could set a trigger event for example:
http://jsfiddle.net/wrN2u/3/
EDIT: With a toggle - http://jsfiddle.net/wrN2u/18/
I have this script that run to fix my menu bar to the browser on scroll. Nothing really needs to change here (works as it should). However, you may need it...
var div = $('#wizMenuWrap');
var editor = $('#main_wrapper');
var start = $(div).offset().top;
$(function fixedPackage(){
$.event.add(window, "scroll", function() {
var p = $(window).scrollTop();
$(div).css('position',((p)>start) ? 'fixed' : 'static');
$(div).css('top',((p)>start) ? '0px' : '');
//Adds TOP margin to #main_wrapper (required)
$(editor).css('position',((p)>start) ? 'relative' : 'static');
$(editor).css('top',((p)>start) ? '88px' : '');
});
});
Now for the issue at hand. I have another script function that calls a modal pop-up (which again works as it should). However, it's not slick from a UI perspective when I scroll the page when the modals open. So I want to disable the script above when the modal script below is called. In other words, when I click to open the modal pop-up, the script above shouldn't work.
$(function () {
var setUp = $('.setupButton');
// SHOWS SPECIFIED VIEW
$(setUp).click(function () {
$('#setupPanel').modal('show');
//PREVENTS PACKAGE SELECT FIXED POSITION ON SCROLL
$(setUp).unbind('click',fixedPackage);
});
})
As you can see above, I tried to unbind the scroll function (the first code snippet), but this is not correct.
These two scripts are in two separate js libraries.
I strongly disagree that you ought to be binding and unbinding the event. There's no need! A little logic in your scroll event to check to see if the modal is open should take care of the issue:
$(function fixedPackage(){
$(window).bind("scroll", function() {
// if the modal is displayed, do nothing
if ($('#setupPanel').is(':visible'))
return;
// -- existing code here --
});
});
This way, if the modal element is visible, the code simply stops where it is. Once you hide the element, the code will continue to work as before without having to manage the state of event in some other script... confusing!
Also, as mentioned in some other comments, don't use $.event.add, use the public API method bind
Documentation
jQuery is - http://api.jquery.com/is/
jQuery visible selector - http://api.jquery.com/visible-selector/
jQuery bind - http://api.jquery.com/bind/
When you store a jquery object into a var you can call functions directly:
var setUp = $('.setupButton');
var div = $('#wizMenuWrap');
var editor = $('#main_wrapper');
setUp.click(...);
seTup.unbind(...);
editor.css(...);
div.css(...);
all you need to do is change your script to:
$(function () {
var setUp = $('.setupButton');
// SHOWS SPECIFIED VIEW
$(setUp).bind('click',function () {
$('#setupPanel').modal('show');
//PREVENTS PACKAGE SELECT FIXED POSITION ON SCROLL
$(setUp).unbind('click');
});
})
As explained in the jQuery Docs, Event handlers attached with .bind() can be removed with .unbind() . For more information about bind and unbind:
.bind()
.unbind()
try
$(setUp).unbind('click').die('click')
How can I define in jQuery was it a regular click on the same element or double-click?
For example we have element like this:
<div id="here">Click me once or twice</div>
And we need to perform different actions after regular click and double-click.
I tried something like this:
$("#here").dblclick(function(){
alert('Double click');
});
$("#here").click(function(){
alert('Click');
});
But, of course, it doesn't work, everytime works only 'click'.
Then, some people showed me this:
var clickCounter = new Array();
$('#here').click(function () {
clickCounter.push('true');
setTimeout('clickCounter.pop()', 50);
if (clickCounter.length > 2) {
//double click
clickCounter = new Array(); //drop array
} else {
//click
clickCounter = new Array(); //drop array !bug ovethere
}
});
Here we tried to set the interval between clicks, and then keep track of two consecutive events, but this have one problem.. it doesn't work too.
So, someone knows how to do this? or can someone share a link to the material, where I can read about it?
From QuirksMode:
Dblclick
The dblclick event is rarely used. Even when you use it, you should be
sure never to register both an onclick and an ondblclick event handler
on the same HTML element. Finding out what the user has actually done
is nearly impossible if you register both.
After all, when the user double–clicks on an element one click event
takes place before the dblclick. Besides, in Netscape the second click
event is also separately handled before the dblclick. Finally, alerts
are dangerous here, too.
So keep your clicks and dblclicks well separated to avoid
complications.
(emphasis mine)
What you are doing in your question, is exactly how it should be done.
$(".test").click(function() {
$("body").append("you clicked me<br />");
});
$(".test").dblclick(function() {
$("body").append("you doubleclicked me<br />");
});
It works and here is an demo for that.
Since, you want to detect separate single double click. There is a git project for this.
$("button").single_double_click(function () {
alert("Try double-clicking me!")
}, function () {
alert("Double click detected, I'm hiding")
$(this).hide()
})
It adds up events to detect single double clicks.
Hope it helps you now.