Make images become unavailable when screen is not on fullscreen - javascript

I'm currently making my own card game with JS. The board randomly generates your deck with 5 images and displays them on the screen.
I've tried to make it so when you click on an image, it shows up in the game area, like simulating that you've "chosen that card" to play. With JQuery:
$("#img5").click
(
function()
{
var carta = document.images["img5"].src;
document.images["carta2"].src = carta;
}
);
Ok, but the thing is that I only want that to happen when you are on fullscreen mode, so I made this logic:
pantallaCompleta = false;
contadorScreen = 0;
document.onfullscreenchange = function(event)
{
contadorScreen = contadorScreen + 1;
if(contadorScreen % 2 === 0)
{
pantallaCompleta = false;
console.log("Exiting fullscreen");
console.log(contadorScreen);
console.log(pantallaCompleta);
}
else
{
pantallaCompleta = true;
console.log("Entering fullscreen");
console.log(contadorScreen);
console.log(pantallaCompleta);
}
};
The logic works so when you load the page, you're not on fullscreen mode so counter equals = 0 and check = false. Then, when document.onfullscreenchange = function(event) happens counter equals counter++ and check changes to true.
Okay, so with all of that combined and working, I try to put the JQuery code inside this:
if(pantallaCompleta == true)
It never works. The console.log(pantallaCompleta); is telling me that the check is true or false with accuracy, but the click on images never works.
Does anyone have an idea of what could be wrong?

Currently you have
if(pantallaCompleta == true) {
$("#img5").click(function() {
var carta = document.images["img5"].src;
document.images["carta2"].src = carta;
});
}
This will only set an event listener on img5 if pantallaCompleta is true when this code runs, which is likely on page load.
I suggest you want an event listener that is always assigned (no matter the state of pantallaCompleta), but checks to see if that value is true or false before changing the img src.
$("#img5").click(function() {
if(pantallaCompleta == true) {
var carta = document.images["img5"].src;
document.images["carta2"].src = carta;
}
});

Related

How to synchronise ExtJS "checkboxes" (buttons) with Javascript/JQuery?

I am currently trying to synchronize two checkboxes on a page.
I need the checkboxes to be synchronized - to this end, I'm using a Tampermonkey userscript to pick up when one of them is clicked. However, I'm at a loss as to how to do it.
I believe they are not actually checkboxes, but ExtJS buttons that resemble checkboxes. I can't check whether they're checked with JQuery because of this: the checked value is appended to a class once the JS behind the button has run.
I have tried preventDefault and stopPropagation, but either I'm using it wrong or not understanding its' usage.
I'm not quite clever enough to just call the JS behind the box instead of an onclick event. Otherwise, that would solve my issue.
This is my code:
//Variables - "inputEl" is the actual button.
var srcFFR = "checkbox-1097";
var destFFR = "checkbox-1134";
var srcFFRb = "checkbox-1097-inputEl";
var destFFRb = "checkbox-1134-inputEl";
//This checks if they're synchronised on page load and syncs them with no user intervention.
var srcChk = document.getElementById(srcFFR).classList.contains('x-form-cb-checked');
var destChk = document.getElementById(destFFR).classList.contains('x-form-cb-checked');
if (srcChk == true || destChk == false) {
document.getElementById(destFFRb).click();
} else if (destChk == true || srcChk == false) {
document.getElementById(srcFFRb).click();
}
//This is where it listens for the click and attempts to synchronize the buttons.
$(document.getElementById(srcFFRb)).on('click', function(e) {
e.preventDefault();
if (document.getElementById(srcFFR).classList == document.getElementById(destFFR).classList) {
return false;
} else {
document.getElementById(destFFRb).click();
}
});
$(document.getElementById(destFFRb)).on('click', function(e) {
e.preventDefault();
if (document.getElementById(srcFFR).classList == document.getElementById(destFFR).classList) {
return false;
} else {
document.getElementById(srcFFRb).click();
}
});
I'm at a bit of a loss...any help would be greatly appreciated.
Figured it out - I was comparing class lists without singling out what I wanted to actually match.
My solution:
$(document.getElementById(srcFFRb)).on('click', function(){
if (document.getElementById(srcFFR).classList.contains('x-form-cb-checked')
== document.getElementById(destFFR).classList.contains('x-form-cb-checked')) {
return false;}
else {
document.getElementById(destFFRb).click();;
}});
$(document.getElementById(destFFRb)).on('click', function(){
if (document.getElementById(srcFFR).classList.contains('x-form-cb-checked')
== document.getElementById(destFFR).classList.contains('x-form-cb-checked')) {
return false;}
else {
document.getElementById(srcFFRb).click();;
}});

Keypress Gestures using Tampermonkey for Chrome

