Bootstrap - Prevent Alert From Closing Through JavaScript Alert Event - javascript

Kindly look at my code:
$('#myPanel').on('closed.bs.alert', function () {
// insert code here
});
I tried return false inside, and even passed event as parameter in function(){} and performed event.preventDefault(), but it still won't stop the alert from being closed. I need to prevent the alert from being closed in case some conditions that I will put will not be satisfied.

Perhaps this will work for you:
$('#myPanel [data-dismiss]').on('click', function () {
return false;
});
Instead of hooking into bootstrap's event we hook into the user's click of the dismiss button, and prevent bootstrap's event from triggering.

The reason the code wasn't working is that you were adding an event handler to the event that fires after the alert has already been closed and not the one before it closes. This is what you wanted:
$('#myPanel').on('close.bs.alert', function (e) {
e.preventPropagation();
});
Using return false; would also work but I try to use the event methods whenever I can since not all browsers interpret returning false from an event handler in the same way.

Related

I want to use Bootstrap Modal buttons to return results on click event

My aim is to override the jquery confirm() function with `function
confirm(message){
//There is a modal opened already
$('#confirm').modal('show', {backdrop: 'static'}); //Show second modal on top of the first modal
$('#confirm').find('.modal-title').html(message);
$('.confirm').on('click',function(){ //on Confirm button click of the second modal
$('#confirm').removeClass('fade').modal('hide');//Hide the Second modal
$('.page-body').addClass('modal-open'); // Addig back modal-open class to body element to prevent modal conflict
callback(); //some suggested this but it doesnt work
return true; //I want to return this to the function called this function but i get no results
});
$('.cancel').on('click',function(){
$('#confirm').removeClass('fade').modal('hide');
$('.page-body').addClass('modal-open');
callback();
return false;
});
$('.close').on('click',function(){
$('#confirm').removeClass('fade').modal('hide');
$('.page-body').addClass('modal-open');
callback();
return 'cancel';
});
}` I am not getting any results when I call the function
jQuery doesn't have a confirm() function, so you're either using the browser's built-in function or some plugin...
You're not returning anything from your custom confirm function. You're defining event handlers that may eventually return values, but they won't return anything until they're called.
It's hard to figure out what this function should be doing. Can you summarize the logic in English?
Here's what it looks like your code is doing right now:
When the user calls the built-in confirm function,
Show a modal dialog
Set its title to the message parameter
Do nothing right now, but attach an onclick event handler to the confirm class.
Do nothing right now, but attach an onclick event handler to the cancel class.
Do nothing right now, but attach an onclick event handler to the close class.
It's too late to do anything useful with those event handlers at that point, and you'll never see their return values.
If you post your HTML and say step-by-step, in detail what order you want events to happen in, people can help. But otherwise I'm not sure how.

jQuery Function Stuck in Loop

I have a simple div with a link with in:
<div class="mhButton">
<span class="icon-checkmark"></span> Register Animal
</div>
I've have a function that is triggered whenever the 'div.mhButton' is clicked. This function should find 'div.mhButton' child 'a' and click it.
$(".mhButton").on('click', function () {
var a = $(this).find("a").text();
console.log(a);
$(this).find("a").click();
});
This works, however, I get stuck in a loop that runs like 639 times.
I can't comprehend why this runs X amount of times, then continues without error.
Does anyone have a solution on how to prevent this? Along with an explanation on why this happens?
Note* The console is logging the same button, again and again.
Because the a tag is embedded in the button, you are continuously re-firing the event. Events will bubble up, so the anchor will get clicked, and then its parent. It is running until the browser gets tired of running it and then it just stops. The method doesn't actually do anything which is likely why you aren't seeing any issues. You can accomplish your goal a couple of ways:
$(".mhButton").click(function () {
$(this).off('click'); // turn the click handler off in the handler itself.
var a = $(this).find("a").text();
console.log(a);
$(this).find("a").click();
});
If you do this, then you will end up only being able to fire the event once.
Alternatively:
$(".mhButton").click(function (e) {
a = $(this).find("a").text();
console.log(a);
$(this).find("a").click();
});
$("#RegisterAnimal").click(function (e) {
e.stopPropagation(); // prevent the anchor from re-firing the button click
});
Altenatively, you can just style the link to look like a button and avoid the unnecessary click handlers all together.
When you call $(this).find("a").click(); the event will bubble up to the div.mhButton tag and cause your handler to be called again. The reason it runs around 500 times is because it stops with a stack overflow, it does not continue
You can prevent it by checking if the click was the <a> tag itself and not calling click() in that case
Working example: http://jsfiddle.net/mendesjuan/zdkrhh42/
Note Regarding the accepted answer
Bic's second answer almost works, mine is a different approach with fewer side effects. The main problem with calling stopPropagation is that there may be handlers on the whole document that wouldn't get fired in that case. A commmon case is when you have a menu or a dialog that is supposed to hide when you click anywhere else on the page. The stopPropagation approach will prevent the menu from being hidden when they click your button.
$(".mhButton").click(function (e) {
// Only run this handler if the click was on the div, not the link itself
if ( $(e.target).is('a, a *') ) {
return;
}
var a = $(this).find("a").text();
$(this).find("a").click();
});

I can't prevent a button click event on JQuery

