Bootstrap tooltips stop working whenever anything is clicked on the page - javascript

On my page, I initialize Bootstrap tooltips this way
<script>
$(document).ready(function () {
$(function () {
$('[data-toggle="tooltip"]').tooltip();
});
});
</script>
This question suggests that any time an event happens you have to reload tooltips. However, across various ajax page updating there are probably 50+ events to account for. (This site is using asp.net web forms and ajaxcontroltoolkit)
How can I universally reinitiate tooltips every time an event takes place? -- or is there a simpler solution to solving this problem?

You need a javascript reference to Sys.WebForms.PageRequestManager
Take a look at the beginRequest/endRequest events. Since asp.net ajax is replacing your html you'll need to rebind the bootstrap widgets after asp.net is finished with its ajax.
Try this:
<script>
var prm = Sys.WebForms.PageRequestManager.getInstance();
//func to rebind tooltip
function reBind () { $('[data-toggle="tooltip"]').tooltip(); }
$(document).ready(function () {
$(function () {
reBind();
prm.add_endRequest(reBind);
});
});
</script>
Be warned some bootstrap widgets will break if they are bound twice, so use your discretion; some elements might need to have their events monitored to see if they are bound more than once.

Related

How to restart the Jquery events, to avoid the repetition of each one of them?

I have an index page that contains the following events.
<div id="sub_page"></div>
$(document).ready(function () {
$("a.menu_navegacion_abrircaja").on('click', function (ev) {
ev.preventDefault();
var href = “nombrecontrollerEJ/view_ej";
$.post(href, function (data) {
$("#sub_page").html(data);
});
});
});
In it, when you click, load the html contents of subpages in the div sub_page.
In view view view_ej, I bring html code and also, jquery code. The Jquery code of the view that is added to the index div is as follows:
$(document).ready(function () {
$('#modal_establecer_turnos').on('hidden.bs.modal', function () {
alert("hello");
});
});
By clicking on the link that contains the class "menu_navegacion_abrircaja", I get the alert ("hello");
But it turns out that there is a problem, for every time I click on the link, the alert messages are repeated (alert ("hello");). For example, the first time I click on the link that contains the class menu_navegacion_abrircaja, it works fine showing the alert once, but then I click again on the same link it shows me the alert twice, then I do it for the third time, He shows me three times the alert, and so on.
I would like to know how to solve this problem.
Will there be any way to restart the events or handler of the jquery, as are the events click, change, "hidden.bs.modal", etc., in such a way that their repetition of the events is avoided?
I have seen the methods unbind (), bind (), off (), which might be the solution, but if so, how could you apply them?
Maybe you could try something like this in the jQuery code of your subpage:
$(document).ready(function () {
$('#modal_establecer_turnos').off('hidden.bs.modal');
$('#modal_establecer_turnos').on('hidden.bs.modal', function () {
alert(“hello”);
});
});

Redirect Jquery mobile to new page with triggering of functions in this page?

