If Statement based on Visibility JS Fade In - javascript

How do I change this so nothing happens if the element being faded in is already visibility = 'visible' It's basically changing visibility based on mouse position, but right now it fades in every time the mouse moves. Demo: https://dl.dropboxusercontent.com/u/246684898/VipSitaraman.com/index2.htm. If you're bored, feel free to steal my code cuz coding it was a pain and I'd love to help someone else...just credit me.
$(".txt").mousemove(function(e){
var offset = $(this).offset();
var a = e.clientX - offset.left;
var b = e.clientY - offset.top;
var c = 0
if (a > 0 && a <= 750) {
$('#s1').css('visibility','visible').hide().fadeIn();
$('#s2,#s3,#s4,#s5,#s6').css('visibility','hidden');
$('#home').text(c + ", "+ b);
} else if (a > 750 && a <= 1500) {
$('#s2').css('visibility','visible').hide().fadeIn();
$('#s1,#s3,#s4,#s5,#s6').css('visibility','hidden');
} else if (a > 1500 && a <= 2250) {
$('#s3').css('visibility','visible').hide().fadeIn();
$('#s1,#s2,#s4,#s5,#s6').css('visibility','hidden');
} else if (a > 2250 && a <= 3000) {
$('#s4').css('visibility','visible').hide().fadeIn();
$('#s1,#s2,#s3,#s5,#s6').css('visibility','hidden');
} else if (a > 3000 && a <= 3750) {
$('#s5').css('visibility','visible').hide().fadeIn();
$('#s1,#s2,#s3,#s4,#s6').css('visibility','hidden');
} else if (a > 3750 && a <= 4500) {
$('#s6').css('visibility','visible').hide().fadeIn();
$('#s1,#s2,#s3,#s5,#s4').css('visibility','hidden');
} else {
$('#s1,#s2,#s3,#s5,#s4,#s6').css('visibility','hidden');
}
});
});
</script>

Try
var $ss = $('.s');
$(".txt").mousemove(function (e) {
var offset = $(this).offset();
var a = e.clientX - offset.left;
var b = e.clientY - offset.top;
var c = 0;
var d = Math.ceil(a / 750);
if (d > 0 && d <= $ss.length) {
var $t = $ss.eq(d - 1);
if (!$t.data('visible')) {
$t.css('visibility', 'visible').hide().fadeIn().data('visible', true);
$ss.not($t).css('visibility', 'hidden').data('visible', false);
$('#home').text(c + ", " + b);
}
} else {
$ss.css('visibility', 'hidden');
}
});
Demo: Fiddle

Related

How to detect collision?

I am building a video game where a spaceship moves with controllers and it must avoid some fireballs in order to win. However now I would like to setup a collision system: when a fireball touches the spaceship, game is over (alert("game over")). Any help with this? Thanks!!!
let spaceship = document.querySelector("#icon")
//Fireball script
const fireballArray = []
function generateFireBallWithAttributes(el, attrs) {
for (var key in attrs) {
el.setAttribute(key, attrs[key])
};
return el
}
function createFireBalls(amount) {
for (let i = 0; i <= amount; i++) {
fireballArray.push(generateFireBallWithAttributes(document.createElement("img"), {
src: "Photo/fireball.png",
width: "40"
}))
}
}
createFireBalls(10)
fireballArray.forEach((fireballElement) => {
const fallStartInterval = setInterval(function() {})
document.querySelector("body").appendChild(fireballElement);
const fireballMovement = {
x: fireballRandom(fireballElement.offsetWidth),
y: 0
}
const fireLoop = function() {
fireballMovement.y += 2;
fireballElement.style.top = fireballMovement.y + "px";
if (fireballMovement.y > window.innerHeight) {
fireballMovement.x = fireballRandom(fireballElement.offsetWidth);
fireballElement.style.left = fireballMovement.x + "px";
fireballMovement.y = 0
}
}
fireballElement.style.left = fireballMovement.x + "px";
let fireInterval = setInterval(fireLoop, 1000 / ((Math.random() * (50)) + 75))
})
function fireballRandom(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))
}
//Spaceship moves into space + prevent going out borders
let hits = 0
let pos = {
top: 1000,
left: 570
}
const keys = {}
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true
})
window.addEventListener("keyup", function(e) {
keys[e.keyCode] = false
})
const loop = function() {
if (keys[37] || keys[81]) {pos.left -= 5}
if (keys[39] || keys[68]) {pos.left += 5}
if (keys[38] || keys[90]) {pos.top -= 4}
if (keys[40] || keys[83]) {pos.top += 4}
if (pos.left < 0) { pos.left = -1}
if (pos.top < 0) {pos.top = -1}
if (pos.left + spaceship.offsetWidth >= body.offsetWidth) {
pos.left = body.offsetWidth - spaceship.offsetWidth
}
if (pos.top + spaceship.offsetHeight >= body.offsetHeight) {
pos.top = body.offsetHeight - spaceship.offsetHeight
}
spaceship.setAttribute("data", body.offsetWidth + ":" + body.offsetHeight)
spaceship.style.left = pos.left + "px";
spaceship.style.top = pos.top + "px"
}
let sensibilty = setInterval(loop, 8)
<body>
<img src="Photo/Spaceship1.png" id="icon">
</body>
Check this out (hitboxes)
Also this
Your code is missing complete information. That said, as your game progresses with explicit and independent setIntervals on fireballs and spaceship, and you dont want to make bigger changes I suggest you call the checkCollision() function any time fireball moves or spaceship moves (that is in the loop and fireloop "animation functions").
The collision itself is done with the following:
function detectOverlap(fireball) {
const shipRect = spaceship.getBoundingClientRect();
const fireballRect = fireball.getBoundingClientRect();
//these two variables are of following type
//DOMRect {x: 570, y: 836, width: 104.484375, height: 112.828125, ...}
// this will test if the ship collides with specific fireball
if (
(shipRect.x + shipRect.width > fireballRect.x && shipRect.x < fireballRect.x + fireball.width)
&& (shipRect.y + shipRect.height > fireballRect.y && shipRect.y < fireballRect.y + fireball.height)
) {
return true;
} else {
return false;
}
};
function checkCollision() {
let collision = false;
fireballArray.forEach(fireball => {
if (detectOverlap(fireball)) { collision = true };
});
// this is satisfied if the ship collides with any fireball
if (collision === true) {
// do some logic on collision
console.log('collision');
}
};
This will do rectangle vs rectangle collision detection. This might not fit the best, but it is a good first approximation.
NOTE: You can check the devtools console (F12) to assess the correct collision detection.

