Stuck on executing this function after 10 seconds of page load. - javascript

I created this function that checks for user's cookies and then shows a newsletter Popup. I need to load this after the user has spent 10 seconds navigating on the site. I've use window.setTimeout but it hasn't worked so far. The script works beautifully except for this 10 second delay execution. Any idea what I'm doing wrong?
theme.ModalNewsletter = function() {
if ($.cookie('tada-cookies')) {
}
else {
var el = $('#newslettermodal');
if (el.length) {
$('#newslettermodal').removeClass("hide");
$.magnificPopup.open({
items: {
src: el
},
type: 'inline'
});
}
}
$.cookie('tada-cookies', 'true', { expires: 7});
}

Make sure your timeout passes the function itself and doesn't execute it.
Correct way:
setTimeout(theme.ModalNewsletter, 10000);
Incorrect way:
setTimeout(theme.ModalNewsletter(), 10000);

Is this the right approach?
setTimeout(theme.ModalNewsletter, 10000); {
theme.ModalNewsletter = function()
if ($.cookie('tada-cookies')) {
}
else {
var el = $('#newslettermodal');
if (el.length) {
$('#newslettermodal').removeClass("hide");
$.magnificPopup.open({
items: {
src: el
},
type: 'inline'
});
}
}
$.cookie('tada-cookies', 'true', { expires: 7});
}

Related

How to remove external JS when navigate to another page VUEJS

I have java script component in home component with external js. I need to remove external js when page navigate to another page. Page does not refresh.
<script>
function initFreshChat() {
window.fcWidget.init({
token: "***",
host: "https://wchat.freshchat.com"
});
}
function initialize(i,t){var e;i.getElementById(t)?initFreshChat():((e=i.createElement("script")).id=t,e.async=!0,e.src="https://wchat.freshchat.com/js/widget.js",e.onload=initFreshChat,i.head.appendChild(e))}function initiateCall(){initialize(document,"freshchat-js-sdk")}window.addEventListener?window.addEventListener("load",initiateCall,!1):window.attachEvent("load",initiateCall,!1);
</script>
This is the external js: https://wchat.freshchat.com/js/widget.js
I need this because i need to keep this freshchat window in one page.
This can be done by putting any condition. But it will works if we refresh the page. Here pages are not refreshing at all.
Therefore I need to remove the external js when navigate to another pages. And mount back when came to this page.
You can wrap the script in side a Vue component life circle,
render
remove
refresh
whenever you need.
I found this code on codepen https://codepen.io/akccakcctw/pen/LBKQZE
Vue.component("fc-button", {
template: "#fcButton",
props: {
fc: {
type: Object,
default: {},
}
},
methods: {
openWidget: function() {
document.getElementById("fc_frame").style.visibility = "visible";
window.fcWidget.open();
}
}
});
const vm = new Vue({
el: "#app",
data: function() {
return {
fc: {
isInit: false,
},
};
},
mounted: function() {
var self = this;
window.fcSettings = {
token: "8d3a4a04-5562-4f59-8f66-f84a269897a1",
host: "https://wchat.freshchat.com",
config: {
cssNames: {
widget: "custom_fc_frame",
open: "custom_fc_open",
expanded: "custom_fc_expanded"
},
headerProperty: {
hideChatButton: true
}
},
onInit: function() {
window.fcWidget.on("widget:loaded", function() {
self.fc.isInit = true;
window.fcWidget.on("unreadCount:notify", function(resp) {
console.log(resp);
test = resp;
if (resp.count > 0) {
// document.getElementById('notify').classList.add('h-btn-notify');
document.getElementById("notify").style.visibility = "visible";
} else if (resp.count == 0) {
// document.getElementById('notify').classList.remove('h-btn-notify');
document.getElementById("notify").style.visibility = "hidden";
}
});
window.fcWidget.on("widget:closed", function() {
document.getElementById("fc_frame").style.visibility = "hidden";
document.getElementById("open_fc_widget").style.visibility =
"visible";
});
window.fcWidget.on("widget:opened", function(resp) {
document.getElementById("open_fc_widget").style.visibility =
"hidden";
});
});
}
};
}
});

Redirect after the flash message disappears in Angular2

