JQuery .show() works only from click event - javascript

I am trying to write a simple game using two.js. I have a function which is called either from button click event and from game loop:
function endGame(gameLoop){
showStartGame();
gameLoop.pause();
$("#gameSquare svg:first").remove();
$("#startGame").show();
}
The line $("#startGame").show() executes correctly only when called from the event, the rest works perfectly fine in both cases.
Click event handler:
$("#abandonGame").click(function(){
endGame(two);
gameLoopPaused = true;
gameStarted = false;
});
The call that doesn't work properly(this.update() is called inside game loop):
this.update = function(){
var computedVector = new Two.Vector(0,0);
screens.forEach(function(screen){
screen.update(speed);
screen.getRectangles().forEach(function(item){
computedVector.x = item.rect.translation.x;
computedVector.y = item.rect.translation.y + screen.getPosition().y;
if(computedVector.distanceTo(new Two.Vector(ship.getX(), ship.getY())) < latura + 20)
endGameEvent();
});

try wrapping it in document.ready
$(document).ready(function() {
$("#startGame").show();
});
You can't call show() on an object before it exists

The problem was with the parent of $("#startGame"), it was hidden as well. It worked with event because by the time I was hitting the $("#abandonGame") button It was displayed on the screen.

Related

$(window).focus() not executed properly in Chrome

I want to track clicks on AdSense elements on my page. To achieve that I put the focus on the window object and if it loses focus, I check if the mouse was in the area of the AdSense iFrame. Then i put the focus back on the window again.
This works. But in Chrome it works only once. So if I click on an adSense ad (opening in a new tab) and then I click on another one, the event doesn't fire anymore.
If I execute $(window).focus() in the console, the onBlur event fires again - but the $(window).focus() executed from within my code doesn't show any effect. I tried it with a Timeout too, without success.
Any ideas?
trackElements("#contentAdSense, #fallbackAdSense, #sidebarAdSense");
function trackElements (elementsToTrack)
{
var isOverElement = false;
$(window).focus();
$(elementsToTrack).mouseenter(function(e){
isOverElement = e.currentTarget.id;
});
$(elementsToTrack).mouseleave(function(e){
isOverElement = false;
});
$(window).blur(function(e){
windowLostBlur();
});
function windowLostBlur ()
{
if (isOverElement)
{
console.log(isOverElement);
$(window).focus();
}
};
};
Simplified version: https://jsfiddle.net/327skdns/2/
This is a documented Chrome bug: jQuery focus not working in Chrome
You need to wrap your focus() call with a setTimeout:
trackElements("#contentAdSense, #fallbackAdSense, #sidebarAdSense");
function trackElements (elementsToTrack)
{
var isOverElement = false;
$(window).focus();
$(elementsToTrack).mouseenter(function(e){
isOverElement = e.currentTarget.id;
});
$(elementsToTrack).mouseleave(function(e){
isOverElement = false;
});
$(window).blur(function(e){
windowLostBlur();
});
function windowLostBlur ()
{
if (isOverElement)
{
console.log(isOverElement);
setTimeout( function(){ $(window).focus(); }, 50 );
}
};
}

How to show the result of this jQuery function without the need of clicking the button?

I have this function below, however I want to make it work on windows load and show the result without clicking the button.
This is the code I use https://raw.githubusercontent.com/SuyashMShepHertz/indexedDB_sample/master/index.html
How to do this?
$("#getBtn").click(function(){
var type = 'permanent';
var request = db.transaction(["hashes"],"readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event){
$("#result").html("Name : "+request.result.name);
};
});
just put your code in
$( window ).load(function() {
//Code Here
});
If you need it both on click and initially when the page loads, make it a reusable function:
function doTheThing() {
var type = 'permanent';
var request = db.transaction(["hashes"], "readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event) {
$("#result").html("Name : " + request.result.name);
};
}
Then call it from both places you need it:
On page load
On click
To call it on page load, just make sure your script is at the end of the HTML (just before the closing </body> tag; this is best practice unless you have a good reason for doing something else) and call it:
doTheThing();
If you can't put the script at the end of the HTML, you can use jQuery's ready callback instead:
// Concise, but easy to misunderstand:
$(doTheThing);
// Or more verbose but also more clear:
$(document).ready(doTheThing);
(See note below about doing it directly or indirectly.)
To call it on click, hook it up, either directly or indirectly:
// Directly
$("#getBtn").click(doTheThing);
// Or indirectly
$("#getBtn").click(function() {
doTheThing();
});
The only reason for hooking it up indirectly would be to avoid having it receive the event object jQuery will pass it automatically, and to avoid having its return value examined by jQuery to see if it should stop propagation and prevent the default event action.
To avoid creating globals, I'd make sure the entire thing is in a scoping function:
(function() {
function doTheThing() {
var type = 'permanent';
var request = db.transaction(["hashes"], "readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event) {
$("#result").html("Name : " + request.result.name);
};
}
doTheThing();
$("#getBtn").click(doTheThing);
})();
just put it in $(document).ready, like this
$(document).ready(function(){
var type = 'permanent';
var request = db.transaction(["hashes"],"readwrite").objectStore("hashes").get(type);
request.onsuccess = function(event){
$("#result").html("Name : "+request.result.name);
};
});

Function not firing on first click

I have a button that takes 2 functions onclick. Here is my button:
<button id="btnNext" onclick="increment(); Next();">Next</button>
The increment() function works as intended on the first click but the Next() function does not. It does work as intended after first click. If I remove the increment() function, the Next() function works on first click. I have tried combining the functions but it gives me the same result.
The Next() function moves to the next form and the increment() function moves the scrollbar slider to the desired position.
Here are my functions:
var Next = function () {
UserVM.Model.MoveCurrentToNext();
}
var increment = function () {
if (lastScroll < 240) {
lastScroll += 40;
}
scrollpos.scrollTop = lastScroll;
}
Does anyone know what the reason is for this?
UPDATE: I added an alert to the Next() function. Now when I trigger the button it shows the next form when the alert box pops up but when I click ok, it returns to the previous form. This only happens when I click the button for the first time. Any reason for this? Anyway to solve it?
I don't know why are you using two separate functions for a single onclick unit because if you want to do both the operations why don't you call the form redirection code in the same function.
var increment = function ()
{
if (lastScroll < 240)
{
lastScroll += 40;
}
scrollpos.scrollTop = lastScroll;
//form navigation
UserVM.Model.MoveCurrentToNext();
}
HTML
<button id="btnNext" onclick="increment();">Next</button>
You can try this:
var Next = function () {
alert("This is Next Function");
}
var increment = function () {
alert("This is Increment Function");
Next();
}
<button id="btnNext" onclick="increment()">Next</button>
I have a feeling it is a timing issue. Add a slight delay to give the scroll position to change. (Just an educated guess);
var Next = function () {
window.setTimeout(UserVM.Model.MoveCurrentToNext, 100);
}
var increment = function () {
if (lastScroll < 240) {
lastScroll += 40;
}
scrollpos.scrollTop = lastScroll;
}
remove the onclick attr and put this in your code js:
$(document).ready(function(){
$(document).on("click","#btnNext",function(){
Next();
increment();
});
});
All provided answer work but I think this one is closer to what you need (without using other JS libraries neither making the functions to depend on others)
<button id="btnNext" onclick="(function(){increment();setTimeout(next, 100)})()">Next</button>
Note that this solution is wrapping the call of both increment() and newxt() function inside another anonymous function.
I feel dumb. I figured it out, should have figured it out way earlier. I have the variable lastScroll in another function, so I just change it to the variable position - var position = 0;. Now it works. Sorry for wasting everyone's time. I'll leave this question up just in case any of your answers help someone else out.

Modal popup window with Javascript

I have a clickable image that when you click a modal popup appears. I want to make sure you can only click it once and while the popup is showing, the clickable image is unclickable. I've tried several methods but no solution works as I want it to.
Here is the code:
init: function () {
var myButton = document.getElementById("kaffePic");
var clickable = true;
console.log(clickable);
myButton.onclick = function(e) {
e.preventDefault();
console.log(clickable);
if(clickable)
{
clickable = false;
popup(myButton, clickable);
}
else
{
return false;
}
};
}
And here is a part of the popup window (removed some code that has nothing to do with the issue).
function popup(theButton, returnClick) {
var myDiv = document.createElement("div");
myDiv.className = "popupWindow";
var newButton = document.createElement('a');
var image = document.createElement('img');
image.src = 'img/theclosebutton.png';
image.className = "popupImage";
newButton.appendChild(image);
myDiv.appendChild(newButton);
newButton.onclick = function () {
document.body.removeChild(myDiv);
returnClick = true;
};
}
Right now I can click it once, and then never again.
Any suggestions?
it's called only once because clickable is set to false after the first click. i suspect you are trying to set it to true in your popup-method by calling returnClick = true; but all that does is setting your argument-value, not the actual clickable-variable itself.
right now, clickable is a variable in the scope of init, so popup can't access it. you could, for example, make clickable a var in the scope of init's parent object. then in popup, you'd access clickable by parentObject.clickable.
//illustration of my example
parentObject {
var clickable,
function init()
}
function popup() {
...
parentObject.clickable = true;
}
Check .one() event handler attachment of jquery and this the .one() of jquery is used to Attach a handler to an event for the elements. The handler is executed at most once per element per event type. second one is link to an stack overflow questions about resetting the .one().Hope this helps

Problem using loop values in function

Beginners Javascript question here.
I am trying to create a function that finds all the links in a given div and sets up an onclick event for each one. I can get the link hrefs correctly, but when I try using them in the onclick function, Javascript seems to only use the last value found:
I.E
I have these links
#purpose
#future
#faq
When I use the onclick function, every link is reported as the #faq link.
Here's the code:
function prepareLinks () {
var nav = document.getElementById('navigation');
var links = nav.getElementsByTagName ('a');
for (var i = 0; i<links.length; i++) {
var linkRef = links[i].getAttribute('href').split("#")[1];
links[i].onclick = function () {
var popUp = "You clicked the " +linkRef +" link";
alert (popUp);
}
}
}
Here you have a closure creation. External variable linkRef becomes saved in inner onclick function. Try this way:
clickFunction() {
var popUp = "You clicked the " + this.href.split("#")[1] +" link";
// this should mean current clicked element
alert (popUp);
}
for (var i = 0; i<links.length; i++) {
links[i].onclick = clickFunction;
}
This is a scoping problem. The expression "You clicked the " +linkRef +" link" is evaluated when the onclick event fires, but what is the value of linkRef at this point?
You're trying to attach a separate onClick handler to each link, but you're accidentally attaching the same one.
You could generate a new function each time by using the new Function() constructor as
links[i].onclick = new Function("","alert('You clicked the '"+linkRef+"' link');");
See http://tadhg.com/wp/2006/12/12/using-new-function-in-javascript/ for more details.
But it's generally better to see if you can have a single handler. It's interesting that when you get to an event handler, the "this" keyword refers to the generator of the event. So you could have your original code refer to this.getAttribute("href"). Too many handlers will make your javascript event processing slow.

Categories