jump mechanic in javascript

im currently making a game, and this is the jump mechanic.
the idea behind it is that it goes up for 500ms, waits for 200ms, and goes back to the ground (the ground is at top 471).
everything works now but it doesn't stop when its at top 471 i tried doing this:
if (characterTop > 471) {
stopMoveDown()
}
that didn't work so then i tried doing this: (in the movingDown function)
if (characterTop > -1 || character < 471) {
character.style.top = top + "px";
}
both of these didn't work.
and there is another problem, how can i make sure the player can't jump again while jumping?
this is the code i have now:
document.body.onkeydown = function(e){
if(e.keyCode == 32){
jump = setInterval(function(){
let top =
parseInt (window.getComputedStyle(character).getPropertyValue("top"));
top -= 1;
var characterTop = parseInt(
window.getComputedStyle(character).getPropertyValue("top")
)
if (characterTop > -1 || character < 471) {
character.style.top = top + "px";
}
}, 1);
setTimeout(function() {
stopMoveUp()
}, 500);
setTimeout(function() {
movingDown()
}, 700);
//if (characterTop > 471) {
// stopMoveDown()
//}
}
}
function movingDown() {
falling = setInterval(function(){
let top =
parseInt (window.getComputedStyle(character).getPropertyValue("top"));
top += 1;
var characterTop = parseInt(
window.getComputedStyle(character).getPropertyValue("top")
)
if (characterTop > -1 || character < 471) {
character.style.top = top + "px";
}
}, 1);
}
function stopMoveUp() {
clearInterval(jump);
}
function stopMoveDown() {
clearInterval(movingDown);
}
var movingRight = false;
var movingLeft = false;
can anybody please help me with these 2 problems?

Detecting End Of Scrolling In jQuery

