Do something after boolean gets triggered n times - javascript

Hi i'm trying to make a little game
Basically i'm trying to achieve the user strikes the match once it sparks, then strikes it again it lights the match
I've managed to get the "match to follow the cursor" and detect when the match "a div" intersects the match box "another div"
What i'm struggling with is that when the two divs intersect the boolean changes to true, but because its in the mouse move function it triggers true multiple time whilst moving across the strip
how do i trigger something when true counts to the value of 200 or above, i'm not sure how to trigger that?
i like the way this works as it mirrors how it would work in real life with pressure and velocity, but if there are any other suggestions there welcome.
heres the code i've been working with
<style>
.matchBox {
position: relative;
height: 86px;
width: 200px
}
.strip {
position: absolute;
background: red;
width: 100%;
height: 60%;
top: 50%;
transform: translateY(-50%);
}
.matchWrap {
height: 100px;
width: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.matchTip {
height: 30px;
width: 30px;
background: yellow;
position: absolute;
top: 0;
left: 0;
}
</style>
<div>
<h1>Light the match</h1>
<div class="matchBox">
<div class="strip" id="pad">
</div>
</div>
</div>
<div class="matchWrap">
<div class="matchTip" id="tip">
</div>
<div>
const match = document.querySelector('.matchWrap')
function isTouchDevice() {
try {
document.createEvent(TouchEvent);
return true;
} catch (e) {
return false;
}
}
const move = (e) => {
try {
var x = !isTouchDevice() ? e.pageX : e.touches[0].pageX;
var y = !isTouchDevice() ? e.pageY : e.touches[0].pageY;
} catch (e) {}
match.style.top = y + "px";
match.style.left = x + "px";
}
var strike
document.addEventListener('mousemove', (e) => {
move(e);
function elementsOverlap(el1, el2) {
const domRect1 = el1.getBoundingClientRect();
const domRect2 = el2.getBoundingClientRect();
return !(
domRect1.top > domRect2.bottom ||
domRect1.right < domRect2.left ||
domRect1.bottom < domRect2.top ||
domRect1.left > domRect2.right
);
}
const el1 = document.getElementById('tip');
const el2 = document.getElementById('pad');
console.log(elementsOverlap(el1, el2)); // 👉️ true
var strike = elementsOverlap(el1, el2);
var spark = 200
var lit = 500
if (strike.length > spark) {
console.log('reached')
} else if (strike.length > lit) {
console.log('reached2')
}
})
Thanks
Mike

Related

How to write a simple marquee effect with javascript

I need everyone's help. I currently need to implement a marquee effect. The yellow box needs to be scrolled up to show the name. Every time I scroll, I have to stay in the middle of the box for 1 second before continuing to scroll. I can find such an example on the Internet. , but the logic of this program is a bit difficult for me to understand for urban beginners. I wonder if anyone would like to provide a simpler and easier-to-understand writing method if I want to achieve this marquee effect?
​​Sorry, I am a beginner in the program, the current logic More complex programs are more difficult to understand.
function slideLine(box, stf, delay, speed, h) {
var slideBox = document.getElementById(box);
var delay = delay || 1000,
speed = speed || 20,
h = h || 40;
var tid = null,
pause = false;
var s = function() {
tid = setInterval(slide, speed);
};
var slide = function() {
if (pause) return;
slideBox.scrollTop += 1;
if (slideBox.scrollTop % h == 0) {
clearInterval(tid);
slideBox.appendChild(slideBox.getElementsByTagName(stf)[0]);
slideBox.scrollTop = 0;
setTimeout(s, delay);
}
};
setTimeout(s, delay);
}
slideLine("kanban_info", "p", 1000, 25, 40);
.kanban {
position: absolute;
margin: 0 auto;
width: 278px;
height: 50px;
background-color: yellow;
left: 50%;
transform: translate(-50%);
text-align: center;
line-height: 6;
}
.kanban .kenban_wrap {
height: 38px;
transform: translateY(28px);
overflow: hidden;
}
.kanban .kenban_wrap .kanban_info {
line-height: 38px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="kanban">
<div class="kenban_wrap" id='kanban_info'>
<p class="kanban_info">Allen</p>
<p class="kanban_info">james</p>
<p class="kanban_info">jack</p>
</div>
</div>
By combining scroll-behavior with anchor tags that are programmatically clicked you can simplify it. This should be easier to understand and you can go from there, even if it might not be the best solution.
let links = document.querySelectorAll("a"); // List of links
let div = document.querySelector("div");
let index = 0;
let t = 2000; // setTimeout duration
// Change Scroll behavior to prevent the animation from the last to first list item
function scrollBeh() {
if(index == 1) {
div.style.scrollBehavior = "auto";
t = 0; // Timeout duration to 0 to prevent `1` being shown longer than other list items
} else {
div.style.scrollBehavior = "smooth";
t = 2000;
}
}
// Loop through list items
function resetInd() {
if(index < 3) {
index++;
} else {
index = 0;
}
}
function clickLinks() {
links[index].click();
resetInd();
scrollBeh();
setTimeout(clickLinks, t);
}
setTimeout(clickLinks, t);
div {
width: 200px;
height: 100px;
background-color: darkblue;
overflow: hidden;
scroll-behavior: smooth;
}
li {
height: 100px;
list-style: none;
}
a {
text-decoration: none;
color: #FFF;
font-size: 50px;
}
<div>
<ul>
<li id="one">1</li>
<li id="two">2</li>
<li id="three">3</li>
<li id="one_loop">1</li>
</ul>
</div>

How to scale a container keeping its bottom right corner fixed?

I have a red container which initially is at bottom right of black container. I have a scale function that gradually scales the container. I want to make the bottom right position of red container to be fixed and scale it towards top left. How can I do that?
const box = document.getElementById("box")
const initHeight = 200
const initWidth = 200
const centerX = initWidth / 2
const centerY = initHeight / 2
function transform(scale, translate) {
if (translate) {
translate[0] = -centerX + translate[0]
translate[1] = -centerY + translate[1]
}
box.style.transform = `scale(${scale})${
translate ? ` translate(${translate.map((x) => x + "px").toString()})` : ""
}`
}
let initX = initWidth
let initY = initHeight
let scaleVal = 0.5
transform(scaleVal, [initX, initY])
function scale() {
scaleVal = scaleVal + 0.01
transform(scaleVal, [
initX - scaleVal * initWidth,
initY - scaleVal * initHeight
])
if (scaleVal <= 1) {
setTimeout(() => {
requestAnimationFrame(scale)
}, 50)
}
}
scale()
* {
box-sizing: border-box;
}
.box {
height: 200px;
width: 200px;
background-color: black;
position: absolute;
}
.box:nth-child(2) {
background-color: red;
}
<div id="app">
<div class="box"></div>
<div class="box" id="box"></div>
</div>
To lock the bottom right corner of the red box to the bottom right of the black box this snippet does two things: positions red box right bottom relative to the parent app container and sets the transform-origin to that spot too (normally transform origin is at the center of an element). It then uses a CSS animation to expand the red box and contract it again using scale.
This method does not need JS as it is a simple scaling transform, but of course some of the subtleties of the original transformations are lost because of tying the corner down.
* {
box-sizing: border-box;
}
body {
position: relative;
width: 100vw;
height: 100vh;
}
#app {
position: absolute;
height: 200px;
width: 200px;
}
.box:nth-child(1) {
height: 200px;
width: 200px;
background-color: black;
position: absolute;
top: 0;
left: 0;
}
#box {
background-color: red;
width: 100px;
height: 100px;
position: absolute;
bottom: 0;
right: 0;
transform-origin: right bottom;
animation: scale 5s 1 ease-in-out;
}
#keyframes scale {
0% {
transform: scale(1);
}
50% {
transform: scale(2);
}
100% {
transform: scale(1);
}
}
<div id="app">
<div class="box"></div>
<div class="box" id="box"></div>
</div>
Okay so I finally figured it out,
const box = document.getElementById("box")
let scale = 0
const initWidth = 50
const initHeight = 50
function fixed(num, fix = 1) {
return Number(parseFloat(num).toFixed(fix))
}
function scaleBox() {
const [x, y] = [
fixed((initWidth - scale * initWidth) / 2),
fixed((initHeight - scale * initHeight) / 2)
]
box.style.transform = `translate(${x}px, ${y}px) scale(${scale})`
scale = scale + 0.1
if (scale < 1) {
setTimeout(() => {
requestAnimationFrame(scaleBox)
}, 500)
}
}
scaleBox()
* {
box-sizing: border-box;
}
.box {
height: 50px;
width: 50px;
background-color: black;
position: absolute;
}
.box:nth-child(2) {
background-color: red;
transform: translate(0, 0) scale(0);
}
<div id="app">
<div class="box"></div>
<div class="box" id="box"></div>
</div>
Explanation
The trick is to translate the container in such a way that when its scaled after the translation, it always places itself in the bottom right of purple container.
To figure out the translation amount, let's first scale the container to 0.5 without any translation. It looks like this,
As you can see the container's width is 25 as 0.5(scale) * 50(init_width)=25 and position from container from all sides(top left, bottom left, top right, bottom right) will be (25/2, 25/2)=(12.5,12.5) since the container is scaled equally from all sides.
Since the position from bottom right is (12.5,12.5), we need to translate the container to (+12.5,+12.5) and then scale it to exactly place it at bottom right.
You can achieve many things using display:flex, it's great!
This is how I would approach your problem:
const handleClick = () => {
const blackDiv = document.getElementById("black-div");
const redDiv = document.getElementById("red-div");
let widthRatio = 0;
let heightRatio = 0;
const scaleUpTimer = setInterval(() => {
if (widthRatio === 1 || heightRatio === 1) clearInterval(scaleUpTimer);
widthRatio = redDiv.offsetWidth / blackDiv.offsetWidth;
heightRatio = redDiv.offsetHeight / blackDiv.offsetHeight;
redDiv.style.width = widthRatio * 100 + 2 + "%";
redDiv.style.height = heightRatio * 100 + 2 + "%";
}, 10);
};
#black-div {
width: 200px;
height: 200px;
background-color: rgb(0, 0, 0);
display: flex;
align-items: flex-end;
justify-content: flex-end;
}
#red-div {
background-color: red;
width: 50%;
height: 50%;
}
<div id='black-div'>
<div id='red-div' onclick={handleClick()}></div>
</div>
EDIT: I used onclick here but obviously you would have to handle the situations where someone clicks the red square and its already scaled up to avoid setting unnecessary timers. Or you could just call the function directly, without having to click anything.

