jQuery onclick not working on mobile - javascript

I'm trying to activate a menu with jQuery with a click (touch) on mobile, but it is not working in mobile. When I do the 'window' resize to try the mobile look, it works with the click, but in an emulator or even trying it with my phone, it doesn't work.
HTML Markup
<img src="i/mobilemenu.jpg" id="mobileMenuButton" style="position:absolute; right:0;"/>
CSS:
#mobileNavigation {display:none}
Javascript Code:
<script type="text/javascript">
$(document).ready(function(){
$('#mobileMenuButton').on('click touchstart',function(){
if ($('#mobileNavigation').css('display') == 'none') {
$('#mobileNavigation').css('display','block');
}
else
{
$('#mobileNavigation').css('display','none'); }
});
});
</script>

Establish a click handler based on the client as such:
var clickHandler = ("ontouchstart" in window ? "touchend" : "click")
and use it whenever you want to listen to click events:
$(".selector").on(clickHandler, function() {...})
This way you can always make sure the proper event is being listened to.

<script type="text/javascript">
$(document).ready(function(){
$('#mobileMenuButton').on('mousedown touchstart',function(){
var userAgent = window.navigator.userAgent;
if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i)|| userAgent.match(/Android/i)) {
if ($('#mobileNavigation').css('display') == 'none') {
$('#mobileNavigation').css('display','block');
} else {
$('#mobileNavigation').css('display','none');
}
}
});
});
</script>
Just provide the user agent.

I remember when I was building a mobile app, elements that weren't links wouldn't pick up on the click event unless I gave them the CSS property of cursor: pointer. Perhaps this is a similar issue. Try giving the button that property in the style attribute.

Came across this question and realized the click (and touchstart) should work.
#vulcanR, it is not working in your case is because you already have #mobileNavigation as display: none; So, there is no place for the event to be triggered.
Instead, try the following code and it should work-
$(document).ready(function() {
$('#mobileMenuButton').on('click touchstart', function() {
if ($('#mobileNavigation').css('opacity') == '0') {
$('#mobileNavigation').css('opacity','1');
} else {
$('#mobileNavigation').css('opacity','0'); }
});
});
});
The reason behind this working is that opacity:0 retains the height and width of the element whereas display:none makes the dimensions zero, so there is no estate for the event.
You could have also used visibility:hidden, but that doesn't listen to click event or any events in general.

Related

menu hide and toggle strange behavior

