How to prevent a jQuery Mobile collapsible from expanding? - javascript

I'm working with the JQM collapsibleset widget.
I need one collapsible to just be a button (that allows to add more elements to the set/accordeon), so when it's clicked, it should NOT expand (or collapse).
I'm using the following code to no avail:
$("div.ui-dynamic-tabs div.tab_add").on("collapsiblebeforeexpand", function (e) {
e.stopPropagation();
e.stopImmediatePropagation();
e.preventDefault();
return false;
console.log("foo");
});
with both the collapsibleexpand and the collapsiblebeforeexpand custom event I added to JQM to test whether this would help.
I can register all events and returning false also does prevent the console from being triggered. However... the collapsible still expands... :-(
I thought adding a beforeexpand event would prevent the subsequent code inside JQM to run when calling preventDefault on the event, but it still executes.
Question:
How do I stop the collapsible from expanding correctly by prevent execution of an event triggered before the expanding javascript is run?
PS: I'm also tagging with jQueryUI because both JQM and UI use the same widget factory and event mechanisms.

In jQuery Mobile 1.3.2, that event is called collapsibleexpand, and its default behavior can indeed be prevented.
You only have to write:
$("div.ui-dynamic-tabs div.tab_add").on("collapsibleexpand", function(e) {
e.preventDefault();
});

Here is the solution from JQM on Github:
$.widget( "mobile.collapsible", $.mobile.collapsible, {
_handleExpandCollapse: function( isCollapse ) {
if ( this._trigger( "collapsiblebefore" +
( isCollapse ? "collapse" : "expand" ) ) ) {
this._superApply( arguments );
}
}
});

As per frequent's answer, this is a modification that suits JQM 1.4:
$.widget('mobile.collapsible', $.mobile.collapsible, {
_handleExpandCollapse: function(isCollapse) {
if (this._trigger('before' + (isCollapse ? 'collapse' : 'expand'))) {
this._superApply(arguments);
}
}
});
Bind the event:
$('#mycollapsible div').on('collapsiblebeforeexpand', function(event, ui) {
if (someCondition)
event.preventDefault(); // prevent node from expanding
});

Related

Triggered click don't work propertly [duplicate]

I'm having a hard time understand how to simulate a mouse click using JQuery. Can someone please inform me as to what i'm doing wrong.
HTML:
<a id="bar" href="http://stackoverflow.com" target="_blank">Don't click me!</a>
<span id="foo">Click me!</span>
jQuery:
jQuery('#foo').on('click', function(){
jQuery('#bar').trigger('click');
});
Demo: FIDDLE
when I click on button #foo I want to simulate a click on #bar however when I attempt this, nothing happens. I also tried jQuery(document).ready(function(){...}) but without success.
You need to use jQuery('#bar')[0].click(); to simulate a mouse click on the actual DOM element (not the jQuery object), instead of using the .trigger() jQuery method.
Note: DOM Level 2 .click() doesn't work on some elements in Safari. You will need to use a workaround.
http://api.jquery.com/click/
You just need to put a small timeout event before doing .click()
like this :
setTimeout(function(){ $('#btn').click()}, 100);
This is JQuery behavior. I'm not sure why it works this way, it only triggers the onClick function on the link.
Try:
jQuery(document).ready(function() {
jQuery('#foo').on('click', function() {
jQuery('#bar')[0].click();
});
});
See my demo: http://jsfiddle.net/8AVau/1/
jQuery(document).ready(function(){
jQuery('#foo').on('click', function(){
jQuery('#bar').simulateClick('click');
});
});
jQuery.fn.simulateClick = function() {
return this.each(function() {
if('createEvent' in document) {
var doc = this.ownerDocument,
evt = doc.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, doc.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
} else {
this.click(); // IE Boss!
}
});
}
May be useful:
The code that calls the Trigger should go after the event is called.
For example, I have some code that I want to be executed when #expense_tickets value is changed, and also, when page is reload
$(function() {
$("#expense_tickets").change(function() {
// code that I want to be executed when #expense_tickets value is changed, and also, when page is reload
});
// now we trigger the change event
$("#expense_tickets").trigger("change");
})
jQuery's .trigger('click'); will only cause an event to trigger on this event, it will not trigger the default browser action as well.
You can simulate the same functionality with the following JavaScript:
jQuery('#foo').on('click', function(){
var bar = jQuery('#bar');
var href = bar.attr('href');
if(bar.attr("target") === "_blank")
{
window.open(href);
}else{
window.location = href;
}
});
Try this that works for me:
$('#bar').mousedown();
Technically not an answer to this, but a good use of the accepted answer (https://stackoverflow.com/a/20928975/82028) to create next and prev buttons for the tabs on jQuery ACF fields:
$('.next').click(function () {
$('#primary li.active').next().find('.acf-tab-button')[0].click();
});
$('.prev').click(function () {
$('#primary li.active').prev().find('.acf-tab-button')[0].click();
});
I have tried top two answers, it doesn't worked for me until I removed "display:none" from my file input elements.
Then I reverted back to .trigger() it also worked at safari for windows.
So conclusion, Don't use display:none; to hide your file input , you may use opacity:0 instead.
Just use this:
$(function() {
$('#watchButton').trigger('click');
});
You can't simulate a click event with javascript.
jQuery .trigger() function only fires an event named "click" on the element, which you can capture with .on() jQuery method.

Onsen UI Navigator prevent double click

I have an on-list with items that I allow users to click on. Clicking on an item takes the user to a details page. If you click fast enough it's possible that two click events get fired taking the user to one details page, then another. Is there a way to prevent this? For example can you tell the navigator to not to push another page until the navigation is complete?
Here is my code called after the list has been populated, assigning the click event:
$( '#myList .item', this ).on( 'click', function() {
navi.pushPage( "details.html" ) );
});
To disable this behaviour you can currently pass {cancelIfRunning: true} as a second argument to navi.pushPage. We are planning on making this the default behaviour soon, which is why it's an undocumented setting, but until then you can just call it explicitly.
navi.pushPage('details.html', {cancelIfRunning: true});
As Fran Dios mentioned - there was an issue with this setting, but it should already be fixed in beta 6.
So as long as you are using OnsenUI beta 6 or higher you should have no problems with this setting turned on. Otherwise you can use Zakaria Acharki's solution.
Try to prevent the double click by adding preventDefault() in dbclick event attached to the list items :
$( '#myList .item', this ).on( 'dbclick', function(e) {
e.preventDefault();
});
Or you could disable the list items for a while after click to prevent the fast double click on different items :
//Example of disabling list for 1 second after click
$( '#myList .item', this ).on( 'click', function(e) {
e.preventDefault();
navi.pushPage( "details.html" ) );
$('#myList .item').prop('disabled', true);
setTimeout(function(){
$( '#myList .item').prop('disabled', false);
}, 1000);
});
Hope this helps.

