Can you tell me why this alert does not work?
my js codes:
var character =
document.getElementById("character");
var block = document.getElementById("block");
function jump() {
if (character.classList != "animate") {
character.classList.add("animate");
}
setTimeout(function () {
character.classList.remove("animate");
}, 500);
var checkDead = setlnterval(function () {
var characterTop =
parseInt(window.getComputedStyle(character)
.getPropertyValue("top"));
var blockLeft =
parseInt(window.getComputedStyle(block)
.getPropertyValue("left"));
here is the if part (my problem): i want to know why it dose not work?
if (blockLeft<20 && blockLeft>0 && characterTop>=130) {
block.style.animation = "none";
block.style.display = "none";
alert("U Lose!");
}
}, 10);
}
If there will be two alert boxes when you run the code, then check the "prevent this page from creating additional dialog" checkbox. Refresh the page again and you won't get the alert box ever again.
Solution is that you need to close that webpage and reopen it again in the browser (don't need to close the entire browser). I am assuming you are using Chrome. Internet Explorer or Firefox don't have this checkbox feature.
Related
So I have a website where I can select links and click a button to open them all at the same time. When I do that Firefox takes me to one of the newly opened links automatically.
I wanted to stop this behavior, so I looked and looked, and eventually found this option:
browser.tabs.loadDivertedInBackground
Now, when I set this to true, newly opened tabs never automatically take me to them. So if I click an ad on a site that normally opens in a new tab and takes me to it, now it doesn't happen. I also tried this code:
<p><a href="#" onclick="window.open('http://google.com');
window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>
This code opens 2 links at the same time. I was thinking maybe opening multiple links at the same time somehow overrides Firefox. But no, the links opened and I was not automatically taken to any of the new tabs.
Also must be said that I'm having this problem in Firefox 75 and 74. But when I try it in Firefox 55.0.2, I don't have the problem. In Firefox 55.0.2 the "browser.tabs.loadDivertedInBackground" actually works even on the website where I have the problem (I can't share the site because it's behind login).
This appears to be the code responsible to open multiple links on the website I have an issue with:
$(document).on('click', '.statbtn', function () {
var me = $(this);
var isAnyRowSelected = false;
$('.row-checkbox').each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
$('select[name="status[' + t.val() + ']"]').val(me.attr('id'));
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
$(document).on('click', '.openlink', function () {
var me = $(this);
var isAnyRowSelected = false;
$($('.row-checkbox').get()).each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
console.log();
var win = window.open(t.data('link'), '_blank');
if (win) {
win.focus();
} else {
bootbox.alert('Please allow popups for this website');
}
}
});
So I tried everything I could think of. Many changes to the about:config, restarting my browser, unticking the "When you open a link in a new tab, switch to it immediately" option in Firefox. But nothing works. When I open links from this one site using this specific button, I always get automatically taken to one of the newly opened tabs.
Here is a similar-ish problem - https://www.reddit.com/r/firefox/comments/bnu6qq/opening_new_tab_problem/
Any ideas why this happens and how to fix it? I mean, a website shouldn't be able or allowed to override Firefoxe's native setting, right?
Okay, because I don't wanna be an ass, here is the solution.
$(document).on('click', '.statbtn', function () {
var me = $(this);
var isAnyRowSelected = false;
$('.row-checkbox').each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
$('select[name="status[' + t.val() + ']"]').val(me.attr('id'));
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
$(document).on('click', '.openlink', function () {
var me = $(this);
var isAnyRowSelected = false;
$($('.row-checkbox').get().reverse()).each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true;
console.log();
// var win = window.open(t.data('link'), '_blank');
setTimeout(() => window.open(t.data('link'), '_blank'),1000);
// if (win) {
// win.focus();
// } else {
// bootbox.alert('Please allow popups for this website');
// }
}
});
if(isAnyRowSelected == false){
bootbox.alert("No Orders Selected");
}
});
Basically, adding a "setTimeout" fixed it. For some reason Firefox needed the delay to process things correctly, I guess, I think. Before the delay, the actions would happen instantly, and I'll just guess that Firefox couldn't "catch up" to it in order to apply the exemption of not navigating to new tabs. But a timeout delay fixed it.
And for anyone that may run into this with a similar issue, it also required an edit in Firefox in "about:config" to set this to True.
browser.tabs.loadDivertedInBackground
That's all folks :)
Can someone help me find the mistakes in my code? The window won't close when "no" is entered after finishing a game and I just can't seem to find the mistake.
For context: I was trying to make a battleship game and to make it interactive with javascript. When the ship is hit the user is supposed to have the option to play again (the window reloads just fine) and if the user decides that he doesn't want to play anymore he just has to enter "no" and the window closes but that doesn't work for some reason. I can't seem to find the mistake no matter what I do. Does anyone more experienced have an idea?
var table = document.getElementById("buttons");
var len_board = document.getElementsByClassName("tr").length;
var button = document.getElementsByClassName("location")
//Places ships on the board randomly
function placeShips(len_board) {
window.random_row = Math.floor(Math.random() * (len_board - 1)) + 1;
window.random_column = Math.floor(Math.random() * (len_board - 1)) + 1;
};
//Save users choice and determine if ship is hit
function getId(element) {
var chosen_row = element.parentNode.parentNode.rowIndex
var chosen_column = element.parentNode.cellIndex
if ((random_row == chosen_row) && (random_column == chosen_column)) {
element.style.backgroundColor = 'red';
element.style.borderColor = 'red';
element.textContent = "X";
alert("you hit my ship");
var answer = prompt("Would you like to play again? Enter 'Yes' for
yes and 'No' for no:");
var answer = answer.toLowerCase();
if (answer == "yes") {
location = location;
}
else if (answer == "no") {
window.close();
}
else {
var reply = prompt("I'm sorry, " + answer + " is not a valid
input. Please try again: ");
var reply = reply.toLowerCase();
if (reply == "no") {
window.close();
}
else if (answer == "yes") {
location = location;
}
else {
window.close();
};
};
}
else {
element.style.backgroundColor = "#a9c8f9";
element.style.borderColor = "#a9c8f9";
};
};
A script can only close a window that was opened by the script. You can't close the main window that loaded the script.
Window.close() on MDN
This method is only allowed to be called for windows that were opened
by a script using the window.open() method. If the window was not
opened by a script, an error similar to this one appears in the
console: Scripts may not close windows that were not opened by script.
This was done for security reasons. I'm sure you wouldn't like it if you were browsing the web and all of a sudden your window closed along with all the back history after clicking on a random link from a reddit post.
Closing the current window
In the past, when you called the window object's close() method
directly, rather than calling close() on a window instance, the
browser closed the frontmost window, whether your script created that
window or not. This is no longer the case; for security reasons,
scripts are no longer allowed to close windows they didn't open.
(Firefox 46.0.1: scripts can not close windows, they had not opened)
Hello StackOver Flow friends!
Please I am a newbie
I need to convert this code to Jquery!
I am working on it but unable to make it work. I am learning javascript but I want to see how do the same code work in Jquery. What all I need.
Now, What this function do is:
When an audio starts and as the time limit of 30 sec gets over. It Shows a confirm box whether to login for listening to the audio further or not.
If user clicks 'OK' it redirects to a login page and If the User clicks close or cancel it refreshes the page. Now What I need is that I need to make the confirm box appear with css style. So I need to change it to jquery . Or what the Masters of code think would be perfect.
<script>
document.addEventListener("play", function (e) {
var audios = document.getElementsByTagName("audio");
for (var i = 0, len = audios.length; i < len; i++) {
if (audios[i] === e.target) {
e.target.addEventListener("canplaythrough", function () {
setTimeout(function () {
e.target.pause();
var r = confirm("Please Log in for more than 30s preview!");
if (r == true) {
//x = "You pressed OK!";
window.location.href = "https://www.google.com";
} else {
//x = "You pressed Cancel!";
location.reload();
}
},
30000);
}, false);
}
}
}, true);
</script>
I'm going to show "New message..." in title every second when browser tab is inactive or user is in other tabs. I used this:
<script>
var mytimer;
function log() {
document.title = document.title == "" ? "New message..." : "";
}
$(window).focusout(function () {
mytimer=setInterval(function () {
log();
}, 1000);
}).focusin(function () {
clearInterval(mytimer);
});
</script>
when user leaves current tab it starts to work but when it comes back to the tab it doesn't stop. Any idea what is wrong with that?
Solution:
I just changed focusout method to blur and focusin to focus and started to work in Firefox. In IE and Chrome works properly.
You are not setting the setInterval to myTimer.
mytimer = setInterval(function () {
log()
}, 1000);
Added a fiddle;
Focus the output window by clicking on it, and unfocus by clicking another frame.
Edit: Tested and working in chrome,firefox,ie, and opera. Flashes back and forth between original title and New Message like on irc.
$(function(){
var title = $('title').html();
var thread = null;
$(window).focusout(function () {
var i = 0;
thread = setInterval(function(){
if(i % 2 == 0 || i == 0){
$('title').html("New Message..");
}else{
$('title').html(title);
}
i++;
},500);
}).focusin( function(){
clearInterval(thread);
$('title').html(title);
});
});
Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.