Window.onblur with if statement - javascript

I am building kind of clock and I strongly need to use settimeout().
However, Google Chrome and Safari doesn't allow settimeout() when tab inactive. So, I decided to reloading page when tab active again. (I know, it's not proper way to do it, but I am new at javascript and tried to learn.) I saw this answer and tried to implement to my case. But there is a challenge, I have 3 modals in this page and I don't want reload page when modals are open.
So, I added a global variable equels an integer then changed the value of variable when modals are open.
Here is my code,
var modalCheck = 2;
function openModal() {
var doneModal = document.getElementById("done");
var done = document.getElementsByClassName("closeMessage")[0];
modalCheck = 1;
doneModal.style.display = "block";
done.onclick = function() {
doneModal.style.display = "none";
modalCheck = 2;
}
window.onclick = function(event) {
if (event.target == doneModal) {
doneModal.style.display = "none";
modalCheck = 2;
}
}
}
window.onblur = function() {
window.onfocus= function () {
if (modalCheck = 2) {
console.log(modalCheck);
location.reload(true);
}
}
};
Page reloading is still working, but if modals are opened page reaload immediately.
My question is why this is not working? Is there a syntax error or something like that? What is the solution?

Here's the problem:
if ( modalCheck = 2 ) {
This "if" condition is always true, because you're actually assigning the value "2" to "modalCheck" rather than checking whether "modalCheck" equals "2". The assignment resolves to the value "2", which is treated as a "truthy" expression in your if statement. So this if statement never fails. I recommend
if ( modalCheck === 2 ) {
Others have suggested "if ( modalCheck == 2 ) {", but it's generally better to compare using === rather than == to avoid unexpected weirdness.

i don't know what your html part is, try this code
var modalCheck = 2;
function openModal() {
var doneModal = document.getElementById("done");
var done = document.getElementsByClassName("closeMessage")[0];
modalCheck = 1;
doneModal.style.display = "block";
done.onclick = function() {
doneModal.style.display = "none";
modalCheck = 2;
}
window.onclick = function(event) {
if (event.target == doneModal) {
doneModal.style.display = "none";
modalCheck = 2;
}
}
}
window.onblur = function() {
this.addEventListener('focus',function(){
if (modalCheck == 2) {
console.log(modalCheck);
location.reload(true);
}});
};

Related

How to get addEventListener click event to work on IOS with vanilla javascript

So I encountered something weird today (at least to me). I'm trying to do a basic click event that adds and removes a class to a div with some css animations. This is an image slider I'm building. It works fine on Safari, Chrome etc on desktop. But on Iphone it seems like it only works the first time it's clicked or touched. Looks like it doesn't remove the class so it can be added again..
I did try to add this to check for user agent and adding touchstart with no luck:
var ua = navigator.userAgent,
event = ua.match(/iPad/i) || ua.match(/iPhone/) ? "touchstart" : "click";
I also added all the prefixes I could find to the css but since it is working the first time it's probably not the issue.
Hope someone have an idea of what's going on.
const clientBtn = document.querySelectorAll(".client-btn");
let clientSliderContainer = document.querySelectorAll(
".field-clientslider-container__wrapper"
);
clientSliderContainer[0].style.display = "grid";
let clientNumber = 0;
clientBtn.forEach(function (button) {
button.addEventListener('click', function () {
clientSliderContainer[clientNumber].style.display = "none";
clientSliderContainer[clientNumber].classList.remove("fadein");
if (button.classList.contains("client-slider-prev-btn")) {
clientNumber--;
if (clientNumber < 0) {
clientNumber = clientSliderContainer.length - 1;
}
clientSliderContainer[clientNumber].style.display = "grid";
clientSliderContainer[clientNumber].classList.add("fadein");
}
if (button.classList.contains("client-slider-next-btn")) {
clientNumber++;
if (clientNumber > clientSliderContainer.length - 1) {
clientNumber = 0;
}
clientSliderContainer[clientNumber].style.display = "grid";
clientSliderContainer[clientNumber].classList.add("fadein");
}
});
});
Ok so I found out it indeed was that, my class was not being removed properly. I thought I handled that by removing the class in the beginning of my listener callback. But I just made a fix where I did a setTimeout() to remove the class after a few milliseconds instead. That did the trick.
clientBtn.forEach(function (button) {
button.addEventListener('click', function (event) {
clientSliderContainer[clientNumber].style.display = "none";
if (event.currentTarget.classList.contains("client-slider-prev-btn")) {
clientNumber--;
if (clientNumber < 0) {
clientNumber = clientSliderContainer.length - 1;
}
clientSliderContainer[clientNumber].style.display = "grid";
clientSliderContainer[clientNumber].classList.add("fadein");
setTimeout(function() {
clientSliderContainer[clientNumber].classList.remove("fadein");
}, 1000);
}
if (event.currentTarget.classList.contains("client-slider-next-btn")) {
clientNumber++;
if (clientNumber > clientSliderContainer.length - 1) {
clientNumber = 0;
}
clientSliderContainer[clientNumber].style.display = "grid";
clientSliderContainer[clientNumber].classList.add("fadein");
setTimeout(function() {
clientSliderContainer[clientNumber].classList.remove("fadein");
}, 1000);
}
});
});

(Javascript) Script won't count just once, perhaps not recognizing variable?

I'm sure this is a super easy fix and I just can't see it..
I have a play button and I only want it to write to database (inc playcount) only when it's clicked the first time.
Any idea why this doesn't work? This result counts every click, and if I do if countonce = 0 and declare at beginning as 0 it won't count any clicks. Am I misunderstanding javascript?
<div id="left-05-play_">
<script type="text/javascript">
var currsong = 1;
var playcountadd = document.getElementById('left-05-play_');
playcountadd.onclick = function() {
if (countonce != 1) {
$.post( "php/songadd.php", { addsong: "1", } );
var countonce = 1;
} }
</script>
</div>
Thank-you for taking the time to read this question.
This should do the trick.
var currsong = 1;
var songadded = false;
var playcountadd = document.getElementById('left-05-play_');
playcountadd.onclick = function() {
if (!songadded) {
$.post( "php/songadd.php", { addsong: "1", } );
songadded = true;
}
}
Changed countonce to songadded
Moved songadded out of onclick function
Changed songadded to boolean logic
Check whether songadded=false before proceeding with AJAX post

Hide div with js, but without affecting html code

Let's say we have a div with id = '123'
Ho to make it invisible with js without affecting its html code?
So document.getElementById('123').style.display = 'none' is not an option.
JS only
UPD:
I just have interesting task! I have to hide some comments with js from guestbook , but when I change html code to hide it, Server somehow understands what I've done and redirects me to warning Page. So I have to do something with that.
UPD2:
I had obfuscated script on my page
function check_divs() {
var try_again = true;
var arr_divs = document.getElementById('content').getElementsByTagName('div');
if (arr_divs.length != divs_count) {
try_again = false;
} else {
for (var i = 0; i < arr_divs.length; i++) {
if ((arr_divs[i].style.display == 'none') || (arr_divs[i].style.position == 'absolute')) {
try_again = false;
};
};
}; if (try_again) {
setTimeout(check_divs, 998);
} else {
document.location.href = '/alert.html';
};
}
This one, so my solution was to clear all timeouts.
document.getElementById('123').style.visibility = 'hidden';
or
document.getElementById('123').setAttribute('style','display:none');
or
document.getElementById('123').setAttribute('style','visibility:hidden');
or if you have jQuery libraries
$('#123').css('visibility','hidden')
or
$('#123').css('display','none')
Any of that help?

JS function that stops another JS function

I have two JS functions: a load() function that displays a progress bar and a kill () function that stops the execution of the load once the page is loaded.
Now when another page is loaded the progress bar is not displayed, knowing that the load function is called on every page.
Any hints on where the problem might be and if there is a way to fix it.
Here is my code:
<script type="text/javascript">
var count=0;
function load(i) {
j = parseInt(i);
document.getElementById("progressBar").style.display = "block";
count=count+1;
if (document.all) {
document.all.btn1.value=count+'%';
document.all.progressbar.pic1.width=2*count;
}
else {
document.getElementById("pic1").width=2*count;
document.getElementById("bar").width=count+'%';
}
if (count<100) {
setTimeout('load(j)',j);
}
if(count==100) {
document.getElementById("progressBar").style.display = "none";
count=0;
}
}
function kill(){
if (document.applets[0].isActive()) {
document.getElementById("progressBar").style.visibility = "hidden";
}
}
</script>
Thank you in advance !
In load() you're changing display to block, but in kill() you set visibility to hidden; you should set display to none instead, so it can properly be set to block again next time. Read about visibility.
Optimized code:
<script type="text/javascript">
var count = 0,
win = window,
doc = document,
progressBar = doc.getElementById("progressBar"),
t, j;
function load(i) {
j = parseInt(i);
progressBar.style.display = "block";
count++;
// no actual need to check if doc.all is available
// just select through id
doc.getElementById("pic1").style.width = 2*count;
doc.getElementById("bar").style.width = count+'%';
if (count < 100) {
t = win.setTimeout('load(j)',j);
} else {
progressBar.style.display = "none";
win.clearTimeout(t);
count = 0;
}
}
function kill(){
if (doc.applets[0].isActive()) {
progressBar.style.display = "none";
}
}
</script>
If you assign setTimeout to a variable, you can use clearTimeout on it to stop it.
E.g.
set the timeout with
t = setTimeout('load(j)',j);
then stop it with
clearTimeout(t); Let me know if that helps, and makes sense :)

Delay to run code (prototype)

I am modifing a Magento template, and want to have 1-2s delay to run 2 line:
popup.style.display = 'none';
$(menuId).removeClassName('active');
I don't understand javascript at all, how can I do this, thanks
function wppHideMenuPopup(element, event, popupId, menuId)
{
element = $(element.id); var popup = $(popupId); if (!popup) return;
var current_mouse_target = null;
if (event.toElement)
{
current_mouse_target = event.toElement;
}
else if (event.relatedTarget)
{
current_mouse_target = event.relatedTarget;
}
if (!wppIsChildOf(element, current_mouse_target) && element != current_mouse_target)
{
if (!wppIsChildOf(popup, current_mouse_target) && popup != current_mouse_target)
{
popup.style.display = 'none';
$(menuId).removeClassName('active');
}
}
}
use window.setInterval("javascript function",milliseconds);
Usage > window.setInterval("hidethething()",2000);
Just place that (and replace with the correct function) wherever you want to start counting the 2 secs.
Thanks,
#leo

Categories

Resources