I have a function which calls a service.
submitPost(value:any)
{
this._adminLogin.postAdminLogin(this.adminLoginmodel).subscribe(
data => {
this.responseStatus = data;
if(this.responseStatus.status == 1)
{
localStorage.setItem('admin_id', this.responseStatus.detail.id);
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 5000 });
top.location.href = 'admin/dashboard';
}
else
{
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-danger', timeout: 2000 });
}
},
err => {
console.log(err)
},
() => {}
);
this.status = true;
}
My concern is with this section of code:-
if(this.responseStatus.status == 1)
{
localStorage.setItem('admin_id', this.responseStatus.detail.id);
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 5000 });
top.location.href = 'admin/dashboard';
}
Is there any way by which the redirect action could take place after the flash message disappears after 5000 ms? Something like this:-
if(this.responseStatus.status == 1)
{
localStorage.setItem('admin_id', this.responseStatus.detail.id);
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: {function(){ top.location.href = 'admin/dashboard'; }, 5000 });
}
The following code should navigate after the message disappears. Yout flashMessage will be displayed for 5000 ms and your navigate should happen after 7000ms
if(this.responseStatus.status == 1)
{
localStorage.setItem('admin_id', this.responseStatus.detail.id);
this._flashMessagesService.show(this.responseStatus.message, { cssClass: 'alert-success', timeout: 5000 });
setTimeout(()=>{
top.location.href = 'admin/dashboard';
},7000);
}
I would do this by having the _flashMessagesService.show() return an Observable.
In the _flashMessageService, something like this:
myObserver : Observer<any>
function show(){
// do stuff
return Observable.create(observer =>{
this.myObserver =observer;
});
}
When you're ready to resolve the Observable, you can do:
this.myObserver.next('Possibly some value here');
this.myObserver.complete();
In your invoking code
this._flashMessagesService.show()
.subscribe(result=> { top.location.href = 'admin/dashboard'});}
I have been working on something similar.
An alternate approach, perhaps simpler is to just use Observable.timer in your main component:
Observable.timer(5000).subscribe(result=> { top.location.href = 'admin/dashboard'});
I prefer the first way, because it is contingent on the flashMessage service deciding when the flash message goes away, not on a hard coded time value.

Jquery setTimeout on popup

How to set the opening time for a popup?
<script type="text/javascript">
mgsjQuery(window).load(function () {
if(mgsjQuery(window).width() > 991) {
if(getCookie('newsletter')!='nevershow'){
if (mgsjQuery('#newsletter').length) {
mgsjQuery.magnificPopup.open({
items: {
src: '#newsletter'
},
type: 'inline'
});
}
}
}
});
</script>
I think that i should include the code below, but i do not know where?
setTimeout( NAME, 8000 );
Here's setTimeout method documentation.
So where the NAME is, you should insert your function name or anonymous function.
So in your case it'll be something like:
mgsjQuery(window).load(function () {
if(mgsjQuery(window).width() > 991) {
if(getCookie('newsletter')!='nevershow'){
if (mgsjQuery('#newsletter').length) {
setTimeout(function(){ // <- Inserted - below code will run after 8 seconds
mgsjQuery.magnificPopup.open({
items: {
src: '#newsletter'
},
type: 'inline'
});
}, 8000); // <- Inserted 8000 ms = 8 sec.
}
}
}
});
If you just need to wait some time before the popup opens, you can use delay(). You can call the method after the .open()
Like this:
<script type="text/javascript">
mgsjQuery(window).load(function () {
if(mgsjQuery(window).width() > 991) {
if(getCookie('newsletter')!='nevershow'){
if (mgsjQuery('#newsletter').length) {
mgsjQuery.magnificPopup.open({
items: {
src: '#newsletter'
},
type: 'inline'
}).delay(1000);
}
}
}
});
</script>
In this case, the delay function will wait 1 second (the parameter is given in miliseconds) before opening the popup.

ExtJs minify Gets ignored

