jQuery .trigger('click') inside interval function? - triggers

This is a rephrased question from here. After some testing I isolated the problem, but have no clue on fixing it. No need to read the previous question, this is the simplified code:
THE PROBLEM -> trigger('click') executes, but the event doesn't trigger when inside looped (intervaled) function
$(document.ready(function(){
var checkForConfirmation = function(){
clearInterval(checkInterval);
$("#anchorLink").trigger('click');
}
var checkInterval = setInterval(function(){checkForConfirmation()}, 5000);
});
The function is being called in intervals. When the proper response is replied, interval stops, and simulates the click on an anchor link.
In the html file there is an anchor link <a id="anchorLink" href="#hiddenDiv">Show</a>.
It points to the hidden div which has some content. I'm using Fancybox plugin to show the hidden div when the anchor link is clicked.
If I click on Show link fancybox shows, as expected.
If I get the response from the back-end, code executes as expected, but fancybox is not shown.
If I move $("#anchorLink").trigger('click'); outside the checkForConfirmation function, fancybox shows.
When I replace $("#anchorLink").trigger('click'); with $("#anchorLink").text('Im clicked'); the string shows in the <a id="ancoredLink"> tag.
This is the summary, I have tried it in different situations.
The problem is obviously in triggering the click event while in looping function. The $("#anchorLink") selector is accessible, it is triggering it correctly from everywhere else. Obviously there is a problem in triggering the mouse event inside looping function.
Any suggestions?

Try:
$(document).ready(function(){
// ...
});
instead of:
$(document.ready(function(){
// ...
});

Related

How to capture click event on dynamic content in task pane?

I've got some code that successfully takes text from the document, does some stuff with it, and renders variations in dynamic divs in the task pane.
Right now I'm just trying to register a click on one of the dynamic divs in the console log but I don't see any event happening. But when I stop and restart the code in VS I see this in the console...
Item Details Clicked! undefined
So, something is registering.
I'm reading the Office.js docs and other blog posts but can't seem to find what I'm doing wrong.
I've tried variations of these to no avail.
// dynamic div
var myDetails = 'details-S' + myId + 'I' + idxWarn;
var myDetLink = ' <div class="linkItemDetails" id="' + myDetails + '">...</div>';
function clickedItemDetails() {
console.log("Item Details Clicked! " +JSON.stringify(this));
}
$('.linkItemDetails').click(clickedItemDetails);
$('.linkItemDetails').on('click', clickedItemDetails());
$('.vtsItemDetails').bind("click", clickedItemDetails);
$('#parentDivItemCategories').on('click', '.linkItemDetails', function () { clickedItemDetails() });
Now, when I stop and restart the code in VS I see this in the console...
Item Details Clicked! undefined
So, something is registering, somewhere. Just not when/where/how I want it to.
Can someone point me in the right direction?
Disregard. I had the right code but with the wrong parent div ID. Feeling like a total newb. But wait, I am! Anyway, this code works if you have the right parent div ID
$('#parentDivItemCategories').on('click', '.linkItemDetails', function () { clickedItemDetails() });

bootstrap jquery show.bs.modal event won't fire

i'm using the modal example from the bootstrap 3 docs. the modal works. however i need to access the show.bs.modal event when it fires. for now i'm just trying:
$('#myModal').on('show.bs.modal', function () {
alert('hi')
})
Nothing happens, the event does not fire. What am I doing wrong??? This doesn't make sense to me.
use this:
$(document).on('show.bs.modal','#myModal', function () {
alert('hi');
})
Make sure you put your on('shown.bs.modal') before instantiating the modal to pop up
$("#myModal").on("shown.bs.modal", function () {
alert('Hi');
});
$("#myModal").modal('show'); //This can also be $("#myModal").modal({ show: true });
or
$("#myModal").on("shown.bs.modal", function () {
alert('Hi');
}).modal('show');
To focus on a field, it is better to use the shown.bs.modal in stead of show.bs.modal but maybe for other reasons you want to hide something the the background or set something right before the modal starts showing, use the show.bs.modal function.
Wrap your function in $(document).ready(function() { }), or more simply, $(function() {. In CoffeeScript, this would look like
$ ->
$('#myModal').on 'show.bs.modal', (event)->
Without it, the JavaScript is executing before the document loads, and #myModal is not part of the DOM yet. Here is the Bootstrap reference.
$(document).on('shown.bs.modal','.modal', function () {
/// TODO EVENTS
});
Try this
$('#myModal').on('shown.bs.modal', function () {
alert('hi');
});
Using shown instead of show also make sure you have your semi colons at the end of your function and alert.
Add this:
$(document).ready(function(){
$(document).on('shown.bs.modal','.modal', function () {
// DO EVENTS
});
});
Similar thing happened to me and I have solved using setTimeout.
Bootstrap is using the following timeout to complete showing:
c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,
So using more than 300 must work and for me 200 is working:
$('#myModal').on('show.bs.modal', function (e) {
setTimeout(function(){
//Do something if necessary
}, 300);
})
In my case, I was missing the .modal-dialog div
Doesn't fire event: shown.bs.modal
<div id="loadingModal" class="modal fade">
<p>Loading...</p>
</div>
Does fire event: shown.bs.modal
<div id="loadingModal" class="modal fade">
<div class="modal-dialog">
<p>Loading...</p>
</div>
</div>
I had the same issue with bootstrap4.
The solution was to add it inside the jQuery document ready() function:
$(document).ready(function() {
$('#myModal').on('show.bs.modal', function () {
alert('hi')
})
}
This happens when code might been executed before and it's not showing up so you can add timeout() for it tp fire.
$(document).on('shown.bs.modal', function (event) {
setTimeout(function(){
alert("Hi");
},1000);
});
I had a similar but different problem and still unable to work when I use $('#myModal'). I was able to get it working when I use $(window).
My other problem is that I found that the show event would not fire if I stored my modal div html content in a javascript variable like.
var content="<div id='myModal' ...";
$(content).modal();
$(window).on('show.bs.modal', function (e) {
alert('show test');
});
the event never fired because it didn't occur
my fix was to include the divs in the html body
<body>
<div id='myModal'>
...
</div>
<script>
$('#myModal).modal();
$(window).on('show.bs.modal', function (e) {
alert('show test');
});
</script>
</body>
Remember to put the script after the call of "js/bootstrap", not before.
Had the same issue. For me it was that i loaded jquery twice in this order:
Loaded jQuery
Loaded Bootstrap
Loaded jQuery again
When jQuery was loaded the second time it somehow broke the references to bootstrap and the modal opened but the on('shown.bs..') method never fired.
Ensure that you are loading jQuery before you use Bootstrap. Sounds basic, but I was having issues catching these modal events and turns out the error was not with my code but that I was loading Bootstrap before jQuery.
Sometimes this doesn't work if:
1) you have an error in the java script code before your line with $('#myModal').on('show.bs.modal'...). To troubleshoot put an alert message before the line to see if it comes up when you load the page. To resolve eliminate JSs above to see which one is the problem
2) Another problem is if you load up the JS in wrong order. For example you can have the $('#myModal').on('show.bs.modal'...) part before you actually load JQuery.js. In that case your call will be ignored, so first in the HTML (view page source to be sure) check if the script link to JQuery is above your modal onShow call, otherwise it will be ignored. To troubleshoot put an alert inside the on show an one before. If you see the one before and not the one inside the onShow function it is clear that the function cannot execute. If the spelling is right more than likely your call to JQuery.js is not made or it is made after the onShow part
Make sure that you really use the bootstrap jquery modal and not another jquery modal.
Wasted way too much time on this...
In my case the problem was how travelsize comment.. The order of imports between bootstrap.js and jquery. Because I'am using the template Metronic and doesn't check before
i used jQuery's event delegation /bubbling... that worked for me. See below:
$(document).on('click', '#btnSubmit', function () {
alert('hi loo');
})
very good info too: https://learn.jquery.com/events/event-delegation/
The popular solution to put a setTimeout could work in some case, but is a terrible solution. I was myself using it amongst wraping it in $(document).ready() off course (but it never helped), but I was never able to have a reliable solution. Some browser/system take more time than other, and sometime 1000ms was not enough. And I was tired searching why the $(document).ready() wasn't helping, so :
I took a different approach.
I make the subscription to modal events when I need to use the modal for the first time.
Open my modal
and on the JS side :
function ShowModal() {
InitModalEventsOnce();
$('#MyModal').modal('show');
}
var InitModalEventsIsDone = false; // Flag to keep track of the subscribtion
function InitModalEventsOnce() {
if (!InitModalEventsIsDone) {
InitModalEventsIsDone = true;
$('#MyModal').on('shown.bs.modal', function () {
// something
})
$('#MyModal').on('hidden.bs.modal', function (e) {
// something
});
}
}
And that's it! The only reliable solution I found.
Try like this.
let mymodal=$('#myModal');
mymodal.on('show.bs.modal', function ()
{
alert('hi')
});
Below are the granular details:
show.bs.modal works while model dialog loading
shown.bs.modal worked to do any thing after loading. post rendering

Prevent TinyMCE prompting onbeforeunload with save from custom button

I couldn't find any post regarding this issue, so this was my last way out. I'd like to somehow tell TinyMCE that I've taken care of the saving process (reset the isdirty I guess), but to keep checking for further changes without reloading the page. Ofcourse, if I do a location.reload it works, but that takes a bit of elegance out of it.
I have a custom save-button with the following method:
$("#saveAbout").click(function(){
tinymce.activeEditor.getBody().setAttribute('contenteditable', false);
$("#outerWrapper").animate({opacity:0.3});
$("#bigloader").fadeIn();
var currentData = tinyMCE.activeEditor.getContent();
var currentLanguage = $("#currentLang").val();
$.post("src/actions/pup_about.php", { text: currentData, lang: currentLanguage })
.done(function(data) {
$("#bigloader").fadeOut();
$("#outerWrapper").animate({opacity:1});
// What to do here?
});
});
This basically gets the contents and saves it through a PHP file. A neat ajax loader shows up and fades out during the process. The #outerWrapper div is a div around the TinyMCE in order to fade it slightly out during the save process.
Is there any smart way to tell TinyMCE that saving is done, but to keep looking for further changes?
You could issue in your function
tinymce.get('your_editor_id').save();
this should then take care of setting everything else.

Testing modal dialogs with zombie.js

I have some input fields inside a modal dialog like so (that's jade):
.modal-body
.control-group
label.required(for="event-planner-email")= Email
.input
input#event-planner-email(name="email", type='text')
.control-group
label.required(for="event-planner-name")= Name
.input
input#event-planner-name(name="name", type='text')
And I would like to be able to fill them out in a test. I tried pressing the link that opens the modal and filling the fields using zombie.js browser object, code in coffee follows:
browser.clickLink 'a#open-planner', () ->
browser
.fill('event-planner-email', someEmail)
.fill('event-planner-name', someName)
.pressButton 'Create', () ->
do done
But I get an error saying: "No INPUT matching 'event-planner-email'". If anyone knows how to do this, help would be much appreciated. Thanks!
Maybe the modal has not come into view yet by the time your call back is firing. If there is a transition happening to show the modal, you'll have to wait for that transition to complete.
Maybe try adding a setTimeout in your call back of the clickLink:
browser.clickLink 'a#open-planner', ->
fillForm = ->
browser
.fill('event-planner-email', someEmail)
.fill('event-planner-name', someName)
.pressButton 'Create', ->
do done
setTimeout fillForm, 1000
From the Bootstrap docs
You need to run your zombie code after the modal loads, so you should use the "shown" event
$('#myModal').on('shown', function () {
// zombie
})
I'm not sure how to represent that in coffee
Thanks everyone, turns out I just didn't use the proper css selector for the input elements, so instead of
.fill('event-planner-email', someEmail)
should be
.fill('input#event-planner-email', someEmail)
Because in jade snippet above, 'event-planner-email' is the id of the input element. Wanted to delete my question, so that I don't expose my stupidity any further, but apparently it's too late.

In jQuery Mobile, how do you target the element created using loadPage?

I load a "page" into the DOM using $.mobile.loadPage(). I then want to target the element created, but I haven't figured out how to do this. This is what I thought would work:
var toc = $.mobile.loadPage('toc.html');
toc.trigger('customevent');
The above does not work in part because toc is a "deferred promise object" rather than a good ol' jQuery DOM reference. Additionally, it does not work because the second line is triggered before loadPage finishes. Is there a way to fire a callback after loadPage?
Thanks!
If you know the id of the page being loaded then you can bind the 'pagecreate' event to that object with .live() like so:
$('#blah').live('pagecreate', function () {alert('created');});
This will fire after the page has been loaded into the dom.
I just was just able to figure this out, even if you don't have the id, here's an example of how i am performing an action (fadeIn) on the the inserted element....
$(document).bind('pageload',function(evt,data){
$(document).unbind('pageload');
$(data.page).fadeIn();
});
$.mobile.loadPage('mypage.html',{'pageContainer':$('#my_item')});
You can use pageshow in order to fire a callback when the page is loaded. Please refer to the jQuery Mobile Events API for more detail.
An example would be something like:
$('div').live('pageshow',function(event, ui){
...
});