I have a button that clears a list, the click on this button shows a dialog that asks for validation (Yes/No). What I want is to disable the "Clear" button after clearing the list (Click on Yes). Here's my code :
$('#clearBtn').click(function() {
$('#alert5').show();
$('#bg').show();
$('#Yes').click(function(){
$('.list1').empty();
$('#clearBtn').disable(true);
$('#clearBtn').click(function(e){
e.preventDefault();
});
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
});
the preventDefault() function doesn't seem to work.
First never nest event handlers.
$('#cleatBtn').click(function () {
$('#alert5').show();
$('#bg').show();
});
$('#Yes').click(function () {
$('.list1').empty();
$('#cleatBtn').attr('disabled', true);
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
If you just want to disable then use the following syntax
$('#cleatBtn').attr('disabled', true);
Remove the innermost event completely.. That is not required.
Use on to bind the events, if you want the button to be enabled but turn off the event handler using off
One more option you have is to apply a class to the button when you press yes and execute the code only when the class is not present.
$('#cleatBtn').click(function () {
if( !$(this).hasClass('active')) {
$('#alert5').show();
$('#bg').show();
}
});
$('#Yes').click(function () {
$('.list1').empty();
$('#cleatBtn').attr('disabled', true);
$('#cleatBtn').addClass('active');
$(".alert").fadeOut(250);
$(".alertbg").fadeOut(250);
});
To disable a button, call the prop function with the argument true on it:
$('#cleatBtn').prop("disabled", true);
e.preventDefault(); is the correct way of cancelling events. Some older browsers also expect a return type of false. Which I think will cause jQuery to call preventDefault()?
Here's a good answer: What's the effect of adding 'return false' to a click event listener?
I think your structure looks a bit odd. you don't need to attach click events within a click event.
Just attach them all separately on document.ready events. At the moment they are nested, then go back to trying to cancel your event. The dom tree might be confused by the way the events are nested.
Hope that helps.

Should I return false; every function that needs a trigger?

Should I return false; every function that actually needs an action from the user or the browser to trigger?
For example:
$('myDiv').click(function(){ ... });
or
function myFunction(){ ... }
This second one would later appear below a click function as the first one.
This question is for both JQuery and pure Javascript.
Using return false will prevent the calling of further listeners, and also it default event (such as leaving the page on clicking a link). If that is what to what, then return false, otherwise don't.
With e.preventDefault() further listeners will still be called, but the default reaction won't be trigger ("don't leave the page, when a link was clicked").
If you do neither, a later called listener can stil use e.preventDefault() and/or return false.
Using jQuery, there is no need to do both (e.preventDefault(); return false;). JQuery will call preventDefault for you, if you return false.
As for default event of links, I found href="javascript:void(0)" to work the best; even if JavaScript is deactivated.
No, that will make the event fail to perform its normal duty.
you can use event.preventDefault() anywhere in the function instead of return false.
$('#some-id').click(function(e) {
e.preventDefault();
// …;
});
and for simple javascript:
document.getElementById('some-id').onclick = function(e) {
e.preventDefault();
// …;
};
It seems you're talking about event which have already a default behaviour (like the <a> element). I answered that way. but for element which haven't any, it's not necessary

How can I trigger an element's default event within an event handler?

I have an HTML button that needs to check several conditions, and if they pass allow the default action to occur.
The following works in Firefox, but it fails in IE. I setup a click handler on the button:
Ext.get('send').on('click', handleSend, this, {
preventDefault: true
});
which pops up one of several message boxes if one of the conditions isn't met. If all conditions are met, I remove the click listener from the button and click the button again:
Ext.get('send').un('click', handleSend, this);
Ext.getDom('send').click();
As far as I can tell, it fails in IE (and possibly other browsers) because click() isn't a standard function for a DOM element.
If the default action were a simple form submit, I could just do that after the checks pass, but we're using Tapestry 4 with a listener, which doesn't get executed on a normal form submit.
I've tried submitting the form with
tapestry.form.submit('composeForm', 'doSend');
but the doSend listener isn't getting called.
Conditionally allowing the default event is the best solution I've come up with, but there are a couple of options that may be possible:
Is there some other way to cause a Tapestry 4 listener to be fired from within Javascript?
Is there any way to recognize the normal form submit in my Tapestry Page and thereby trigger the listener?
JSFiddle added
In this jsfiddle, the default action is to submit the form; this is prevented when the checkbox is unchecked. When checked it removes the handler, but the call to click() doesn't work in IE.
Is there a way to simulate a click in IE?
Update
Another snag in the problem is that I have to display an 'are you sure' dialog, so in order to give them time to answer, the event has to be stopped. If they click OK, the default action needs to occur. JSFiddle doesn't seem to have ExtJS widgets like MessageBox, so I'm not sure how to demo this behavior.
At #Ivan's suggestion I tried
Ext.getDom('send').fireEvent('onclick');
but it returns false, meaning the event is being cancelled somewhere. I then tried
var evt = document.createEvent("Event");
evt.initEvent('click', false, false);
var cancelled = Ext.getDom('send').fireEvent('onclick', evt);
but IE9 says that document.createEvent doesn't exist, even though this is how MSDN says to do it.
If all conditions are met, I remove the click listener from the button
and click the button again:
Don't.
You should rather check the conditions in the click handler and call stopEvent there like so:
Ext.get('send').on('click', handleClick);
function handleClick(e) {
if (condition) {
e.stopEvent();
}
}
Internet explorer does not support click. You should use fireEvent method instead e.g.
Ext.getDom('send').fireEvent('onclick');
That should work for IE. For other browsers I guess click is ok. Anyway If I should do similar task I'll try to write an adapter for tapestry and use tapestry javascript library.
There's a listener parameter on Form components; from the Tapestry 4 doc:
Default listener to be invoked when the form is submitted. Invoked
only if another listener (success, cancel or refresh) is not invoked.
Setting this parameter to my listener method like so:
<binding name="listener" value="listener:doSend" />
causes a Tapestry form submit
tapestry.form.submit('myFormId');
to trigger the listener.

Categories

Resources