How can I return a href link to it's default behavior after using e.preventDefault();?

I updated my code and rephrased my question:
I am trying to create the following condition. When a link with an empty href attribute (for example href="") is clicked, a modal is launched and the default behavior of that link is prevented..
But when the href attribute contains a value (href="www.something.com") I would like for the link to work as it normally does using its default behavior.
For some reason my code isn't working. Any help is appreciated.
// Semicolon (;) to ensure closing of earlier scripting
// Encapsulation
// $ is assigned to jQuery
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('.launch').bind('click', function(e) {
var attrId = $(this).attr('attrId');
if( $('.launch').attr('href') == '') {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('div[attrId="' + attrId+'"]').bPopup({
//position: ['auto', 'auto'], //x, y
appendTo: 'body'
});
} else {
$(this).removeAttribute('attrId');
return true;
}
});
});
})(jQuery);
Your jQuery is... very wrong. $('href').attr('') is getting the empty attribute from an element <href>... Did you mean:
if( $(this).attr('href') == '')
A few things: event is undefined, as your event object is simply called e. Secondly, e.stopPropagation(); will not do what you want. stopPropagation simply prevents parent events from firing (eg: clicking a <td> will also fire click on the containing <tr> unless stopped).
Try just replacing your else statement with
return true;
Also your jQuery is incorrect (as stated in the other answer here).
This answer may help as well:
How to trigger an event after using event.preventDefault()
Good luck!

disable mouseenter on menu-aim

Using menu-aim:
https://github.com/hfknight/jQuery-menu-aim/blob/master/jquery.menu-aim.js
Having an issue going responsive with it. It uses mouseenter and I need to disable mousenter on with a click.function() {}. If you view the the code in the plugin (above) at the bottom you see these events:
$menu
.mouseleave(mouseleaveMenu)
.find(options.rowSelector) // here
.mouseenter(mouseenterRow) // and here
.mouseleave(mouseleaveRow)
.click(clickRow);
$(document).mousemove(mousemoveDocument);
I want to disable the mouseover event in this .click(function (){})
$('[data-toggle="offcanvas"]').click(function () {
});
Here is an incorrect code so you get a better understanding of what I am trying to achieve:
$('[data-toggle="offcanvas"]').click(function () {
$(".dropdown-menu").menuAim({
activate: function(){disable mouseenter here }
});
});
TL;DR
Didn't quite understand but this way you can off any event. You may give it a try:
// For all elements with an identifier
function(){ $('elementIdOrClass').off('mouseenter'); }
// For current element only
function(){ $(this).off('mouseenter'); }
Also you may use unbind('mouseenter').