I am building a mobile app, using JQuery mobile, and in the front page let's call it page-1 contains navigation buttons to different pages let's call one of them page-2
Below are page-1
$(document).ready(function () {
$("body").pagecontainer({
defaults: true
});
$("#page-2").click(function () {
$("body").pagecontainer("change", "page-2.html", {
reload: true
});
$(document).ready(function () {
function_in_page - 2.init();
});
});
page-2 has the following
var function_in_page = {
init: function () {
alert('first-1');
$("#button-1").click(function () {
alert('second-1');
});
});
So what is happening that I get the alert of "First-1" but when I click the button with ID (button-1) nothing happens , any advise?
First of all, .pagecontainer() is auto-initialized with default settings, so you don't need to initialize it.
Secondly, refrain from using .ready() to add listeners in jQuery Mobile and stick to pagecontainer events instead. The latter events are fired whenever jQM framework loads a page and/or navigates to it via Ajax, especially in Single Page Model. Unlike .ready() which fires one time only when framework is initialized.
There are many methods to control your webapp using jQuery Mobile in a Single Page Model using pagecontainer events. The safest way is to give each page a unique ID in order to determine which event is omitted on which page. Another note, you need to know that no matter how many external pages you have, only two pages will remain in DOM; homepage and another external page you have navigated to from homepage.
To add listeners, use pagecreate event, it is equivalent to .ready() and can be delegated to specific pages.
<div data-role="page" id="home">
$(document).on("pagecreate", "#home", function () {
$(".selector").on("click", function () {
/* run code */
});
});
That event will fire once per page, but note that it will fire again on any external page loaded via Ajax. Therefore, you should remove previous bindings before adding new ones, by using .off(). Otherwise, attached listeners will multiple whenever you load an external page via Ajax.
<div data-role="page" id="second">
$(document).on("pagecreate", "#second", function () {
$(".selector").off("click").on("click", function () {
/* run code */
});
});
Keep all your custom JS code in head of all pages, although the code will be loaded once in first run. jQuery Mobile loads first page div of each external page, anything outside that div is entirely neglected.
Back to your code above, here is how it should look like. Give each page an ID, and use them to add click listeners. Let's assume home is homepage and second is page-2.html.
$(document).on("pagecreate", "#home", function () {
$("#btn").on("click", function () {
$.mobile.pageContainer.pagecontainer("change", "page-2.html");
});
});
Now, page-2.html is visible. Add a click listener to button-1.
$(document).on("pagecreate", "#second", function () {
$("#button-1").off("click").on("click", function () {
alert("page 2");
});
});
Demo
Read more about pagecontainer events.
If the script in page-2 is executed to early the button might not exist yet. Try wrapping it in a document.ready
$(document).ready(function(){
var function_in_page={init:function(){
alert('first-1');
$("#button-1").click(function(){
alert('second-1');
});});
});

Intercept click-event on Google Calendar with jquery

I am trying to do my own stuff when I click on a event in my embedded Google Calendar (iframe).
My code so far:
<script type="text/javascript">
$(document).on('click', function (e) {
if ($(this).hasClass('te-s')) {
e.preventDefault();
e.stopImmediatePropagation();
}
});
$(function () {
$('.te-s').bind("click", function () {
alert("test");
});
</script>
te-s is the class containing the event-text, and instead of showing this additional details bubble, I (later) want to redirect on my own site (alert is only there for test purposes).
Is this possible using jquery?
Im not sure this is possible. I guess your script would have to be within the child iframe to be able to listen to events within it.
Apart from that the class you are referencing 'te-s' will most likely not bear the same name again. These name will keep changing.
The best solution would be to use a call back from the API, if it exists.

Show jquery mobile dialog only once on startup (web app)

My problem is that following code works fine (dialog show once on startup), but when I navigate to another page (with standard ajax activated), and then navigate back to the first page, the dialog is showing again (and then in a loop manner when I click "dismiss").
What am I doing wrong?
Code looks like that:
$(document).on('pageinit', '#pageindex', function(event) {
setTimeout(function(){
$('#dialog').click();
$('#dialog').remove();
},1000);
});
For a quick fix, replace .on with.one. However, normally pageinit event should fire once only, so there must be something causing it to fire multiple times.
The following code is executed once on single/multipage page and multiple pages approach:
$(document).on('pageinit', '#pageindex', function (event) {
$(this).off(event);
setTimeout(function () {
$('#dialog').click();
$('#dialog').remove();
}, 1000);
});

jQuery $(document).ready and UpdatePanels?

I'm using jQuery to wire up some mouseover effects on elements that are inside an UpdatePanel. The events are bound in $(document).ready . For example:
$(function() {
$('div._Foo').bind("mouseover", function(e) {
// Do something exciting
});
});
Of course, this works fine the first time the page is loaded, but when the UpdatePanel does a partial page update, it's not run and the mouseover effects don't work any more inside the UpdatePanel.
What's the recommended approach for wiring stuff up in jQuery not only on the first page load, but every time an UpdatePanel fires a partial page update? Should I be using the ASP.NET ajax lifecycle instead of $(document).ready?
An UpdatePanel completely replaces the contents of the update panel on an update. This means that those events you subscribed to are no longer subscribed because there are new elements in that update panel.
What I've done to work around this is re-subscribe to the events I need after every update. I use $(document).ready() for the initial load, then use Microsoft's PageRequestManager (available if you have an update panel on your page) to re-subscribe every update.
$(document).ready(function() {
// bind your jQuery events here initially
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
// re-bind your jQuery events here
});
The PageRequestManager is a javascript object which is automatically available if an update panel is on the page. You shouldn't need to do anything other than the code above in order to use it as long as the UpdatePanel is on the page.
If you need more detailed control, this event passes arguments similar to how .NET events are passed arguments (sender, eventArgs) so you can see what raised the event and only re-bind if needed.
Here is the latest version of the documentation from Microsoft: msdn.microsoft.com/.../bb383810.aspx
A better option you may have, depending on your needs, is to use jQuery's .on(). These method are more efficient than re-subscribing to DOM elements on every update. Read all of the documentation before you use this approach however, since it may or may not meet your needs. There are a lot of jQuery plugins that would be unreasonable to refactor to use .delegate() or .on(), so in those cases, you're better off re-subscribing.
<script type="text/javascript">
function BindEvents() {
$(document).ready(function() {
$(".tr-base").mouseover(function() {
$(this).toggleClass("trHover");
}).mouseout(function() {
$(this).removeClass("trHover");
});
}
</script>
The area which is going to be updated.
<asp:UpdatePanel...
<ContentTemplate
<script type="text/javascript">
Sys.Application.add_load(BindEvents);
</script>
*// Staff*
</ContentTemplate>
</asp:UpdatePanel>
User Control with jQuery Inside an UpdatePanel
This isn't a direct answer to the question, but I did put this solution together by reading the answers that I found here, and I thought someone might find it useful.
I was trying to use a jQuery textarea limiter inside of a User Control. This was tricky, because the User Control runs inside of an UpdatePanel, and it was losing its bindings on callback.
If this was just a page, the answers here would have applied directly. However, User Controls do not have direct access to the head tag, nor did they have direct access to the UpdatePanel as some of the answers assume.
I ended up putting this script block right into the top of my User Control's markup. For the initial bind, it uses $(document).ready, and then it uses prm.add_endRequest from there:
<script type="text/javascript">
function BindControlEvents() {
//jQuery is wrapped in BindEvents function so it can be re-bound after each callback.
//Your code would replace the following line:
$('#<%= TextProtocolDrugInstructions.ClientID %>').limit('100', '#charsLeft_Instructions');
}
//Initial bind
$(document).ready(function () {
BindControlEvents();
});
//Re-bind for callbacks
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
BindControlEvents();
});
</script>
So... Just thought someone might like to know that this works.
Upgrade to jQuery 1.3 and use:
$(function() {
$('div._Foo').live("mouseover", function(e) {
// Do something exciting
});
});
Note: live works with most events, but not all. There is a complete list in the documentation.
You could also try:
<asp:UpdatePanel runat="server" ID="myUpdatePanel">
<ContentTemplate>
<script type="text/javascript" language="javascript">
function pageLoad() {
$('div._Foo').bind("mouseover", function(e) {
// Do something exciting
});
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
,since pageLoad() is an ASP.NET ajax event which is executed each time the page is loaded at client side.
My answer?
function pageLoad() {
$(document).ready(function(){
etc.
Worked like a charm, where a number of other solutions failed miserably.
I would use one of the following approaches:
Encapsulate the event binding in a function and run it every time you update the page. You can always contain the event binding to specific elements so as not to bind events multiple times to the same elements.
Use the livequery plug-in, which basically performs method one for you auto-magically. Your preference may vary depending on the amount of control you want to have on the event binding.
function pageLoad() is very dangerous to use in this situation. You could have events become wired multiple times. I would also stay away from .live() as it attaches to the document element and has to traverse the entire page (slow and crappy).
The best solution I have seen so far is to use jQuery .delegate() function on a wrapper outside the update panel and make use of bubbling. Other then that, you could always wire up the handlers using Microsoft's Ajax library which was designed to work with UpdatePanels.
When $(document).ready(function (){...}) not work after page post back then use JavaScript function pageLoad in Asp.page as follow:
<script type="text/javascript" language="javascript">
function pageLoad() {
// Initialization code here, meant to run once.
}
</script>
I had a similar problem and found the way that worked best was to rely on Event Bubbling and event delegation to handle it. The nice thing about event delegation is that once setup, you don't have to rebind events after an AJAX update.
What I do in my code is setup a delegate on the parent element of the update panel. This parent element is not replaced on an update and therefore the event binding is unaffected.
There are a number of good articles and plugins to handle event delegation in jQuery and the feature will likely be baked into the 1.3 release. The article/plugin I use for reference is:
http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery
Once you understand what it happening, I think you'll find this a much more elegant solution that is more reliable than remembering to re-bind events after every update. This also has the added benefit of giving you one event to unbind when the page is unloaded.
FWIW, I experienced a similar issue w/mootools. Re-attaching my events was the correct move, but needed to be done at the end of the request..eg
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {...
Just something to keep in mind if beginRequest causes you to get null reference JS exceptions.
Cheers
pageLoad = function () {
$('#div').unbind();
//jquery here
}
The pageLoad function is perfect for this case since it runs on the initial page load and every updatepanel async postback. I just had to add the unbind method to make the jquery work on updatepanel postbacks.
http://encosia.com/document-ready-and-pageload-are-not-the-same/
My answer is based on all the expert comments above, but below is the following code that anyone can use to make sure on each postback and on each asynchronous postback the JavaScript code will still be executed.
In my case, I had a user control within a page. Just paste the below code in your user control.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() == undefined) {
UPDATEPANELFUNCTION();
}
}
function UPDATEPANELFUNCTION() {
jQuery(document).ready(function ($) {
/* Insert all your jQuery events and function calls */
});
}
UPDATEPANELFUNCTION();
</script>
Update Panel always replaces your Jquery with its inbuilt Scriptmanager's scripts after every load. Its better if you use pageRequestManager's instance methods like this...
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest)
function onEndRequest(sender, args) {
// your jquery code here
});
it will work fine ...
Use below script and change the body of the script accordingly.
<script>
//Re-Create for on page postbacks
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
//your codes here!
});
</script>
In response to Brian MacKay's answer:
I inject the JavaScript into my page via the ScriptManager instead of putting it directly into the HTML of the UserControl. In my case, I need to scroll to a form that is made visible after the UpdatePanel has finished and returned. This goes in the code behind file. In my sample, I've already created the prm variable on the main content page.
private void ShowForm(bool pShowForm) {
//other code here...
if (pShowForm) {
FocusOnControl(GetFocusOnFormScript(yourControl.ClientID), yourControl.ClientID);
}
}
private void FocusOnControl(string pScript, string pControlId) {
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "focusControl_" + pControlId, pScript, true);
}
/// <summary>
/// Scrolls to the form that is made visible
/// </summary>
/// <param name="pControlId">The ClientID of the control to focus on after the form is made visible</param>
/// <returns></returns>
private string GetFocusOnFormScript(string pControlId) {
string script = #"
function FocusOnForm() {
var scrollToForm = $('#" + pControlId + #"').offset().top;
$('html, body').animate({
scrollTop: scrollToForm},
'slow'
);
/* This removes the event from the PageRequestManager immediately after the desired functionality is completed so that multiple events are not added */
prm.remove_endRequest(ScrollFocusToFormCaller);
}
prm.add_endRequest(ScrollFocusToFormCaller);
function ScrollFocusToFormCaller(sender, args) {
if (args.get_error() == undefined) {
FocusOnForm();
}
}";
return script;
}
Sys.Application.add_load(LoadHandler); //This load handler solved update panel did not bind control after partial postback
function LoadHandler() {
$(document).ready(function () {
//rebind any events here for controls under update panel
});
}
For anyone else in my situation, I was trying to get jquery document ready function to work for a DevExpress ASPxCallbackPanel and nothing above (to-date) worked. This is what did work for me.
<script>
function myDocReadyFunction(){ /* do stuff */ }
</script>
<dx:ASPxCallbackPanel ID="myCallbackPanel" ... >
<ClientSideEvents EndCallback="function(){ myDocReadyFunction();}">
</ClientSideEvents>
<PanelCollection ...>
</dx:ASPxCallbackPanel>

Categories