I want to detect if user scrolled to the end of the window then make a trigger click to a "show more" button like Facebook newsfeed.
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()){
$('.feed-show-more-button').trigger('click');
}
});
this is my code but it's not working only if i scrolled to the end of the window then go back to the top
Anyone can help ?
Try this
var CheckIfScrollBottom = debouncer(function() {
if (getDocHeight() == getScrollXY()[1] + window.innerHeight) {
$('.feed-show-more-button').trigger('click');
}
}, 500);
document.addEventListener('scroll', CheckIfScrollBottom);
function debouncer(a, b, c) {
var d;
return function() {
var e = this,
f = arguments,
g = function() {
d = null, c || a.apply(e, f)
},
h = c && !d;
clearTimeout(d), d = setTimeout(g, b), h && a.apply(e, f)
}
}
function getScrollXY() {
var a = 0,
b = 0;
return "number" == typeof window.pageYOffset ? (b = window.pageYOffset, a = window.pageXOffset) : document.body && (document.body.scrollLeft || document.body.scrollTop) ? (b = document.body.scrollTop, a = document.body.scrollLeft) : document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop) && (b = document.documentElement.scrollTop, a = document.documentElement.scrollLeft), [a, b]
}
function getDocHeight() {
var a = document;
return Math.max(a.body.scrollHeight, a.documentElement.scrollHeight, a.body.offsetHeight, a.documentElement.offsetHeight, a.body.clientHeight, a.documentElement.clientHeight)
}
Added jsfiddle
http://jsfiddle.net/3unv01or/
var processing;
$(document).ready(function(){
$(document).scroll(function(e){
if (processing)
return false;
if ($(window).scrollTop() >= ($(document).height() - $(window).height())){
console.log('in it');
processing = true;
$('#container').append('More Content Added');
console.log($('#container'));
processing = false;
});
}
});
});
.loadedcontent {min-height: 800px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">Hello world<div class="loadedcontent"></div></div>

an if statement returns true, but the condition won't trigger

I have an if statement in my code as you can see below. When I check in console log when those two elements collide with each other, the if statement becomes true, but it won't stop my interval function. I wonder what would have caused it to not work as it should?
var animationTimer = setInterval(bladAnimation, 30);
document.onkeydown = function(event) {
if (event.keyCode == 37) {
// <--
fx = -15;
fy = 0;
froskAnimation()
}
if (event.keyCode == 38) {
// opp
fy = -15;
fx = 0;
froskAnimation()
}
if (event.keyCode == 39) {
// -->
fx = 15;
fy = 0;
froskAnimation()
}
if (event.keyCode == 40) {
// ned
fy = 15;
fx = 0;
froskAnimation()
}
}
function froskAnimation() {
Xfrosk = fx + Xfrosk;
Yfrosk = fy + Yfrosk;
if ((Yfrosk + 70 > maxY) || (Yfrosk < minY)) {
Yfrosk = Yfrosk - fy;
}
if ((Xfrosk + 70 > maxX) || (Xfrosk < minX)) {
Xfrosk = Xfrosk - fx;
}
frosk.style.left = Xfrosk + "px";
frosk.style.top = Yfrosk + "px";
console.log(Xfrosk)
}
function bladAnimation() {
Yblad = by + Yblad;
if ((Yblad + 70 > maxY) || (Yblad < minY)) {
by = by * -1;
}
blad.style.top = Yblad + "px";
}
if (blad.x < frosk.x + frosk.width && blad.x + blad.width > frosk.x
&& blad.y < frosk.y + frosk.height && blad.y + blad.height > frosk.y) {
clearInterval(animationTimer);
}
full code here: https://codepen.io/ctrlvi/pen/jXbJYG
That condition is executed only once, when your javascript is loaded. At that point the condition is probably false. You should move it at the end of bladAnimation (I suppose what you're trying to do is stop the self-moving block when it hits the other one).
function bladAnimation() {
Yblad = by + Yblad;
if ((Yblad + 70 > maxY) || (Yblad < minY)) {
by = by * -1;
}
blad.style.top = Yblad + "px";
if (blad.x < frosk.x + frosk.width && blad.x + blad.width > frosk.x
&& blad.y < frosk.y + frosk.height && blad.y + blad.height > frosk.y) {
clearInterval(animationTimer);
}
}

window.onload is not firing in IE

Here is my code:
var scrollOnLoad = function scrollOnLoad(selector, offset) {
window.onload = function() {
if ($(window).height() <= 800) {
var attempts = 100;
var interval = setInterval(function() {
var h = $(selector).height();
console.log("attempt #" + attempts + ", h=" + h);
if (h > 0 || !attempts--) {
$("body,html").animate({scrollTop : h + offset}, '1000');
clearInterval(interval);
}
}, 50)
}
}
}
and here is how its caling:
scrollOnLoad(".content-wrapper", 50);
I've noticed that window.onload event is not firing in IE (console is not logging anything) - any ideas why? Thanks in advance!
You can use document.readyState property:
function scrollOnLoad(selector, offset) {
if(document.readyState === 'complete')
x();
else
document.addEventListener('readystatechange', function(){
if(document.readyState === 'complete')
x();
});
function x(){
if ($(window).height() <= 800) {
var attempts = 100;
var interval = setInterval(function() {
var h = $(selector).height();
console.log("attempt #" + attempts + ", h=" + h);
if (h > 0 || !attempts--) {
$("body,html").animate({scrollTop : h + offset}, '1000');
clearInterval(interval);
}
}, 50)
}
}
}
As mentioned in comments your function scrollOnLoad is getting executed after the window has loaded.
Now in better scenarios these events should be added in global scope.
So it should be like
window.onload = function() {
if(someConditionIsSatisfied){
if ($(window).height() <= 800) {
var attempts = 100;
var interval = setInterval(function() {
var h = $(selector).height();
console.log("attempt #" + attempts + ", h=" + h);
if (h > 0 || !attempts--) {
$("body,html").animate({scrollTop : h + offset}, '1000');
clearInterval(interval);
}
}, 50)
}
}
}

Categories

Resources