How do I make an image move when i scroll down?

Here is an example of what i want to achieve:
https://www.flambette.com/en/
I have tried to change the css properties of images but that effect does not satisfy my needs.
I have tried the following code:
mydocument.on('scroll',function() {
if (mydocument.scrollTop() > 10 && mydocument.scrollTop() < 200 ) {
$('#first').css('top', '320px');
$('#first').css('left', '215px');
$('#first').css('transition', '0.5s');
}
else {
$('#first').css('top', '300px');
$('#first').css('left', '200px');
$('#first').css('transition', '0.5s');
}
});
This is supposed to move an image when you scroll between 10 and 200 px.
var container = document.getElementById('container');
var windowHeight = window.innerHeight;
var windowWidth = window.innerWidth;
var scrollArea = 1000 - windowHeight;
var square1 = document.getElementsByClassName('square')[0];
var square2 = document.getElementsByClassName('square')[1];
// update position of square 1 and square 2 when scroll event fires.
window.addEventListener('scroll', function() {
var scrollTop = window.pageYOffset || window.scrollTop;
var scrollPercent = scrollTop/scrollArea || 0;
square1.style.left = scrollPercent*window.innerWidth + 'px';
square2.style.left = 800 - scrollPercent*window.innerWidth*0.6 + 'px';
});
body {
overflow-x: hidden;
}
.container {
width: 100%;
height: 1000px;
}
.square {
position: absolute;
}
.square-1 {
width: 100px;
height: 100px;
background: red;
top: 600px;
}
.square-2 {
width: 120px;
height: 120px;
background: black;
left: 800px;
top: 800px;
}
<div class="container" id="container">
<div class="square square-1"></div>
<div class="square square-2"></div>
</div>
Hope to help you.
Here you can see more examples about movable elements and scroll events.

