I have a JS that plays a notification sound on the arrival of any new notifications. It works completely fine when a new notification comes, it should play the sound and it does play.
The notification I am talking about is only an integer which is returned from a query through an ajax call. I set this integer into my <asp:label.../> through the script.
The problem is : I have written the script on MasterPage. So every time I open a new page, or a refresh the same one the <asp:Label.../> gets cleared which I set from my script using .html(value) causing the script to run the sound again as every time the page refreshes or another page is loaded.
The problem may be is , that the value is not persistent ?
I want that the value should be set to the html of the label and also its value should be persistent on all the pages . What should I do for this persistence ?
My Script is :
myFunction();
function myFunction() {
$.get("AjaxServicesNoty.aspx", function (data) {
var recievedCount = parseInt(data);
alert(recievedCount);
var existingCount = $(".lblEventCount").text();
if (existingCount == "") {
existingCount = 0;
alert(existingCount);
} else {
existingCount = parseInt($(".lblEventCount").text());
alert(existingCount);
}
// if (existingCount == "" && recievedCount != 0) {
// $(".lblEventCount").html(recievedCount);
// $(".lblAcceptedCount").html(recievedCount);
// var sound = new Audio("Sound/notificationSound.wav");
// sound.play();
// }
if ((parseInt(recievedCount) > parseInt(existingCount)) && existingCount == 0) {
$(".lblEventCount").html(recievedCount);
$(".lblAcceptedCount").html(recievedCount);
var sound = new Audio("Sound/notificationSound.wav");
sound.play();
} else {
$(".lblEventCount").html(existingCount);
$(".lblAcceptedCount").html(existingCount);
}
});
}
setInterval(myFunction, 5000);
use DIV ID instead of selecting via class
$("#divID").html(existingCount);
Related
I use Elementor Pro.
I have a button that is limited to 7 clicks, when clicking number 7 is disabled, and this is saved in localstorage to display later.
My problem if the user login from different device, the count start againg in 0. and obviously the code don't work for my need, The user after 7 click Never can click again.
How can resolve this?
this is the code:
<script>
// On page load (or in whatever event creates the button)
window.addEventListener("load", ()=>{
// Read the saved state from local storage (if not yet saved, will be null)
let clickcount3 = localStorage.getItem("localStorage.clickcount3");
if(localStorage.clickcount3>6)
document.getElementById("showResultMasPack").style.visibility = "visible";
});
function CounterMastPack() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount3) {
localStorage.clickcount3 = Number(localStorage.clickcount3)+1;
} else {
localStorage.clickcount3 = 1;
}
document.getElementById("resultMastPack").innerHTML = localStorage.clickcount3 + " Click(s).";
} else {
document.getElementById("resultMastPack").innerHTML = "Sorry, your browser does not support web storage...";
}
if(localStorage.clickcount3>6)
document.getElementById("showResultMasPack").style.visibility = "visible";
}
</script>
I am pretty new to this whole jquery and javascript thing as I have really worked with server side languages. However, I have a challenge here where If the specific data received($status) is not the same with the one provided(queu or successf), the page should reload to fetch the data($status), and it should do this to a set number of time, if it reloads the page according to the number of time set; whether or not the data($status) is returned true, I want it to entirely stop reloading the page and exit.I have tried doing it this way; but I am not quite sure what I am missing.
$(document).ready(function($) {
var number_of_time_loaded = 7000;
var queue = '$status';
var inter;
if (queue == 'queu' || queue == 'successf') {
alert('successfully uploaded');
} else {
alert('kindly wait for some minutes');
for (;number_of_time_loaded < 70000;) {
inter = setInterval(function() {
window.location.reload(1);
}, number_of_time_loaded++);
if (number_of_time_loaded >= 21000) {
clearInterval(inter);
} else {
number_of_time_loaded++
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
So you checking a variable that is written by PHP. You are saying if this variable is not a certain value, you want the page to reload after a set period of time. Refreshing the page will reset the JavaScript variables so you would have to use local storage to keep the state.
var maxAttempts = 10;
var queue = "<?php echo $status; ?>";
if (queue == 'queu' || queue == 'successf') {
// it is updated
console.log("Updated);
sessionStorage.removeItem("attempts");
} else {
var currentAttempts = sessionStorage.getItem("attempts") || 0;
currentAttempts++;
if (currentAttempts < maxAttempts) {
console.log("waiting for another attempt");
sessionStorage.setItem("attempts", currentAttempts);
window.setTimeout(function () { window.location.reload(); }, 5000); // wait 5 seconds
} else {
// too many attempts made
console.log("too many attempts made");
sessionStorage.removeItem("attempts");
}
}
Better solution would be an Ajax request instead of refreshing the page. An
other option is setting meta refresh header in PHP and not having to use JavaScript.
So in the PHP if variable is not set, you echo out <meta http-equiv="refresh" content="5">
I am creating a landing page which should exist in two languages. The texts that should be shown are in two JSON files, called accordingly "ru.json" and "en.json". When a user clicks on the "Change language" button, the following function is executed:
function changeLang(){
if (userLang == 'ru') {
userLang = 'en';
document.cookie = 'language=en';
}
else {
userLang = 'ru';
document.cookie = 'language=ru';
}
var translate = new Translate();
var attributeName = 'data-tag';
translate.init(attributeName, userLang);
translate.process();
}
Where Translate() is the following:
function Translate() {
//initialization
this.init = function(attribute, lng){
this.attribute = attribute;
if (lng !== 'en' && lng !== 'ru') {
this.lng = 'en'
}
else {
this.lng = lng;
}
};
//translate
this.process = function(){
_self = this;
var xrhFile = new XMLHttpRequest();
//load content data
xrhFile.open("GET", "./resources/js/"+this.lng+".json", false);
xrhFile.onreadystatechange = function ()
{
if(xrhFile.readyState === 4)
{
if(xrhFile.status === 200 || xrhFile.status == 0)
{
var LngObject = JSON.parse(xrhFile.responseText);
var allDom = document.getElementsByTagName("*");
for(var i =0; i < allDom.length; i++){
var elem = allDom[i];
var key = elem.getAttribute(_self.attribute);
if(key != null) {
elem.innerHTML = LngObject[key] ;
}
}
}
}
};
xrhFile.send();
}
Everything works fine, however, when a user opens the page for the first time, if his Internet connection is bad, he just sees the elements of the page without text. It is just 1-2 seconds, but still annoying.
The question is, is there any way to check the text has loaded and display the page elements only on this condition?
You can use $(document).ready() in this way
$(document).ready(function(){
//your code here;
})
You can use the JavaScript pure load event in this way
window.addEventListener('load', function () {
//your code right here;
}, false);
Source: Here
translate.process() is asynchronous code which needs to make a call to a server and wait for its response. What it means is that, when you call this function, it goes in the background to go do its own thing while the rest of the page continues loading. That is why the user sees the page while this function is still running.
One minimal way I can think around this is by adding this to your css files in the head tag.
body { display: none }
And then, under this.process function, after the for loop ends, add
document.body.style.display = 'block'
If you want to suppori IE8:
document.onreadystatechange = function () {
if (document.readyState == "interactive") {
// run some code.
}
}
Put the code you want to execute when the user initially loads the page in a DOMContentLoaded event handler like below:
document.addEventListener('DOMContentLoaded', function() {
console.log('Whereas code execution in here will be deffered until the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.');
});
console.log('This will log immediatley');
It's important to note that DOMContentLoaded is different than the load event
I'm trying to build a website locally using PHP and Javascript and MAMP.
What I'm looking for is to put a timer on every page of the website and that timer counts the time spent by the user in the whole website. Even if the user switches between pages the timer will still continue. The solution I've found only shows the time spent on each page and when I reload the same page again the timer restart from zero.
Here's the Javascript for the timer I did:
window.onload=function(){
time=0;
}
window.onbeforeunload=function(){
timeSite = new Date()-time;
window.localStorage['timeSite']=timeSite;
}
I've search everywhere for the solution but with no luck, if anyone knows how to do this please let me know.
Here's a working example. It will stop counting when the user closes the window/tab.
var timer;
var timerStart;
var timeSpentOnSite = getTimeSpentOnSite();
function getTimeSpentOnSite(){
timeSpentOnSite = parseInt(localStorage.getItem('timeSpentOnSite'));
timeSpentOnSite = isNaN(timeSpentOnSite) ? 0 : timeSpentOnSite;
return timeSpentOnSite;
}
function startCounting(){
timerStart = Date.now();
timer = setInterval(function(){
timeSpentOnSite = getTimeSpentOnSite()+(Date.now()-timerStart);
localStorage.setItem('timeSpentOnSite',timeSpentOnSite);
timerStart = parseInt(Date.now());
// Convert to seconds
console.log(parseInt(timeSpentOnSite/1000));
},1000);
}
startCounting();
Add the code below if you want to stop the timer when the window/tab is inactive:
var stopCountingWhenWindowIsInactive = true;
if( stopCountingWhenWindowIsInactive ){
if( typeof document.hidden !== "undefined" ){
var hidden = "hidden",
visibilityChange = "visibilitychange",
visibilityState = "visibilityState";
}else if ( typeof document.msHidden !== "undefined" ){
var hidden = "msHidden",
visibilityChange = "msvisibilitychange",
visibilityState = "msVisibilityState";
}
var documentIsHidden = document[hidden];
document.addEventListener(visibilityChange, function() {
if(documentIsHidden != document[hidden]) {
if( document[hidden] ){
// Window is inactive
clearInterval(timer);
}else{
// Window is active
startCounting();
}
documentIsHidden = document[hidden];
}
});
}
JSFiddle
Using localStorage may not be the best choice for what you need. But sessionStorage, and localStorage is most suitable. Have in mind that sessionStorage when opening a new tab resolves to a new session, so using localStorage has to do with the fact that if only sessionStorage was used and a user opened a new tab in parallel and visit your website would resolve to a new separate session for that browser tab and would count timeOnSite from start for it. In the following example it is tried for this to be avoid and count the exact timeOnSite.
The sessionStorage property allows you to access a session Storage
object for the current origin. sessionStorage is similar to
Window.localStorage, the only difference is while data stored in
localStorage has no expiration set, data stored in sessionStorage gets
cleared when the page session ends. A page session lasts for as long
as the browser is open and survives over page reloads and restores.
Opening a page in a new tab or window will cause a new session to be
initiated, which differs from how session cookies work.
function myTimer() {
if(!sessionStorage.getItem('firstVisitTime')) {
var myDate = Date.now();
if(!localStorage.getItem('timeOnSite')) {
sessionStorage.setItem('firstVisitTime',myDate);
} else {
if(localStorage.getItem('tabsCount') && parseInt(localStorage.getItem('tabsCount'))>1){
sessionStorage.setItem('firstVisitTime',myDate-parseInt(localStorage.getItem('timeOnSite')));
} else {
sessionStorage.setItem('firstVisitTime',myDate);
}
}
}
var myInterval = setInterval(function(){
var time = Date.now()-parseInt(sessionStorage.getItem('firstVisitTime'));
localStorage.setItem('timeOnSite',time);
document.getElementById("output").innerHTML = (time/1000)+' seconds have passed since first visit';
}, 1000);
return myInterval;
}
window.onbeforeunload=function() {
console.log('Document onbeforeunload state.');
clearInterval(timer);
};
window.onunload=function() {
var time = Date.now();
localStorage.setItem('timeLeftSite',time);
localStorage.setItem("tabsCount",parseInt(localStorage.getItem("tabsCount"))-1);
console.log('Document onunload state.');
};
if (document.readyState == "complete") {
if(localStorage.getItem("tabsCount")){
localStorage.setItem("tabsCount",parseInt(localStorage.getItem("tabsCount"))+1);
var timer = myTimer();
} else {
localStorage.setItem("tabsCount",1);
}
console.log("Document complete state.");
}
Working fiddle
If you want a server-side solution then set a $_SESSION['timeOnSite'] variable and update accordingly on each page navigation.
main question
Is there a javascript way to identify if we are accessing a page for the first time or it is a cause of a back?
My problem
I'm implementing html5 navigation in my ajax driven webpage.
On the main script, I initialize a variable with some values.
<script>
var awnsers=[];
process(awnsers);
<script>
Process(awnsers) will update the view according to the given awnsers, using ajax.
In the funciton that calls ajax, and replaces the view, I store the history
history.pushState(state, "", "");
I defined the popstate also, where I restore the view according to the back. Moreover, I modify the global variable awnsers for the old value.
function popState(event) {
if (event.state) {
state = event.state;
awnsers=state.awnsers;
updateView(state.view);
}
}
Navigation (back and forth) goes corectly except when I go to an external page, and press back (arrving to my page again).
As we are accessing the page, first, the main script is called,the valiable awnsers is updated, and the ajax starts. Meanwile, the pop state event is called, and updates the view. After that the main ajax ends, and updates the view according to empty values.
So I need the code:
<script>
var awnsers=[];
process(awnsers);
<script>
only be called when the user enters the page but NOT when it is a back. Any way to do this?
THanks!
Possible solution
After the first awnser I have thought of a possible solution. Tested and works, whoever, I don't know if there is any cleaner solution. I add the changes that I've done.
First I add:
$(function() {
justLoaded=true;
});
then I modify the popState function, so that is in charge to initialize the variables
function popState(event) {
if (event.state) {
state = event.state;
awnsers=state.awnsers;
updateView(state.view);
} else if(justLoaded){
awnsers=[];
process(awnsers);
}
justLoaded=false;
}
Thats all.
what about using a global variable?
var hasLoaded = false;
// this function can be called by dom ready or window load
function onPageLoad() {
hasLoaded = true;
}
// this function is called when you user presses browser back button and they are still on your page
function onBack() {
if (hasLoaded) {
// came by back button and page was loaded
}
else {
// page wasn't loaded. this is first visit of the page
}
}
Use cookie to store the current state.
yeah! This is what I have:
var popped = (($.browser.msie && parseInt($.browser.version, 10) < 9) ? 'state' in window.history : window.history.hasOwnProperty('state')), initialURL = location.href;
$(window).on('popstate', function (event) {
var initialPop = !popped && location.href === initialURL, state;
popped = true;
if (initialPop) { return; }
state = event.originalEvent.state;
if (state && state.reset) {
if (history.state === state) {
$.ajax({url: state.loc,
success: function (response) {
$(".fragment").fadeOut(100, function () {
$(".fragment").html($(".fragment", response).html()).fadeIn(100);
);
document.title = response.match(/<title>(.*)<\/title>/)[1];
}
});
} else { history.go(0); }
else {window.location = window.location.href; }
});
And:
$.ajax({url:link,
success: function (response) {
var replace = args.replace.split(",");
$.each(replace, function (i) {
replace[i] += ($(replace[i]).find("#video-content").length > 0) ? " #video-content" : "";
var selector = ".fragment "+replace[i];
$(selector).fadeOut(100, function () {
$(selector).html($(selector,response).html()).fadeIn(100, function () {
if (base.children("span[data-video]")[0]) {
if ($.browser.msie && parseInt($.browser.version, 10) === 7) {
$("#theVideo").html("");
_.videoPlayer();
} else {
_.player.cueVideoById(base.children("span[data-video]").attr("data-video"));
}
}
});
});
});
document.title = response.match(/<title>(.*)<\/title>/)[1];
window.history.ready = true;
if (history && history.pushState) { history.pushState({reset:true, loc:link}, null, link); }
}
});