$(function(){
$(".OpenTopMenu").click(function (e) {
$("#top_menu").slideToggle("fast");
e.stopPropagation();
});
$(document).click(function() {
$("#top_menu").hide();
});
$(document).on("touchend", function (event) {
if (!$(event.target).closest("#top_menu").length) {
$("#top_menu").hide();
}
});
});
Hi all, i ran into a strange problem with toggle and hide.
As you can see in my code. If i touch the menu button (.OpenTopMenu) the menu (#top_menu) toggle.
And here its the problem. If #top_menu is visible so when i touch on .OpenTopMenu, #top_menu will hide then toggle to visible again. So i can't really hide #top_menu on touching the menu button (.OpenTopMenu).
Can someone help me with this?
Thanks
Your touchend and click are basically doing the same thing. For mobile uses it's always good to know that a "click" can actually be seen as two events that rapidly follow each other, namely the "mousedown" and "mouseup" event, the last one triggering the "click". On mobile devices, the "click" is triggered at the same time as your "touchend". Now there's also an event called "touchstart" which is triggered when a user put's his / her finger on the glass.
You are right now wondering what all this has to do with your question. Well, it has to do with your document click..
Personally I would solve your problem in the following way;
var userClick = function(){
//you will need something that determines whether your user is
//using a mobile device or not.
return (Browser.isMobile)? "touchend" : "click";
};
var menu = {
isOnMenu:false,
isOnMenu_reset:null,
attachEvents:function(){
$('#top_menu').on('mouseenter',function(){
menu.isOnMenu = true;
}).on('mouseleave',function(){
menu.isOnMenu = false;
}).on('touchstart',function(){
clearTimeout(menu.isOnMenu_reset);
menu.isOnMenu = true;
}).on('touchend',function(){
menu.isOnMenu_reset = setTimeout(function(){
menu.isOnMenu = false;
},30);
});
$('.OpenTopMenu').on(userClick(),function(){
$("#top_menu").slideToggle("fast");
});
$(document).on(userClick(),function(){
if(!menu.isOnMenu){
$('#top_menu').slideToggle("fast");
}
});
},
init:function(){
menu.attachEvents();
}
};
$(function(){
menu.init();
});
Try to change your $(document).click() by somthing like $(".OpenTopMenu").blur(). This might not work with old browsers.
I only wanted click and touched for testing purpose.
But it only have to work with touchend. This is the working code that i finally use. Thanks.
$(document).ready(function(){
$(".OpenTopMenu").click(function(){
$("#top_menu").slideToggle("fast");
});
});
$(document).on("touchend", function(event){
var $trigger = $(".OpenTopMenu");
if($trigger !== event.target && !$trigger.has(event.target).length){
$("#top_menu").slideUp("fast");
}
});
I tried earlier with
!event.target.hasClass('OpenTopMenu') instead of $trigger !== event.target
in the if condition but it doesn't work. Can someone tell me why the upper code work and this one not?

Jquery click event not working on mobile device

I am trying to make the below JSFiddle work for tablet/mobile devices (e.g. 'on touch' as well as 'click').
https://jsfiddle.net/lkw274/7zt1zL0g/87/
<div class="user-navigation">
<a class="mobile-menu-new" href=""><span></span>Menu</a>
</div>
$(document).ready(function() {
$(".user-navigation a.mobile-menu-new").click(function (e) {
e.preventDefault();
$(".user-navigation a.mobile-menu-new").toggleClass("current");
});
});
.current { background: #F00;}
Expected behaviour:
On clicking 'Menu', either by touch or with clicked with mouse, the background is highlighted red until it is clicked again when the class should be removed, removing the red background and returning it to its original state.
Current behaviour:
On clicking 'Menu', by touch on mobile/tablet device, the background is highlighted red however the class is not removed when 'menu' is clicked for the second time.
Could anyone help to understand how this code needs to be modified for tablet/mobile devices?
I have tried the solution in the below StackOverflow link however this did not function on click once implemented.
document-click-function-for-touch-device
Thanks in advance.
Looks like event delegation is the way to do this since, when you modify the target element, bind seems to fail.
Try the following (works on my iPhone/Chrome).
$(document).ready(function() {
$(".user-navigation").delegate("a.mobile-menu-new", "click", function (e) {
e.preventDefault();
$(this).toggleClass("current");
});
});
Please note I have used .delegate since you seem to be using jQuery 1.6 (as per your fiddle) as otherwise, with jQuery 1.7+, you could use .on like below.
$(document).ready(function() {
$(".user-navigation").on("click", "a.mobile-menu-new", function (e) {
e.preventDefault();
$(this).toggleClass("current");
});
});
add the cursor:pointer to the property of your class and it should work find in mobile
.user-navigation{
cursor:pointer
}
$(selector).bind("click touchstart", function(){
.......
});
Well, in modern jQuery versions, I suppose something like this:
$(document).on('click','selector', function(e){
e.preventDefault();
your code here
});
...would do the trick for mobile devices...

JQuery mobile swipe to change pages

For the life of me I cannot figure out why I'm not able to change pages in my JQuery mobile document when I swipe right. I know the swipe event is written correctly because when I swap it out with and alert("test");that fires correctly.
Heres what I have done :
<script>
$(function() {
$('.table').on('swiperight', function(){
$.mobile.changePage("#home");
});
});
</script>
I've referred to the JQuery mobile documentation and to other posts here on the forum but have not been able to resolve this issue. Any ideas?
Heres a fiddle of the project. http://jsfiddle.net/a6TZW/
You don't need to wrap this event within $function() as such events are triggered once they occur.
Swipe events:
$(document).on('swiperight','.table', function()
{ $.mobile.changePage("#page2");
});
$(document).on('swipeleft','.table', function()
{ $.mobile.changePage("#page1");
});
Also, you can combine them this way:
$(document).on('swiperight swipeleft','.table', function(event) {
if (event.type == 'swiperight') {
$.mobile.changePage("#page2");
}
if (event.type == 'swipeleft') {
$.mobile.changePage("#page1");
}
});
JSfiddle: Test it here

Anchor "javascript:void(0)" causing window.onbeforeunload to fire on IE

I am using a drop down widget called Chosen which has an anchor with a href javascript:void(0). When I click on the drop down it works but on IE it fires a new onbeforeunload event which is frustrating because the application confirms if you want to leave. And obviously you don't want to have those questions when you are inputting form data.
Is there a way to get rid of this problem without altering Chosen library?
Unfortunately this:
window.onbeforeunload = function (e) {
console.log(window.location);
};
Does not log javascript:void(0) either, so, I can't use it to check the target URL.
This behavior occurs in IE9 at least, and that's what I'm concerned (not the older IEs).
The only solution I can see is to add returning of false to the onclick event handler of the links. It will tell IE that you're not planning to change the page by clicking on the link.
Link
The same can be written this way:
<script>
function doSomething() {
// do Something
return false;
}
</script>
Link
I ended up listening to click events against the anchor and cancel the event to prevent onBeforeUnload from firing:
$chosen.find('.chzn-single').click(function() {
return false;
});
I know that this is pretty old...But I have come across this recently for my work. We are unfortunately still forced to support IE9. We are using Angular.js on this project that will dynamically load new content onto a page when the user clicks on an anchor tag with a data-ng-click.
In your example all you would have to do is pass the event and within the function prevent the default action and stop it from bubbling up. To do this all you would have to do is this:
// Inside the HTML
{...}
Link
{...}
<script>
function doSomething(evt) {
evt.preventDefault();
evt.stopPropagation();
// Do Something
};
</script>
{...}
In Angular all I did was the following:
// Inside the View
Add Stuff
// Inside the controller
function addStuff($event) {
$event.preventDefault();
$event.stopPropagation();
// Do Something
};
I hope that this isn't too late and I hope that it helps others.
Had the same problem. Just found your question. My solution is, you need to add onclick attribute to every chosen dropdown list anchor tag and call window.onbeforeunload = null
In my case, I've put
$(".chzn-single").attr("onclick", "window.onbeforeunload = null;");
After setting up chosen library and it works fine
don't use href's for this. A simple solution with minimal extra work:
i prefer to use a CSS class that simulates an href, obviously you will change the color and styling of this class to fit your website, but for this purposes, it's the standard blue underlined link
<style>
.linkSimulate
{
cursor: pointer;
COLOR: blue;
text-decoration: underline;
}
</style>
then use a simple anchor
<a onclick = "do_save();" class ="linkSimulate">Link</a>
Even if this question is old, i've anhanced the answer of #Bartosz, fixing the issue in the comment of #Oiva Eskola:
Wouldn't this prevent the window.onbeforeunload from working after clicking a chosen link element? – var thisOnClick;
Below is my solution to properly create the HTML onclick property, to not override or cancel the event:
var thisOnClick;
$.each( $(' .container a '), function(){
thisOnClick = $(this).attr('onclick');
if ( typeof thisOnClick == 'undefined' ) {
$(this).attr('onclick', 'window.onbeforeunload = null;');
} else if ( typeof thisOnClick == 'string' && thisOnClick.indexOf('window.onbeforeunload') == -1 ) {
$(this).attr('onclick', thisOnClick + 'window.onbeforeunload = null;');
}
});

css pointer-events property change and respective jquery events not triggering together

Here is my code segment. I am using iscroll 4 for scroll in touch devices and desktop.
$('#next_item').bind('mousedown touchstart',function (e) {
//do something onclick
$(this).bind('mousemove touchmove',function(e){ //triggers only when i drag over it
dragstart = true;
$(this).css('pointer-events', 'none');
myScroll._start(myDown);
return;
});
});
$('#next_item').bind('mouseup touchend',function (e) {
if(dragstart) {
dragstart = false;
$(this).css('pointer-events', 'auto');
}
});
I have the click event on #next_item which does a specific task and also have the drag event on #next_item which does different task. Now the problem is when #next_item receives drag event the css pointer-events is changed to none immediately but the drag is not triggering. When i do mouseup and then again drag from over #next_item then only the drag is triggered. I need the css pointer-events to pass drag event to the underlying element. Please suggest if i am doing anything wrong. Without pointer-events iscroll gives error while passing the drag event below #next_item
When you want to disable the pointer event for an element with .css():
$('#element_id').css('pointer-events','none');
When you want to enable the pointer event for an element with .css():
$('#element_id').css('pointer-events','');
In #1, the element gets disabled and then you cannot access that element.
In #2, the same element gets enabled and you can perform other jQuery operation on it.
I've had better luck using the methods provided with iScroll rather than rolling my own. Specifically, onBeforeScroll and onScrollEnd.
var myScroll;
function loaded() {
myScroll = new iScroll('scroller-parent', {
onBeforeScrollStart: function () {
$('#scroller').css('opacity',0.5); // just for a visual ref
return false;
},
onScrollEnd: function () {
alert('done');
$('#scroller').css('opacity',1);
}
});
}
document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
document.addEventListener('DOMContentLoaded', function () { setTimeout(loaded, 200); }, false);
Also, the inclusion of the listeners for touch and the DOM help. Wish I knew exactly what you were trying to do - might be able to show you a better example.
If I'm way off, I'll pull this answer. BTW, jQ 1.6.4 working fine for this answer.
HTH
Include the following <script> in your page:
HTML
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.17/jquery-ui.min.js"></script>
<script src="jquery.ui.touch-punch.min.js"></script>
<script>
$(document).ready(function () {
$('#widget').draggable(); // This is required for drag...
$('#widget').dialog().addTouch();
// Here you call your functions and perform
// the functionality for touch and drag...
});
</script>
</head>
<body>
<div id="widget" style="width:200px; height:200px border:1px solid red" ></div>
</body>
It is just an example, as I am completely unaware of what functionality you want from your code snippet. It may not answer your entire question, but this is the logical flow required to solve the problem.

Categories