Why is clientX reset to 0 on last drag-event and how to solve it?

I'm trying to drag elements along a line. They should push each other, not cross over or under.
To avoid having a shady element float around on drag, I drag a sub-div which then affects the position of the outer one. Works fine except when you release the mouse which triggers the last drag-event with clientX equal to 0 (see CodePen)!
var b = document.querySelector('.box');
var bi = document.querySelector('.box-inner');
var b2 = document.querySelector('.box2');
bi.addEventListener('dragstart', function() {
console.log("dragstart")
}, false);
bi.addEventListener('drag', function(event) {
const bLeft = event.clientX;
const b2Left = b2.offsetLeft;
b.style.left = bLeft + "px";
if (b2Left - 50 <= bLeft) {
b2.style.left = (bLeft + 50) + "px";
}
console.log("drag", event.clientX, event.target.offsetParent.offsetLeft, b2.offsetLeft);
}, false);
bi.addEventListener('dragend', function() {
console.log("dragend")
}, false);
.box {
width: 50px;
height: 50px;
background-color: hotpink;
position: absolute;
top: 0;
left: 0;
}
.box-inner {
width: 100%;
height: 100%;
}
.box2 {
width: 50px;
height: 50px;
background-color: rebeccapurple;
position: absolute;
left: 200px;
top: 0;
}
<div class="box">
<div class="box-inner" draggable="true"></div>
</div>
<div class="box2"></div>
Why is this and what can I do to avoid resetting it?
By default, data/elements cannot be dropped in other elements. To allow a drop, you must prevent the default handling of the element when dragover.
document.addEventListener("dragover", function(event) {
// prevent default to allow drop
event.preventDefault();
}, false);
I just ignore the last event. I don't know why it emits.
// in `drag` event handler
if (event.screenX === 0) {
return;
}
Notice you should use screenX here. When the user zoom in the page, clientX would be a positive value but not zero.