We have a CMS so I don't have access to the header of the HTML page which gets rendered for our extjs implementation. So I had to make a workaround which is like this:
Ext.local = {};
var lang = {
initLang: function (revisionNr) {
var local = localStorage.getItem('localLang')
if (!local) {
AjaxHandlerByClass('ajax/lang/webuser/init', {}, this.loadLangRemote);
} else {
local = JSON.parse(local);
if (local.revisionNr == config.revisionNr && local.lang == config.lang) {
console.log('loading local lang variables');
if (local.date < new Date().getTime() - (24 * 60 * 60 * 1000) * 2) {//2 day caching time before retry
delete window.localStorage.localLangBackup;
}
this.loadLangLocal(local);
} else {
delete window.localStorage.localLang;
AjaxHandlerByClass('ajax/lang/webuser/init', {}, this.loadLangRemote);
}
}
},
loadLangRemote: function (data) {
data.revisionNr = config.revisionNr;
data.lang = config.lang;
data.date = new Date().getTime();
lang.loadLangLocal(data);
localStorage.setItem('localLang', JSON.stringify(data));
},
loadLangLocal: function (data) {
var jsElm = document.createElement("script");
jsElm.type = "application/javascript";
jsElm.src = 'js/freetext-deploy.min.js?rev={/literal}{$revisionNr}{literal}';
document.getElementsByTagName('head')[0].appendChild(jsElm);
Ext.Date.defaultFormat = 'd-m-Y';
if (!debug) {
Ext.Loader.config.disableCaching = true;
}
Ext.application({
name: 'freetextOrder',
appFolder: 'modules/extjs/freetextOrder/app',
controllers: [
'Main'
],
launch: function () {
var freetextOrder = Ext.create('Ext.container.Container', {
renderTo: Ext.get('freetextOrderDiv'),
layout: 'fit',
id: 'catalogAdministrationDiv_ext',
height: 800,
cls: 'x-dig-override',
items: [Ext.create('freetextOrder.view.base.MainView', {})],
layout:'fit'
});
}
});
Ext.local = data;
}
};
lang.initLang();
The problem I'm having is that the minified version gets ignored completely. I see it load on the http request but extjs ignores them.... even though I can see the objects are being created after include (via console log)
Anyone any idea how I can achieve this?
as i see none found the answer so i post my own here wich i came up with.
Since i could for the love of god not load the damn thing i refactored the loader and exported it into a Js. file. wich i reqired and called later on in code.
exported lang.js file:
Ext.define('Lang', {
singleton: true,
ApplicationConf: null,
Launch: function (launchConfig) {
this.ApplicationConf = launchConfig;
var local = localStorage.getItem('localLang');
var me = this;
this.loadLangRemote = function (data) {
debugger;
data.revisionNr = config.revisionNr;
data.lang = config.lang;
data.date = new Date().getTime();
me.loadLangLocal(data);
localStorage.setItem('localLang', JSON.stringify(data));
};
this.loadLangLocal = function (data) {
Ext.local = data;
Ext.lang = function (langId) {
if (Ext.local[langId]) {
return Ext.local[langId];
}
delete window.localStorage.localLang;
localStorage.setItem('localLangBackup', true);
return langId;
}
Ext.application(me.ApplicationConf);
};
if (!local) {
Ext.Ajax.request({
url: 'ajax/lang/webuser/init',
params: {
sid: sid,
},
success: function (data) {
debugger;
me.loadLangRemote(Ext.JSON.decode(data.responseText));
}
})
} else {
local = JSON.parse(local);
if (local.revisionNr == config.revisionNr && local.lang == config.lang) {
console.log('loading local lang variables');
if (local.date < new Date().getTime() - (24 * 60 * 60 * 1000) * 2) {//2 day caching time before retry
delete window.localStorage.localLangBackup;
}
debugger;
me.loadLangLocal(local);
} else {
delete window.localStorage.localLang;
Ext.Ajax.request({
url: 'ajax/lang/webuser/init',
params: {
sid: sid,
},
success: function (data) {
me.loadLangRemote(Ext.JSON.decode(data.responseText));
}
})
}
}
},
})
And IMPORTANT was to add the
Ext.onReady(function () {
Lang.Launch({
name: 'catalogAdministration',
appFold....
To the call of the Launch function in code, bacause it would have been not defined at run time. i added the file to the minified file first and call the Lang.Launch instead Ext.Application.
Hope somone has use of my solution :)

Displaying a jgrowl message after X seconds?

I'm implementing jgrowl on my website, but did not find any indication on the plugin's website nor on the internet on how to display the message with a lag. Ideally I'd like the Jgrowl message to appear 10 seconds after the page loads. Is it possible?
<script type="text/javascript">
$(function () {
if($.cookie("new_visitor") != "true") {
$.cookie("new_visitor", "true", { expires: 1, path: '/' });
$.jGrowl("A message with a header", { header: 'Important' });
}
});
</script>
exactly what the others said. See it in code.
$(function () {
if($.cookie("new_visitor") !== "true") {
$.cookie("new_visitor", "true", { expires: 1, path: '/' });
setTimeout(function(){
$.jGrowl("A message with a header", { header: 'Important' });
},10000); // display after 10 seconds
}
});

Categories

Resources