I'm working on a tampermonkey userscript to replace a feature that existed with FireGestures back in Pre-Quantum Firefox. The ability to open all hovered links into new background tabs. So having a combination keypress, which in FG was Ctrl + Right Click and drawing a gesture trail though every link you wanted open. Everything I have so far has been written for me by somebody else so I'm not trying to take credit and I in am way over my head. I don't have the know-how to edit and fix what is needed. This is what I have so far.
(function(delay, t, lnk, clicked) {
//config: delay before click. mouse movement will reset the delay timer.
delay = 1000; //in milliseconds. 1sec = 1000ms
t = 0;
function mousemove() {
clearTimeout(t);
if (lnk) t = setTimeout(clickLink, delay);
}
function clickLink() {
removeEventListener("mousemove", mousemove);
clearTimeout(t);
if (lnk) {
lnk.target = "_blank";
lnk.click();
lnk.target = "";
clicked = true;
}
}
addEventListener("mouseover", function(ev, el, el2) {
el = ev.target;
removeEventListener("mousemove", mousemove);
clearTimeout(t);
while (el) {
if (el.tagName === "A") {
el2 = el;
if (el !== lnk) {
lnk = el;
clicked = false;
addEventListener("mousemove", mousemove);
clearTimeout(t);
t = setTimeout(clickLink, delay);
}
return;
}
el = el.parentNode;
}
if (!el2) {
lnk = null;
clicked = false;
removeEventListener("mousemove", mousemove);
clearTimeout(t);
}
});
})();
There is a couple issues I face.
1. This doesn't require any sort of button combination. It is continually active and will click any link that is hovered over for the specified length of time. I would prefer it to only function when a button combination is pressed, ideally Ctrl + Rightclick. I found a thread dealing with combination keypresses but wouldn't know how to edit it and insert it into the existing script to fit my needs.
document.addEventListener ("keydown", function (zEvent) {
if (zEvent.ctrlKey && zEvent.altKey && zEvent.code === "KeyE") {
// DO YOUR STUFF HERE
}
} );
2. The pop-up blocker in chrome actually prevents these tabs from opening. I don't know if there is any way of remedying this other than turning off the pop-up blocker, but if there was I'd appreciate the help
3. This script opens up tabs in the foreground rather than the background. So opening up a bunch of links on a page wouldn't be possible because it would navigate to the new tab as soon as the first link is clicked. My original idea for fixing this was to just have the script just do a middle-click mouse event over every link it passed over, but I don't even know if that is something that is possible or practical.
I know I am asking a lot but I was just hoping that someone out there that knows what they are doing could help me out by either editing what I already have or writing something out themselves. I appreciate any help provided.
here's my spin on it. This is toggled rather than going on while you are holding onto the keys.
you could had the following to your TamperMonkey script, and when you press "Ctrl + Alt + S", the links on the page are modified and appended a onmouseover event. when you hit the key combination again, the event gets removed from the link. Short and simple.
document.addEventListener('keydown', function (zEvent) {
if (zEvent.ctrlKey && zEvent.altKey && zEvent.code === 'KeyS') {
var links = document.getElementsByTagName('a');
console.log(links.length);//how many links have been grabbed
for (var i = 0; i < links.length; i++) {
if (links[i].onmouseover !== null && links[i].onmouseover.toString().indexOf('function openit') > -1)
{
//toggling the funcitonality off
//remove it
links[i].setAttribute('target', '');
links[i].setAttribute('onmouseover', '');
}
else
{
//toggling the funcitonality on
//add it
links[i].setAttribute('target', 'blank');
links[i].setAttribute('onmouseover', 'function openit(elem){console.log(\'userScript will click on the link\');elem.click();};openit(this);');
}
}
}
}
);
As for popup blocking... I don't know.

Can't make sens out of javascript event and functions

