I want to produce a manual tooltip based upon some user input. The easiest way was to hide all tooltips and then show the relevent ones.
I've reduced my code down to the bare essentials, and my tooltip keeps disappearing after the second "show".
I'm using bootstrap 3.3.4 and jquery 2.1.3
Is there a problem with doing a show immediatly after a hide or am I missing something in my code?
<input id="check" type="checkbox">
<script>
var toolTipData = {
placement: 'right',
title: 'Checkmark checked',
trigger: "manual"
};
$('#check').tooltip(toolTipData);
$(document).on('change', '#check', function () {
$('#check').tooltip("hide");
if (document.getElementById("check").checked) {
$('#check').tooltip("show");
}
});
</script>
Here's a jsfiddle: https://jsfiddle.net/bbrally/4b9g0abh/
You're experiencing a race condition between when the "hide" event happens and when the "show" event happens. Per the documentation the "hide/show" events actually return to the caller before the "hidden/shown" events fire.
http://getbootstrap.com/javascript/#tooltips
Scroll down to the "Methods" section under tooltips
...Returns to the caller before the tooltip has actually been hidden...
...Returns to the caller before the tooltip has actually been shown...
I'm not suggesting the code below is a solution (though, it might be good enough?), but an explanation as to what you're running into. Specifically the timeout value of 250ms will slow it down enough such that it works as you're intending.
var toolTipData = {
placement: 'right',
title: 'Checkmark checked',
trigger: "manual"
};
$('#check').tooltip(toolTipData);
$(document).on('change', '#check', function () {
$('#check').tooltip("hide");
if (document.getElementById("check").checked) {
setTimeout(function() {
$('#check').tooltip("show");
}, 250);
}
});
Hope this helps.
$(document).on('change', '#check', function () {
if (document.getElementById("check").checked) {
$('#check').tooltip("show");
}
else{
$('#check').tooltip("hide");
}
});
It was trying to hide, even though it shouldn't, separate both cases.
I am building a site for both mobile/touch devices as well as desktop non-touch devices.
To help with eliminating the 300ms delay on jQuery .click events for touch devices I am using the tappy library, which works beautifully.
https://github.com/filamentgroup/tappy
That being said, I only want to bind this 'tap' event where necessary and want to bind a regular .click event if the device is non-touch. I know tappy's 'tap' event will fire for non-touch devices, but I'd rather only use it where necessary since there are a few quirks documented.
Up to now I have been writing switch functions each time I want to do this, which looks like this:
if ($('html').hasClass('no-touch')) {
$('.sidebar').find('.strip').find('.explore-wrapper').click(function() {
$(this).closest('.sidebar').addClass('active');
});
} else {
$('.sidebar').find('.strip').find('.explore-wrapper').bind('tap', function() {
$(this).closest('.sidebar').addClass('active');
});
}
I'd like to extend jQuery and write my own version of .click, maybe called 'tapClick' so that my code could function like:
$('.sidebar').find('.strip').find('.explore-wrapper').tapClick(function() {
$(this).closest('.sidebar').addClass('active');
});
I started to try and write my own extension, but couldn't get it...any help would be appreciated:
// Custom tap/click bind
$.extend({
tapClick : function(callbackFnk) {
if ($('html').hasClass('touch')) {
$(this).bind('tap', function() {
if(typeof callbackFnk == 'function') {
callbackFnk.call(this);
}
});
} else {
$(this).click(function() {
if(typeof callbackFnk == 'function') {
callbackFnk.call(this);
}
});
}
}
});
Try substituting jQuery.fn.extend() for jQuery.extend()
e.g.,
$.extend({tapClick:function() {console.log(this)}});
$.fn.extend({tapClick:function() {console.log(this)}});
$.tapClick(); // function (a,b){return new e.fn.init(a,b,h)}
$("html").tapClick(); // [html, ...]
$.extend({tapClick:function() {console.log(this)}});
$.fn.extend({tapClick:function() {console.log(this)}});
$.tapClick();
$("html").tapClick();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
This is the code that I ended up using that solves the problem.
$.fn.extend({
tapClick:function(callback) {
if ($('html').hasClass('touch')) {
return $(this).click(callback);
} else {
return $(this).bind('tap', callback);
}
}
});
I'm using this plugin grid system with drag and drop functionality:
https://github.com/McPants/jquery.shapeshift.
You can call the shapeshift function and pass it the parameters to enable and disable the drag and drop functionality.
$(".container").shapeshift({
enableDrag: true,
});
I want to be able to turn on and off this feature. I used this code:
var dragState = 0;
$(".switch").on("click", function() {
if(dragState == 0) {
options = {
enableDrag: true,
}
dragState = 1;
} else {
options = {
enableDrag: false,
}
dragState = 0;
}
$(".container").shapeshift(options);
});
When I run this code I can turn on drag and drop but not back off again.
Does anyone have any suggestions or experience with this plugin?
Use http://mcpants.github.io/jquery.shapeshift/ as a reference.
Basicaly all you need to do is:
$(function(){
var sso = {
minColumns: 3,
enableDrag: false
};
var ss = $(".container").shapeshift(sso);
$('button').click(function () {
sso.enableDrag = true;
ss.trigger('ss-destroy');
ss.shapeshift(sso);
});
});
I simplified the example to show what needs to be done in this fiddle:
http://jsfiddle.net/carisch19/hDm4e/2/
Added enable and disable buttons:
http://jsfiddle.net/carisch19/hDm4e/4/
Sorry for answering on such an old question but i was just going through shapeshift.js and understand that for disabling drag and drop we can destroy it but not in such a long way and there is no need to take it to variable.
Hope you will interested in this short way and update your codes.
Below is the code
$('div').trigger("ss-destroy");
Above code is sufficient for destroying and also a very clean and convenient way according to me.
Try once!
I want to toggle functions using the jQuery waypoint function, how can I combine these pieces of code to make that happen? (I would be happy with alternative solutions too).
I want to combine this.....
$('#pageborder').waypoint(function(direction) {
//do something here
}, { offset: 'bottom-in-view' });
With this......
.toggle(function(){
$('.play', this).removeClass('pausing');
$('.play', this).addClass('playing');
}, function(){
$('.play', this).addClass('pausing');
$('.play', this).removeClass('playing');
});
The end result should be functions getting toggled when the way point is reached.
More info on the JQuery Waypoint plugin here: http://imakewebthings.com/jquery-waypoints/#doc-waypoint
Here is an example of using the waypoint plugin to do something when the waypoint is reached. In my example I am showing and hiding something based on if the user is scrolling up or down:
Demo: http://jsfiddle.net/lucuma/pTjta/
$(document).ready(function () {
$('.container div:eq(1)').waypoint(function (direction) {
if (direction == 'down') $('.toggleme').show();
else {
$('.toggleme').hide();
}
}, {
offset: $.waypoints('viewportHeight') / 2
});
});
E.B.D., I see you have something working.
If you wanted a slightly more concise toggle action, then you might consider the following :
var $next_btn_containers = $('.next_btn_container, .next_btn_container_static');
$('#pageborder').waypoint(function(dir) {
$next_btn_containers
.toggleClass('next_btn_container_static', dir == 'down')
.toggleClass('next_btn_container', dir == 'up');
}, { offset: 'bottom-in-view' });
By pre-selecting and remembering all members of both classes, execution will be faster - particularly in a large DOM.
The original selector may well simplify, depending on how the elements are initialized.
With a little more thought (and appropriate adjustment of style-sheet directives), then you may be able to simplify things even further by toggling a single "static" class :
var $next_btn_containers = $('.next_btn_container');
$('#pageborder').waypoint(function(dir) {
$next_btn_containers.toggleClass('static', dir == 'down')
}, { offset: 'bottom-in-view' });
.next_btn_container would thus remain a reliable selector (for other purposes), regardless of the statc/non-static state of the element(s).
Note: Unlike the first version (and your own code), this will not handle two sets of elements toggling in anti-phase, if that's what you have.
I used this code to make it work, thanks to lucuma for pointing me in the right direction!
$('#pageborder').waypoint(function(direction) {
if (direction == 'down') $('.next_btn_container').removeClass('next_btn_container').addClass('next_btn_container_static');
else {
$('.next_btn_container_static').removeClass('next_btn_container_static').addClass('next_btn_container');
}
}, { offset: 'bottom-in-view' });
Looked around quite a bit, and can't seem to find a JQuery solution (maybe its just a limitation of JavaScript) for this:
<a href="somelink.php"
onclick="return confirm('Go to somelink.php?');">Click Here</a>
In the above example, when a user clicks on the link, it will only go to its href if the user clicks OK in the confirm box.
What I am trying to do is get a more modern look using a popup div. Perhaps something like this:
<a href="somelink.php"
onclick="return jq_confirm('Go to somelink.php?');">Click Here</a>
(Where jq_confirm is a custom JQuery confirm function that pops up a nice div with a YES/NO or OK/CANCEL button pair).
However, I cannot seem to find any such thing.
I have looked at some JQuery widget libraries etc which offer similar functionality, but none will wait for the response from the user (at least, not in the scenario described above), but instead they just proceed and take the user to the link (or run any JavaScript embedded in the href='' piece of the link). I suspect this is because while you can attach a callback function to many of these widgets to return a true/false value, the onclick event does not wait for a response (callbacks are asynchronous), thereby defeating the purpose of the confirm box.
What I need is the same kind of halt-all-javascript (modal) functionality that the default confirm() command provides. Is this possible in JQuery (or even in JavaScript)?
As I am not an expert in JavaScript nor in JQuery, I defer to you gurus out there. Any JQuery (or even pure JavaScript) solution is welcome (if possible).
Thanks -
I just had to solve the same problem. I wound up using the dialog widget from JQuery UI. I was able to implement this without using callbacks with the caveat that the dialog must be partially initialized in the click event handler for the link you want to use the confirmation functionality with (if you want to use this for more than one link). This is because the target URL for the link must be injected into the event handler for the confirmation button click.
Here's my solution, abstracted away to be suitable for an example. I use a CSS class to indicate which links should have the confirmation behavior.
<div id="dialog" title="Confirmation Required">
Are you sure about this?
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true
});
$(".confirmLink").click(function(e) {
e.preventDefault();
var targetUrl = $(this).attr("href");
$("#dialog").dialog({
buttons : {
"Confirm" : function() {
window.location.href = targetUrl;
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#dialog").dialog("open");
});
}); // end of $(document).ready
</script>
<a class="confirmLink" href="http://someLinkWhichRequiresConfirmation.com">Click here</a>
<a class="confirmLink" href="http://anotherSensitiveLink">Or, you could click here</a>
Check out http://www.84bytes.com/2008/06/02/jquery-modal-dialog-boxes/
They have a good variety of modal-boxes for JQuery.
I think you should see http://www.ericmmartin.com/simplemodal/
A modal dialog override of the JavaScript confirm function. Demonstrates the use of onShow as well as how to display a modal dialog confirmation instead of the default JavaScript confirm dialog.
Did you see the jQuery Modal Dialog on jQuery UI site?
Modal Confirmation Dialog demo
I blogged about the solution to this issue here: http://markmintoff.com/2011/03/asp-net-jquery-confirm-dialog/
Even though the article is geared towards ASP.Net it can be easily adapted to php. It relies on preventing the click with a return false and when the user clicks "OK" or "YES" or what-have-you; the link or button is simply clicked again.
var confirmed = false;
function confirmDialog(obj)
{
if(!confirmed)
{
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Yes": function()
{
$( this ).dialog( "close" );
confirmed = true; obj.click();
},
"No": function()
{
$( this ).dialog( "close" );
}
}
});
}
return confirmed;
}
Give it a try and let me know what you think. I hope this solves your problem.
You should be able to override the standard window.confirm function be writing the following code.
window.confirm = modalConfirm
then you will need to make a function like this
function modalConfirm(message){
// put your code here and bind "return true/false" to the click event
// of the "Yes/No" buttons.
}
This should work, although I haven't tested it yet. I am going to do exactly this right now and will let you all know how it worked.
Edit:
I have tested my example above now and it was not possible, you will have to pass in a callback function to your overwritten confirm function like this:
function modalConfirm(message, callback){
...
$("button.yes").click(function(){
callback(result);
});
...
}
..making your call to the function look like this:
confirm("Are you sure?", function(result){
alert(result);
});
In other words, it is not possible to completely override the default window.confirm function without causing a nasty loop that causes the browser to hang. I think that you will have to modify your confirm calls like above.
Since this question seems to be missing the canonical answer: there is no way to programatically pause (and resume) javascript execution like alert or confirm do.
That being said, relying on this behaviour today is usually considered bad practice given the single threaded nature of javascript, and the reason why the aforementioned functions do pause execution is probably because they were designed when the web was still at a very early stage, and later left unchanged to ensure compatibility. Since the focus nowadays is in writing as much non-blocking js code as possible, it's unlikely the functionality to programmatically halt js will ever make it to any future specification of ECMAScript, so your best bet is to rework your site to make sure confirm and alert dialogs can co-exist with other javascript code running in the background.
My way around this problem was to add some arbitrary data to the object, and check for that data on click. If it existed, proceed with the function as normal, otherwise confirm with a yes/no (in my case using a jqtools overlay). If the user clicks yes - insert the data in the object, simulate another click and wipe the data. If they click no, just close the overlay.
Here is my example:
$('button').click(function(){
if ($(this).data('confirmed')) {
// Do stuff
} else {
confirm($(this));
}
});
And this is what I did to override the confirm function (using a jquery tools overlay):
window.confirm = function(obj){
$('#dialog').html('\
<div>\
<h2>Confirm</h2>\
<p>Are you sure?</p>\
<p>\
<button name="confirm" value="yes" class="facebox-btn close">Yes</button>\
<button name="confirm" value="no" class="facebox-btn close">No</button>\
</p>\
</div>').overlay().load();
$('button[name=confirm]').click(function(){
if ($(this).val() == 'yes') {
$('#dialog').overlay().close();
obj.data('confirmed', true).click().removeData('confirmed');
} else {
$('#dialog').overlay().close();
}
});
}
I have a solution that can be used to replace the default window.confirm function. It doesn't require you overriding window.confirm as that is not fully possible.
My solution allows you to have a general class like me, let's say 'confirm-action' that you place on any element that requires a confirmation before being processed. The script is very simple and utilizes jQuery, jQuery UI Dialog and no other plugins.
You can find the complete demo of the implementation on jsFiddle, http://jsfiddle.net/74NDD/39/.
Usage:
Add this javascript code in your html head or before any other click
binding you have in your javascript.
$("#dialog:ui-dialog").dialog("destroy");
$('.confirm-action').live('click', function(e) {
$self = $(this);
if (e && e.stopImmediatePropagation && $self.data('confirmed') !== true) {
e.stopImmediatePropagation();
$('#confirm-action-dialog').dialog({
height: 110,
modal: true,
resizable: false,
draggable: false,
buttons: {
'Yes': function() {
$(this).dialog('close');
$self.data('confirmed', true);
$self.click();
},
'No': function() {
$self.data('confirmed', false);
$(this).dialog('close');
}
}
});
} else if ($self.data('confirmed') === true) {
e = window.event;
e.cancelBubble = false;
$self.data('confirmed', false);
}
return false;
});
Place this html somewhere in the body (it is hidden by default).
<div style="display:none;" id="confirm-action-dialog" title="Confirm Action?">
<p>
<span class="ui-icon ui-icon-alert"></span>
Are you sure you want to continue?
</p>
</div>
Put the class 'confirm-action' on any element that requires confirmation.
confirm-action
This solution works perfect as it does not alter jQuery event bubbling, it merely pauses (stops) all other events until the user decides what they want to do.
I hope this is helpful for someone else as I was unable to find any other solution that doesn't require me installing another jQuery plugin or do some other hack.
Building on top of Banu's solution (thanks a ton!) to make it a one pop solution on top of each page. Paste this code inside:
$(document).ready
And add "confirmLinkFollow" class to all links you want confirmed:
$(".confirmLinkFollow").click(function(e) {
e.preventDefault();
var targetUrl = $(this).attr("href");
var $dialog_link_follow_confirm = $('<div></div>').
html("<p>Are you sure?</p>").
dialog({autoOpen: false,
title: 'Please Confirm',
buttons : {
"Confirm" : function() {
window.location.href = targetUrl;
},
"Cancel" : function() {
$(this).dialog("close");
}
},
modal: true,
minWidth: 250,
minHeight: 120
}
);
$dialog_link_follow_confirm.dialog("open");
});
Put the redirect inside the function like:
<script>
function confirmRedirect(url, desciption) {
if (confirmWindow(desciption)) {
window.location = url;
}
}
</script>
And call it like this:
Go!
Almost three years later, I am looking for something similar. Since I have not found an acceptable "quick" solution, I wrote something that comes very close to the criteria of the OP. I figure others may find it useful in the future.
JavaScript is event-driven and that means it does not support any sort of "wait" or "sleep" loop that we can use to pause a pure-javascript confirm function. The options involve burning processor cycles, using a browser plugin, or AJAX. In our increasingly mobile world, and with sometimes spotty internet connections, none of these are great solutions. This means that we have to return from our "confirm" function immediately.
However, since there is no "false" logic in the code snippet above (ie. nothing is done when the user clicks "Cancel"), we can trigger the "click" or "submit" event again when the user clicks "OK." Why not set a flag and react based on that flag within our "confirm" function?
For my solution, I opted to use FastConfirm rather than a "modal" dialog. You can easily modify the code to use anything you want but my example was designed to use this:
https://github.com/pjparra/Fast-Confirm
Due to the nature of what this does, I do not see a clean way to package it up. If you feel that this has too many rough edges, feel free to smooth them out or rewrite your code the way that everyone else has recommended:
/* This version of $.fn.hasEvent is slightly modified to provide support for
* the "onclick" or "onsubmit" tag attributes. I chose this because it was
* short, even if it is cryptic.
*
* Learn more about the code by Sven Eisenschmidt, which is licensed under
* the MIT and GPL at:
* http://github.com/fate/jquery-has-event
*/
(function($) {
$.fn.hasEvent = function(A, F, E) {
var L = 0;
var T = typeof A;
E = E ? E : this;
var V = (E.attr('on'+A) != undefined);
A = (T == 'string') ? $.trim(A) : A;
if (T == 'function')
F = A, A = null;
if (F == E)
delete(F);
var S = E.data('events');
for (e in S)
if (S.hasOwnProperty(e))
L++;
if (L < 1)
return V; // = false;
if (A && !F) {
return V = S.hasOwnProperty(A);
} else if(A && S.hasOwnProperty(A) && F) {
$.each(S[A], function(i, r) {
if(V == false && r.handler == F) V = true;
});
return V;
} else if(!A && F) {
$.each(S, function(i, s) {
if (V == false) {
$.each(s, function(k, r) {
if (V == false && r.handler == F)
V = true;
});
}
});
}
return V;
}
$.extend($, {hasEvent: $.fn.hasEvent});
}) (jQuery);
/* Nearly a drop-in replacement for JavaScript's confirm() dialog.
* Syntax:
* onclick="return jq_confirm(this, 'Are you sure that you want this?', 'right');"
*
* NOTE: Do not implement "false" logic when using this function. Find another way.
*/
var jq_confirm_bypass = false;
function jq_confirm(el, question, pos) {
var override = false;
var elem = $(el);
if ($.fn.fastConfirm == undefined) {
override = confirm(question);
} else if (!jq_confirm_bypass) {
if (pos == undefined) {
pos = 'right';
}
elem.fastConfirm({
position: pos,
questionText: question,
onProceed: function(trigger) {
var elem = $(trigger);
elem.fastConfirm('close');
if (elem.hasEvent('click')) {
jq_confirm_bypass = true;
elem.click();
jq_confirm_bypass = false;
}
if (elem.hasEvent('submit')) {
jq_confirm_bypass = true;
elem.submit();
jq_confirm_bypass = false;
}
// TODO: ???
},
onCancel: function(trigger) {
$(trigger).fastConfirm('close');
}
});
}
return override ? override : jq_confirm_bypass;
}
So... onclick="return confirm('Do you want to test this?');" would become onclick="return jq_confirm(this, 'Do you want to test this?');" The pos/"right" parameter is optional and is specifically for Fast-Confirm.
When you click, the jq_confirm() function will spawn the jQuery dialog and return "false." When the user clicks "OK" then jq_confirm() sets a flag, calls the original click (or submit) event, returns "true", then unsets the flag in case you want to remain on the same page.
The following link has a jQuery plugin for confirm boxes similar to constructing like confirm("something") in JavaScript
http://labs.abeautifulsite.net/archived/jquery-alerts/demo/