Execute script when window is active - javascript

How can I execute this function only once and when the browser tab/window is active ?
$(function(){
noty({text:'Here is my text',type:'error'});
return false;
});
If I use:
$(window).one('focus', function(){
The function is executed but only if I leave the tab and come back again.
Any ideas ?
Many thanks

If you use the load event it will fire when the page is loaded.
$(document).ready(() => {
$(window).on('load', () => {
noty({ text: 'Here is my text', type: 'error' });
});
});

What do you mean by 'is active' ?
If you need this function to be called just one time after load, you can use load event or ready with jquery.
If it's every time the tab is active, so when your user is on the tab, and the mouse focus your document, you can use the focus event.
let activated = false;
window.addEventListener('focus', function() {
if(!activated) {
console.log('test');
activated = true;
}
})

Related

Run a event click after sucessful reload of a bootstrap table

I have this function, where I have a ajax call and in the success function, i have refresh the bootstrap table, now after the refresh i have a trigger command which i want to happen only when the refresh is done, how to do that,
success: function (result) {
console.log(result);
$('#overlay').hide();
swal({
title: result['msg'],
// text: result['text'],
type: result['type'],
showConfirmButton: true
});
$('#prospect_table').bootstrapTable('refresh');
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click')
}
the last event click happens at its specific time but I want to run that command only when the refresh is done,ie status=200
Thanks!
I have tried:
var evnCilck = element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click'); // Or any other click function
$('#prospect_table').bootstrapTable('refresh', function(e){
evnCilck();
});
and
$('#prospect_table').bootstrapTable('refresh', function() {
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click');
});
No help from this.
You can do it like this
$('#prospect_table').bootstrapTable('refresh', function() {
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click');
});
Along with triggering an refresh event You also need to bind refresh eventlistener to the table like this :
var $table = $('#table');
$table.on('refresh.bs.table',function(){
// do your stuff here
element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click');
})
You can do it by this way -
var evnCilck = element.parent('div').parent('div').parent('td').parent('tr').prev('tr').find('td:first').find('a').trigger('click'); // Or any other click function
$('#prospect_table').bootstrapTable('refresh', function(e){
evnCilck();
});

Call function after window reload using same button

$('#start').click(function () {
window.location.href=window.location.href;
runme();
});
This is my simple goal, every time user click the start button, I want the page to reload but still call the custom rume function. Please let me know if this is possible or there are other way. Thanks in advance.
Whenever you reload the page JS run again from start, So you can't directly trigger some function after page reload.
But in order to achieve this, you can use, sessionStorage
So, you can do something like:
$('#start').click(function () {
sessionStorage.setItem('callRunMe', '1')
window.location.href=window.location.href;
});
//On Page load
$(document).ready(function () {
if (sessionStorage.getItem('callRunMe')) {
runMe();
sessionStorage.removeItem('callRunMe');
}
});
you can set a flag into sessionStorage or localStorage and get the flag after document ready.
var SOTRAGE_NAME = 'needRunme'
$('#start').click(function () {
sessionStorage.setItem(SOTRAGE_NAME, true);
runme();
});
$(document).ready(function(){
var isNeedRunme = sessionStorage.getItem(SOTRAGE_NAME);
if(isNeedRunme){
runme();
}
})
Place your runme inside $(document).ready, and just use location.reload() to reload the page. Use localStorage to make sure this only happens when you click a button:
$(document).ready(() => {
if (localStorage.getItem("clickedStart") runme();
});
$("#start").on("click", () => {
localStorage.setItem("clickedStart", "true");
location.reload();
});

how to unbind onbeforeunload event on javascript function call and page refresh

Please help me how to unbind onbeforeunload event on javascript function call .
Also I want to unbind onbeforeunload on page refresh.
Actually I want to give pop up alert on page exit .For this I have successfully unbinded onbeforeunload from form submit button and anchor tags. Kindly help me. The code I have used is
var jQuery = jQuery.noConflict();
jQuery(document).ready(function() {
jQuery(window).bind("onbeforeunload", function() {
return confirm("Do you really want to close?")
}
);
jQuery('a').on('click', function() {
jQuery(window).unbind('onbeforeunload')
});
jQuery("form").submit(function() {
jQuery(window).unbind('onbeforeunload')
});
});
Thanks
Do some minor change in your code, it will be work
jQuery(document).ready(function () {
window.onbeforeunload = function () {
return confirm("Do you really want to close?")
};
jQuery('a').on('click', function () {
jQuery(window).unbind('onbeforeunload')
});
jQuery("form").submit(function () {
jQuery(window).unbind('onbeforeunload')
});
});
Check this on jqfiddler, Message pop-up showing on refresh click here

Jquery mobile chained popup dynamic positioning

I have a jquery-mobile popup #graphic-menu activated by an onClick event (getPosition() is in another included script, and works as expected):
HTML
Graphic menu
CSS
function showGM(pos){
$("#menu-buttons").popup("close");
$("#menu-buttons").bind({
popupafterclose: function(event, ui){
$("#graphic-menu").popup("open", {x:pos.x, y:pos.y});
}
});
}
The catch is that #gm-btn is itself part of a parent popup #menu-buttons that:
is called to appear several times
appears at different locations (it's a dragable element)
showGM(pos) uses the position of the #gm-btn when the parent popup first appears, and doesn't change for subsequent child popups when reclicked.
How can I get showGM(getPosition(this)) to correctly recalculate the position of #gm-btn when called (or, more likely, what have I screwed up in my code)?
Edit: at the moment, I'm making things work by storing the position in a variable with global scope (since there's only ever one #menu-buttons active), and passing that to #graphic-menu so it knows where to open. I think this probably isn't good programming practice, so if someone has a better suggestion I'd love to hear about it.
Based on the API (http://api.jquerymobile.com/popup/), they say:
Note: Chaining of popups not allowed: "The framework does not currently support chaining of popups so it's not possible to embed a
link from one popup to another popup. All links with a
data-rel="popup" inside a popup will not do anything at all."
A workaround to get chained popups working is the use of a timeout for
example in the popupafterclose event bound to the invoking popup. In
the following example, when the first popup is closed, the second will
be opened by a delayed call to the open method:
$( document ).on( "pageinit", function() {
$( ".popupParent" ).on({
popupafterclose: function() {
setTimeout(function() { $( ".popupChild" ).popup( "open" ) }, 100 );
}
});
});
In regards to jsFiddle, it works good for this type of testing: https://jsfiddle.net/Twisty/4gjdp4te/7/ You had not set the JQuery library, so I set it to 2.1.3, and retained your JQM 1.4.5 link.
My attempt so far has not yielded the results you want, but you can at least see what direction to take. I plan to keep working on it and will update my answer.
HTML
<div data-role="page">
<div role="main" class="ui-content">
<a id="anchor1" href="#pop-1" data-rel="popup" data-transition="pop">Basic Popup</a>
<div data-role="popup" id="pop-1" data-position-to="#anchor1">
<p>This is a basic popup.</p>
<button id="firstbutton" data-rel="popup">Button to open 2nd popup</button>
</div>
<div data-role="popup" id="pop-2">
<p>This is another basic popup.</p>
</div>
</div>
</div>
JQUERY
var buttonClick = false;
$(document).on("pageinit", function () {
$("#pop-1").on({
popupafterclose: function () {
if (buttonClick) {
console.log("Opening 2nd Popup.");
setTimeout(function () {
$("#pop-2").popup("open", {
positionTo: "#pop-1"
})
}, 100);
buttonClick = false;
} else {
console.log(buttonClick);
}
}
});
});
$(document).ready(function () {
$("#firstbutton").click(function () {
buttonClick = true;
console.log("First Button clicked");
$("#pop-1").popup("close");
});
});
EDIT
I got the code you need: https://jsfiddle.net/Twisty/4gjdp4te/8/
JQUERY
var buttonClick = false;
$(document).ready(function () {
$("#pop-1").popup({
afterclose: function(){
if (buttonClick) {
console.log("Opening 2nd Popup.");
setTimeout(function () {
$("#pop-2").popup("open", {
positionTo: "#pop-1"
})
}, 100);
buttonClick = false;
} else {
console.log(buttonClick);
}
}
});
$("#firstbutton").click(function () {
buttonClick = true;
console.log("First Button clicked");
$("#pop-1").popup("close");
});
});

Trigger event after event.preventDefault()

I had a hyperlinks in the header. When user navigates from one header link to other i need to check whether page is in dirtied or not, if page is dirtied i need to show a modal which has ok and cancel buttons and on ok i need to navigate to the clicked header and on cancel i need to remain in the page. Below is the sample code I wrote.
Template:
HeaderView.js
..
..
ui {
"link1" : "#link1",
"link2" : "#link2",
},
events {
"click #link1" : "navigateLink1"
"click #link2" : "navigateLink2"
}
navigateLink1 : function(e) {
this.navigate(this.ui.link1, "#link1", true, e);
}
navigateLink2 : function(e) {
e.preventDefault();
this.navigate(this.ui.link2, "#link2", true, e);
}
navigate: function(uiElement, path, trigger, event) {
e.preventDefault();
if (model.isDirty() ) {
// I need to send a callback for clicking on ok button
this.callback = function() {
event.trigger();// I am getting an error saying that event.trigger is not a function.
}
new ApplicationModal(model: {callback: this.callback});
} else {
app.router.navigate(path , {trigger: trigger});
}
}
In ApplicationModal i am just executing the callback
I am getting an error saying that event.trigger is not a function while calling from the callback.Let me know how to navigate to the new page after e.preventDefault();

Categories

Resources