Adding DIVs step-by-step...1, 2, 3, 4, 8, 16

I'm trying to create div boxes step by step and animate them for several times when a button is pressed. I have a running code, and everything is going well. It goes right to the endhost, then it goes left again to its original place. This is mainly what I do, and also the demo is found here: http://jsfiddle.net/LSegC/1/
Now what I want to do is to increase the number of whole animated DIVs one-by-one (as it is now) up to 3 Divs, but then have exponential increase on the total number of DIVs. So the total number of animated DIVs will be like 1, 2, 3, and then 4, 8, 16, etc.
Remember, my problem is not with the number being shown inside the DIV, it's actually that how many DIVS are being created! So I want for instance 8 DIVs, numbered from 1 to 8 animated. Hope it is now clear.
$(document).ready(function(){
$("button").click(function() {
var d = $(".t").fadeIn();
var speed = +$("#number1").val();
d.animate({left:'+=230px'}, speed);
d.animate({left:'+=230px'}, speed);
d.animate({top:'+=20px', backgroundColor: "#f09090", text:'12'}, speed/4, "swing", function() {
$('.span', this).fadeOut(100, function() {
$(this).text(function() {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
d.delay(1000).animate({left:'-=230px'}, speed);
d.animate({left:'-=230px'}, speed);
d.fadeOut().promise().done(function() {
d.last().after(function() {
var top = +$(this).css('top').replace('px', ''),
number = +$(this).data('number') + 1,
$clone = $(this).clone();
$clone.data('number', number).css('top', top + 20);
$clone.find('.span').text(number);
return $clone;
});
d.find('.span').text(function() {
return $(this).text().replace('a', '');
});
})
});
EDIT
Your code was too hard to manipulate as it was, I recreated the whole thing:
HTML:
<img id="streamline1" src="https://cdn3.iconfinder.com/data/icons/streamline-icon-set-free-pack/48/Streamline-04-48.png" />
<img id="LAN" src="https://cdn1.iconfinder.com/data/icons/ecqlipse2/NETWORK%20-%20LAN.png" />
<img src="https://cdn3.iconfinder.com/data/icons/streamline-icon-set-free-pack/48/Streamline-04-48.png" id="streamline" />
<div id="mid"></div>
<div id="bottom"></div>
<div>Speed (mS):
<input value="500" id="speed" type="number" style="position: relative"></input>
<button>Apply!</button>
<!-- dynamic area -->
<div class="packets"></div>
</div>
JS:
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
$("button").click(function () {
if (count < 4) {
items = items + 1;
count++;
} else {
items = items * 2;
}
speed = $("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + packetNumber + "</font>").appendTo(div);
packetNumber++;
div.css("left",left+"px");
div.hide();
left += 20;
}
}
function animateDivs() {
$(".t").each(function () {
var packet = $(this);
packet.show();
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
left: '+=230px'
}, speed);
packet.animate({
top: '+=20px',
backgroundColor: "#f09090",
text: '12'
}, speed / 4, "swing", function () {
$('.span').fadeOut(100, function () {
$(this).text(function () {
return 'a' + $(this).text().replace('a', '');
}).fadeIn(100);
});
});
packet.delay(1000).animate({left:'-=230px'}, speed);
packet.animate({left:'-=230px'}, speed);
}).promise().done(function(){
$(".packets").empty();});
}
});
CSS:
#bottom {
border: 1px dashed gray;
position: absolute;
left: 55px;
height: 20px;
width: 500px;
opacity: 0.5;
top: 30px;
z-index=-1;
}
#mid {
border: 1px dashed gray;
position: absolute;
left: 55px;
height: 20px;
width: 500px;
opacity: 0.5;
top: 10px;
z-index=-1;
}
.t {
display: inline-block;
position: absolute;
top: 10px;
left: 60px;
text-align: center;
vertical-align: middle;
width: 20px;
height: 20px;
background-color: lightgreen
}
#streamline {
width: 50px;
height: 50px;
right: 0px;
position: fixed;
left: 548px;
}
#streamline1 {
left: 0px;
width: 50px;
height: 50px;
}
#LAN {
width: 50px;
height: 50px;
left: 275px;
position: fixed;
}
.packets {
display: inline;
}
FIDDLE: http://jsfiddle.net/54hqm/3/
It was tough for me to follow the code also, but I cut it back quite a bit, came up with a "one-way" "empiric" approach. FIDDLE
The speed can be adjusted by the change in the increment (inc), but there are a variety of methods that can be used.
Can you be more specific about what you mean by "exponential"? Do you mean an exponential speed increase across the div, or rather a speed increase until you get to 50%, then a decrement in speed.
JS
$("button").click(function() {
var speed = 1000;
var d = $('.mover');
d.show();
var inc = 1;
for (var i=0; i<290; i=i+inc)
{
d.animate({ left: i,
easing: 'linear'}, 1);
if (inc < 11)
{
inc = inc + 1;
} else {
inc = inc - 1;
}
}
});

Categories