Here is the code that works as-is, a classic onBeforeUnLoad event, in the <script type="text/jscript"> tag of my ASP page :
window.onbeforeunload = function (e) {
a = 1;
e = e || window.event;
e.preventDefault = true;
e.cancelBubble = true;
e.returnValue = "do you wish to save?";
}
Now, two issues i'm experiencing when wanting to do something more complex :
I want this to appear only once at all cost :
var a = 0;
window.onbeforeunload = function (e) {
if (a == 0) {
a = 1;
e = e || window.event;
e.preventDefault = true;
e.cancelBubble = true;
e.returnValue = "Wish to save?";
}
}
//Does not work...
I want it to be able to run this other function that works when not combined with the first :
comfirmExit = function(){
if (confirm("Wish to save?") == true) {
document.getElementById('<%= btnEnregistrer.ClientID %>').click();
}
}
// works, but not when combine to the first function
I tried to put this all together... I want the unload event to make my confirm box function run :
window.onbeforeunload = function (e) {
if (a == 0) {
a = 1;
comfirmExit = function(){
if (confirm("Wish to save?") == true) {
document.getElementById('<%= btnEnregistrer.ClientID %>').click();
}
}
}
And now I realize I'm far from being an expert of javascript...
The beforeunload event won't run any obtrusive Javascript for the user (ie alert, confirm etc).
But there is an workaround, the steps should be something like:
Create a boolean flag to check if the user has canceled the exiting of your page (default false).
Create the beforeunload event handler, and check if the game is not
saved.
If it was already saved, then, you do nothing, and let the user go
But if it was not, then you change that boolean flag to true.
You keep an interval dirty-checking if that variable is true, and at anytime it is, you save the game for the user, and then set this variable to false again.
So, doing that, you'll ensure the user always see a message if they're leaving without saving, and if they cancel the exiting, the game will be automatically saved, making the next try pretty smooth.
Take a look at the example below. To test it, open your console, click on Run. Then, try to click on Run again, and you'll see an exiting message. If you confirm it, your console won't show anything. But if you cancel it, then, you'll be kept in the page, then you try to click Run again, and you'll see that no message will appear, but the console will log true.
(function() {
var game = { saved: false };
var canceled = false;
setInterval(function() {
if (canceled) {
game.saved = true;
canceled = false;
}
}, 100);
window.onbeforeunload = function() {
if (!game.saved) {
canceled = true;
return 'Are you sure?';
}
else {
console.log(game.saved);
}
}
})();

KeyboardState.pressed is always true after .prompt or alert - Why?

As the title says, I have tried THREEx and Stemkovskis standalone KeyboardState.js , and neither of them seems to update properly.
This is my code:
m_vKeyboard = new THREEx.KeyboardState();
// m_vKeyboard.update(); // if using stemkovskis
if (m_vKeyboard.pressed("F")) {
alert("And now it is always true!");
}
you click the F key once, release it; alert window pops up, click OK, it pops up again for all eternity. How come?
Many browsers repeat keydown. Read more here and here (ctrl+f : auto-repeat).
Here's a proposed solution for your specific problem :
A. when keydown store its state as true in some array and make it false on keyup.
wasPressed['F'] = true; //on keydown
wasPressed['F'] = false; //on keyup
B. when checking for next keydown check its state as well.
if (m_vKeyboard.pressed("F") && !wasPressed['F'])
Find full implementation : Here
UPDATE
var wasPressed = {};
if( keyboard.pressed('F') && !wasPressed['f'] ){
alert("F was pressed");
prompt("Enter data : ");
wasPressed['f'] = true;
}
UPDATE 2
keyboard.domElement.addEventListener('keydown', function(event){
wasPressed = {};
})
I'm wondering if it has something to do with alert() being a blocking call. Using the code below gives me your same issue. If I comment out the alert() and un-comment the console.log() it seems to work fine. However, I'm not sure if that helps your issue.
var m_vKeyboard = new THREEx.KeyboardState();
setInterval(function () {
var key = "F";
var pressed = m_vKeyboard.pressed(key);
alert("And now it is always true!");
//console.log("key", key, "pressed", pressed);
}, 100);
Just add this to the beginning of onKeyDown in KeyboardState.js:
if (event.repeat) return;

Javascript function works not as intended when I move mouse too quickly. Ideas on how to improve?

I have a drag-and-droppable control on my page. It has a client-side event 'OnClientDragging' which I am using to provide highlighting to my page. The idea is that there are various zones on the page and, as the user drags the control over parts of the page, the page gets highlighted accordingly.
The problem is that I see the highlighting flicker slightly when moving fast. I do not see any exceptions being thrown, but if I move the mouse rapidly while staying inside of one 'zone' I still see the highlighting being removed and re-added. I can only assume this is because the method is not completing in time -- and fires again due to being dragged more.. which causes unintended issues?
function RemoveHighlighting(dockZone) {
if (dockZone.get_docks().length == 0) {
dockZone.removeCssClass("zoneDropOk");
}
}
function AddHighlighting(dockZone) {
if (dockZone.get_docks().length == 0) {
dockZone.addCssClass("zoneDropOk");
}
}
var previousZone = null;
//Evaluates whether the currently moused-over item is a RadDockZone.
function TryGetZoneFromTarget(target) {
while (target != null && target.id) {
if (target.id.indexOf("RadDockZone") != -1) {
return $find(target.id);
}
target = target.parentNode;
}
return null;
}
//Adds highlighting to the dockZones when the user is dragging objects to the screen.
//Clear the old dockZone as the user moves out of it, and color new ones as they move into it.
function OnClientDragging(sender, eventArgs) {
var target = eventArgs.get_htmlElement();
var zone = TryGetZoneFromTarget(target);
if (zone) {
var currentZone = zone;
dockZoneDroppedOnID = zone.get_id();
if (previousZone == null) {
previousZone = currentZone;
$.queue(AddHighlighting(currentZone));
}
else if (previousZone != currentZone) {
$.queue(RemoveHighlighting(previousZone));
previousZone = currentZone;
$.queue(AddHighlighting(currentZone));
}
}
else {
dockZoneDroppedOnID = "";
if (previousZone != null && $.queue.length == 0) {
RemoveHighlighting(previousZone);
previousZone = null;
}
}
}
Should I be trying to make this script more efficient, or maybe setting a variable outside the local scope to indicate that the previous event is still running and cancel the current event?
EDIT: I've edited in a queue solution which worked well! I'm not sure if it's a perfect solution, but it solved my issue.
I think setting variables outside this scope will be a more effective approach, in particular, you can either make use of or emulate the way jQuery's fx queue works.

Categories