How to set the focus for a particular field in a Bootstrap modal, once it appears

I've seen a couple of questions in regards to bootstrap modals, but none exactly like this, so I'll go ahead.
I have a modal that I call onclick like so...
$(".modal-link").click(function(event){
$("#modal-content").modal('show');
});
This works fine, but when I show the modal I want to focus on the first input element... In may case the first input element has an id of #photo_name.
So I tried
$(".modal-link").click(function(event){
$("#modal-content").modal('show');
$("input#photo_name").focus();
});
But this was to no avail. Lastly, I tried binding to the 'show' event but even so, the input won't focus. Lastly just for testing, as I had a suspiscion this is about the js loading order, I put in a setTimeout just to see if I delay a second, will the focus work, and yes, it works! But this method is obviously crap. Is there some way to have the same effect as below without using a setTimeout?
$("#modal-content").on('show', function(event){
window.setTimeout(function(){
$(event.currentTarget).find('input#photo_name').first().focus()
}, 0500);
});
Try this
Here is the old DEMO:
EDIT:
(Here is a working DEMO with Bootstrap 3 and jQuery 1.8.3)
$(document).ready(function() {
$('#modal-content').modal('show');
$('#modal-content').on('shown', function() {
$("#txtname").focus();
})
});
Starting bootstrap 3 need to use shown.bs.modal event:
$('#modal-content').on('shown.bs.modal', function() {
$("#txtname").focus();
})
Just wanted to say that Bootstrap 3 handles this a bit differently. The event name is "shown.bs.modal".
$('#themodal').on('shown.bs.modal', function () {
$("#txtname").focus();
});
or put the focus on the first visible input like this:
.modal('show').on('shown.bs.modal', function ()
{
$('input:visible:first').focus();
})
http://getbootstrap.com/javascript/#modals
I am using this in my layout to capture all modals and focus on the first input
$('.modal').on('shown', function() {
$(this).find('input').focus();
});
I had the same problem with bootstrap 3, focus when i click the link, but not when trigger the event with javascript.
The solution:
$('#myModal').on('shown.bs.modal', function () {
setTimeout(function(){
$('#inputId').focus();
}, 100);
});
Probably it´s something about the animation!
I had problem to catch "shown.bs.modal" event.. And this is my solution which works perfect..
Instead simple on():
$('#modal').on 'shown.bs.modal', ->
Use on() with delegated element:
$('body').on 'shown.bs.modal', '#modal', ->
Seems it is because modal animation is enabled (fade in class of the dialog), after calling .modal('show'), the dialog is not immediately visible, so it can't get focus at this time.
I can think of two ways to solve this problem:
Remove fade from class, so the dialog is immediately visible after calling .modal('show'). You can see http://codebins.com/bin/4ldqp7x/4 for demo. (Sorry #keyur, I mistakenly edited and saved as new version of your example)
Call focus() in shown event like what #keyur wrote.
I've created a dynamic way to call each event automatically. It perfect to focus a field, because it call the event just once, removing it after use.
function modalEvents() {
var modal = $('#modal');
var events = ['show', 'shown', 'hide', 'hidden'];
$(events).each(function (index, event) {
modal.on(event + '.bs.modal', function (e) {
var callback = modal.data(event + '-callback');
if (typeof callback != 'undefined') {
callback.call();
modal.removeData(event + '-callback');
}
});
});
}
You just need to call modalEvents() on document ready.
Use:
$('#modal').data('show-callback', function() {
$("input#photo_name").focus();
});
So, you can use the same modal to load what you want without worry about remove events every time.
I had the same problem with the bootstrap 3 and solved like this:
$('#myModal').on('shown.bs.modal', function (e) {
$(this).find('input[type=text]:visible:first').focus();
})
$('#myModal').modal('show').trigger('shown');
Bootstrap has added a loaded event.
https://getbootstrap.com/docs/3.3/javascript/#modals
capture the 'loaded.bs.modal' event on the modal
$('#mymodal').on('loaded.bs.modal', function(e) {
// do cool stuff here all day… no need to change bootstrap
})
Bootstrap modal show event
$('#modal-content').on('show.bs.modal', function() {
$("#txtname").focus();
})
A little cleaner and more modular solution might be:
$(document).ready(function(){
$('.modal').success(function() {
$('input:text:visible:first').focus();
});
});
Or using your ID as an example instead:
$(document).ready(function(){
$('#modal-content').modal('show').success(function() {
$('input:text:visible:first').focus();
});
});
Hope that helps..

Categories

Resources