How can I update "event.clientX" every sec? - javascript

I need to console log x coordinate every 1 sec when pointer is on picture but I have no idea how to update "event" from the js code.
function onPic(event) {
let xOnPic = event.clientX;
console.log(xOnPic);
setTimeout(onPic, 1000);
}
.testDiv {
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<div onmouseover="onPic(event)" src="./Pic/pic1.jpeg" class="testDiv">
</div>

You need to throw the event more often. Use onmousemove for that. If you want to restrict the amount of outputs you can do that with a variable.
var wait = false
function onPic(event) {
if (!wait) {
wait = true;
let xOnPic = event.clientX;
console.log(xOnPic);
setTimeout(() => wait = false, 1000);
}
}
.testDiv {
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<!DOCTYPE html>
<html>
<head>
<title>I have no title</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="test.css">
</head>
<body>
<div onmousemove="onPic(event)" src="./Pic/pic1.jpeg" class="testDiv">
</div>
<script src="test.js"></script>
</body>
</html>
I should note that this will only trigger if the mouse actually moved in between, but that is what you usually want.
If you always want to update simply set an variable and output that every second.
let interval = null;
let xPos = 0;
function onEnter() {
interval = setInterval(() => {
console.log(xPos);
}, 1000);
}
function onMove(event) {
xPos = event.clientX;
}
function onLeave() {
clearInterval(interval);
}
.testDiv {
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<!DOCTYPE html>
<html>
<head>
<title>I have no title</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="test.css">
</head>
<body>
<div onmouseenter="onEnter(event)" onmousemove="onMove(event)" onmouseleave="onLeave(event)" src="./Pic/pic1.jpeg" class="testDiv">
</div>
<script src="test.js"></script>
</body>
</html>

here is a working fiddle. Just use mouseenter mouseleave and mousemove and set Intervall.
JS fiddle
HTML
<svg id="svg" class="pic">
</svg>
JS
let mouseInPic = false;
let x;
$("#svg").on("mouseenter", () => {
mouseInPic = true
})
$("#svg").on("mouseleave", () => {
mouseInPic = false
})
$("#svg").on("mousemove", (e) => {
x = e.clientX
})
window.setInterval(function(){
if(mouseInPic == true){
console.log(x)
}
}, 1000);

Here you have a native JS implementation, with 1 second throttling of the updates, so it will console the position every second but not more often than every second. Since it is not possible to get the mouse position without a mouse event when mouse is over the element but not moving, you will need to remember the position of the mouse and store it into global variable, if mouse is moved on mousemove, just update the new position xOnPic.
Use mouseover and mousemove to detect if mouse is over the selected element and mouseout to detect when mouse is out of the element, so that you can stop printing to console.
var xOnPic = 0
var mouseOverPic = false;
var tryingToUpdate = false;
function tryToUpdate(){
if (!tryingToUpdate){
tryingToUpdate = true
console.log(xOnPic);
setTimeout(onPic, 1000);
}
}
function onPic(){
if (mouseOverPic){
console.log(xOnPic);
setTimeout(onPic, 1000);
}else{
tryingToUpdate = false;
}
}
document.getElementById('Pic').addEventListener('mousemove', function(e){
xOnPic = e.clientX;
mouseOverPic = true;
tryToUpdate();
});
document.getElementById('Pic').addEventListener('mouseover', function(e){
xOnPic = e.clientX;
mouseOverPic = true;
tryToUpdate();
});
document.getElementById('Pic').addEventListener('mouseout', function(e){
xOnPic = '';
mouseOverPic = false;
});
.testDiv{
width: 700px;
height: 350px;
background-image: url("./Pic/pic1.jpeg");
background-repeat: no-repeat;
background-size: 700px 350px;
}
<!DOCTYPE html>
<html>
<head>
<title>I have no title</title>
<meta charset = "UTF-8">
<link rel = "stylesheet" href = "test.css">
</head>
<body>
<div id='Pic' src="./Pic/pic1.jpeg" class = "testDiv">
</div>
<script src = "test.js"></script>
</body>
</html>

Use
setInterval(onPic,1000);

Related

How to cancel a drag (on dragenter)

I'm on classic javascript and i want to cancel a drag on enter in a specific div.
in HTML :
<!-- Element i want to drag -->
<div id="draggableElement" draggable="true"></div>
<!-- Element which cancels the drag on enter -->
<div id="specificDiv"></div>
in JS :
document.addEventListener("dragenter", event=> {
if (event.target.id == "specificDiv") {
// Cancel the drag
}
}, false);
I already search on the web but i didn't find a solution, however i found some js libraries but it's too much for the only thing i want to do.
Thanks by advance.
EDIT :
More precisly i want, at least, undisplay the draged image by entering in my specific div to see this one.
So i've already tried to hide the draged image but it doesn't work on dragenter (only in dragstart).
in JS :
let dragged;
document.addEventListener("dragstart", event=> {
dragged = event;
}, false);
document.addEventListener("dragenter", event=> {
if (event.target.id == "specificDiv") {
// Hide the dragged image or cancel the drag
event.dataTransfer.setDragImage(new Image(), 0, 0); // Doesn't work
dragged.dataTransfer.setDragImage(new Image(), 0, 0); // Doesn't work too
}
}, false);
Okay so you want to hide the dragged element when enters over renderCanvas but WITHOUT releasing mouse button am I right?
If so, you have to know that is not possible to modifying drag-ghost-image without releasing mouse button. In that case you can simulate a custom Drag&Drop and hide the dragged element when its position is in range with the other element:
let specificDiv = document.getElementById('specificDiv');
let renderCanvas = document.getElementById('renderCanvas');
//Catches target position
rect = renderCanvas.getBoundingClientRect();
rectX = rect.left;
rectY = rect.top;
//Release dragged element
let released;
document.addEventListener('mouseup', ()=>{
released = true;
})
//Drag element
specificDiv.addEventListener('mousedown', (ev) => {
released = false;
specificDiv.addEventListener('mousemove', (e)=>{
if(!released) {
//Collects actual mouse position while dragging
x = e.clientX
y = e.clientY
//Moves dragged element
specificDiv.style.left = (x-80) + 'px';
specificDiv.style.top = (y-80) + 'px';
//Hides dragged element when is over the other
if(y > rectY) {
specificDiv.style.opacity="0"
}
}
})
})
#specificDiv {
position: relative;
background-color: red;
height: 10em;
width: 10em;
}
#renderCanvas {
background-color: blue;
height: 20em;
width: 20em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<!-- Div element you want to drag-->
<div id="specificDiv">DRAGGED ELEMENT</div>
<!-- Div element who cancels the drag on enter -->
<div id="renderCanvas">TARGET ELEMENT</div>
<script src="js/main.js"></script>
</body>
</html>
You'll have to adapt rectX and rectY to your specific divs position.
The following would be a solution to allow dropping on a div and on another div don't allow dropping:
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
const target = document.querySelector("#dragtarget");
const notarget = document.querySelector("#nodragtarget");
const dragged = document.querySelector("#dragitem");
target.addEventListener("dragover", allowDrop);
target.addEventListener("drop", drop);
dragged.addEventListener("dragstart", drag)
div[draggable] {
height: 3rem;
width: 3rem;
background: yellow;
}
div#dragtarget {
height: 5rem;
width: 5rem;
border: 1px solid green;
}
div#nodragtarget {
height: 5rem;
width: 5rem;
border: 1px solid red;
}
<div id="dragitem" draggable="true"></div>
<div id="dragtarget"></div>
<div id="nodragtarget"></div>
did my answer worked for you? I am quite curious

How can I get a div to change its background-image after a specific event has taken place?

I have made a game using JavaScript and I would like the background to change after the game is over or after isGamerOver = true to be more specific. Here is what I currently have. Right now when ever the game ends I get a Uncaught TypeError: Cannot read property 'style' of null.
function gameOver() {
console.log('game over')
isGamerOver = true
while (grid.firstChild) {
grid.removeChild(grid.firstChild)
}
grid.innerHTML = score
clearInterval(upTimerId)
clearInterval(downTimerId)
clearInterval(leftTimerId)
clearInterval(rightTimerId)
if(isGamerOver = true){
document.getElementById("grid").style.backgroundImage="url('backgrounds/background-up.png')";
}else{
document.getElementById("grid").style.backgroundImage="url('backgrounds/game-over.png')";
}
}
Here is the style sheet I am trying to change
.grid {
width: 400px;
height: 600px;
background-image: url(backgrounds/background-up.png);
position: relative;
font-size: 100px;
text-align: center;
color: #fff;
}
Here Is my HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<title>100% Not Doodle Jump</title>
<link rel="stylesheet" href="style.css"></link>
<script src="app.js" charset="utf-8"></script>
</head>
<body>
<div class="grid"></div>
</body>
</html>
I also added a div in JavaScript
const grid = document.querySelector('.grid')
const doodler = document.createElement('div')
If you got your grid defined like that:
const grid = document.querySelector('.grid')
change this:
if(isGamerOver = true){
document.getElementById("grid").style.backgroundImage="url('backgrounds/background-up.png')";
}else{
document.getElementById("grid").style.backgroundImage="url('backgrounds/game-over.png')";
}
to this:
if(isGamerOver = true){
grid.style.backgroundImage="url('backgrounds/background-up.png')";
}else{
grid.style.backgroundImage="url('backgrounds/game-over.png')";
}

Cycle Through Web Pages with Start and Stop Buttons

I have a few URLs that each show the status of some industrial equipment. I'm trying to create an HTML/Javascript solution that, on load, cycles through each of the websites at a set interval, with two buttons to stop the cycle (to take a closer look at something) and restart the cycle (either from the beginning or where it left off, I'm not picky). I'm REALLY rusty, but I got what I think is a good start. Unfortunately, it doesn't work. Here are the CSS and HTML:
html,
body {
height: 100vh;
width: 100vw;
}
#btStart {
position: absolute;
width: 50px;
height: 40px;
left: 20px;
top: 50px;
}
#btStop {
position: absolute;
width: 50px;
height: 40px;
left: 20px;
top: 120px;
}
#infoFrame {
width: 100%;
height: 100%;
}
.holder {
width: 100%;
height: 100%;
position: relative;
}
<!DOCTYPE HTML>
<html>
<head>
<title>Info Cycle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="main.css" rel="stylesheet">
</head>
<body>
<div class="holder">
<iframe src="" id="infoFrame" frameborder="0" allowfullscreen>
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var i = document.getElementById('infoFrame');
var u = document.getElementById('url');
var timer = setInterval(cycleTimer, 5000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1)? -1 : count;
return url;
}
function cycleTimer() {
u.innerHTML = '';
i.src = nextUrl();
i.onload = function(){
u.innerHTML = i.src;
}
}
</script>
</iframe>
<button type="button" id="btStart" onclick="var timer = setInterval(cycleTimer, 5000);">Start</button>
<button type="button" id="btStop" onclick="clearInterval(timer)";>Stop</button>
</div>
</body>
<footer>
</footer>
</html>
Before I added the buttons it would load, then 5 seconds later it would cycle correctly, and so on. Now it only shows the buttons. Looking at the requests, I believe what's happening in my CSS and structure is trash, and it's loading the appropriate URL, but not displaying. I should add, prior to the buttons I only had the iframe with the script in it as a proof of concept. I div'd it, added the stylesheet, and added the buttons, and now here we are.
This may be a rookie mistake, or something more complicated. I haven't done development in a long time, and I'm just trying to solve a little problem at work. If you could spare a minute, I'd be happy to know how to fix this, and also any feedback on what I could be doing better. I'd love to get back into doing more of this, so I'm interested to learn anything the community can share. I've searched the site and the internet, and I've found a couple of related solutions but nothing for this in particular.
Thanks!
EDIT:
In case it helps, below is the HTML before the buttons and stylesheet, which worked (it rotated between webpages every 7 seconds):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Info Cycle</title>
</head>
<body>
<iframe id="frame" src=""
style="
position: fixed;
top: 0px;
bottom: 0px;
right: 0px;
width: 100%;
border: none;
margin: 0;
padding: 0;
overflow: hidden;
z-index: 999999;
height: 100%;
"></iframe>
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var i = document.getElementById('frame');
var u = document.getElementById('url');
var timer = setInterval(cycleTimer, 7000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1)? -1 : count;
return url;
}
function cycleTimer() {
u.innerHTML = '';
i.src = nextUrl();
i.onload = function(){
u.innerHTML = i.src;
}
}
</script>
</body>
</html>
The iframe style was something I found in an old file I'd written (probably copied and pasted from Stack Overflow to just get a thing to work).
The problem here is having the script inside the iframe. If you move your script out of the iframe and put it under body or head then it will work.
<!DOCTYPE HTML>
<html>
<head>
<title>Info Cycle</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="main.css" rel="stylesheet">
<script type="text/javascript">
var urlArray = ['url1.com',
'url2.com',
'url3.com',
'url4.com',
'url5.com'];
var count = 0;
var timer = setInterval(cycleTimer, 5000);
function nextUrl() {
url = urlArray[++count];
count = (count >= urlArray.length - 1) ? -1 : count;
return url;
}
function cycleTimer() {
var i = document.getElementById('infoFrame');
var u = document.getElementById('url');
u.innerHTML = '';
i.src = nextUrl();
i.onload = function () {
u.innerHTML = i.src;
}
}
</script>
</head>
<body>
<div class="holder">
<iframe src="" id="infoFrame" frameborder="0" allowfullscreen>
</iframe>
<button type="button" id="btStart" onclick="var timer = setInterval(cycleTimer, 5000);">Start</button>
<button type="button" id="btStop" onclick="clearInterval(timer)" ;>Stop</button>
</div>
</body>
<footer>
</footer>
</html>

Simple Basketball Motion Javascript

What happens: When I press space button the ball moves up and stops; when press again the ball moves down.
What I need: When I press space button the ball should move up then move down!
I want to some how repeat this function twice with one click ... Its looks simple; I tried to loop twice upon the press of the space button, but it doesn't work as I expected. Any suggestions?
var body = document.getElementById('body');
var basketball = document.getElementById('basketball');
var x = 0;
var y = 0;
var counter = 0;
var inc = Math.PI / 100 ;
body.addEventListener('keydown',function(e){
var ek = e.which;
if(ek==32){
for( var i = 0; i<=1 ;i+=0.01){
x+=i;
y+= Math.sin( counter );
counter+=inc;
basketball.style.left=x;
basketball.style.bottom=y;
}
}
});
*
{
transition: all 1s;
}
#basketball
{
width: 75px;
position: absolute;
bottom: 0;
left: 10;
}
<html>
<head>
<link rel="stylesheet" href="css/index_style.css">
<title>Basket</title>
</head>
<body id="body">
<img src="https://thumbs.dreamstime.com/b/basketball-ball-transparent-checkered-background-realistic-vector-illustration-91566559.jpg" id="basketball">
<script src="js/mine.js"></script>
</body>
</html>
Try this (the function calls itself):
var body = document.getElementById('body');
var basketball = document.getElementById('basketball');
var x = 0;
var y = 0;
var counter = 0;
var inc = Math.PI / 100 ;
function bounce(e, norecall){
var ek = e.which;
console.log('keydown');
if(ek==32){
for( var i = 0; i<=1 ;i+=0.01){
x+=i;
y+= Math.sin( counter );
counter+=inc;
basketball.style.left=x;
basketball.style.bottom=y;
}
}
if (!norecall) { //only runs the first time (when norecall == undefined)
bounce(e, true)
}
}
body.addEventListener('keydown',bounce); //call bounce on keypress
*
{
transition: all 1s;
}
#basketball
{
width: 75px;
position: absolute;
bottom: 0;
left: 10;
}
<html>
<head>
<link rel="stylesheet" href="css/index_style.css">
<title>Basket</title>
</head>
<body id="body">
<img src="https://thumbs.dreamstime.com/b/basketball-ball-transparent-checkered-background-realistic-vector-illustration-91566559.jpg" id="basketball">
<script src="js/mine.js"></script>
</body>
</html>
What this does is the function bounce gets called with norecall being undefined. !norecall is then true, so the function calls itself, this time with norecall being true, so the function doesn’t get called again, therefore mimicing the mouse being pressed twice, which solves the problem.
No need for loops and stuff, you can just use css and add a class that changes the bottom from 0, and use setTimeout to remove it after some time (you need to click on the example so it will get the focus and the key events).
var body = document.getElementById('body');
var basketball = document.getElementById('basketball');
body.addEventListener('keydown',function(e){
basketball.classList.add('up');
setTimeout(function(){
basketball.classList.remove('up');
}, 300);
});
#basketball
{
transition: all 1s;
width: 75px;
position: absolute;
bottom: 0;
left: 10;
}
#basketball.up {
bottom: 25px;
}
<html>
<head>
<link rel="stylesheet" href="css/index_style.css">
<title>Basket</title>
</head>
<body id="body">
<img src="https://thumbs.dreamstime.com/b/basketball-ball-transparent-checkered-background-realistic-vector-illustration-91566559.jpg" id="basketball">
<script src="js/mine.js"></script>
</body>
</html>

File won't open in Chrome or Firefox, file name in URL changes to "0"

I tried searching for "file name changes to 0 in browser" both in Google and here, but got nowhere. This is a simple file which suddenly stopped opening. I can't even get at the inspector to troubleshoot it. Undo/redo history is lost, so that will not help. I'm guessing it's a simple mistake, but I have NEVER seen this before.
<!doctype html>
<html lang="en">
<head>
<title>JS Animated Navigation Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
<!--
var location = 0;
var bar = document.getElementById("bar1");
function myMove()
{
// if (id != 0) clearInterval(id);
location = -144;
// if (location != -144) return; // don't execute onmouseover while previous onmouseover is still running.
id = setInterval(move, 1);
}
function move()
{
location++;
bar.style.left = location + 'px';
if (location == 300)
{
clearInterval(id);
id = setInterval(moveback, 1);
}
}
function moveback()
{
location--;
bar.style.left = location + 'px';
if (location == -144)
{
clearInterval(id);
// id = setInterval(move, 1);
}
}
-->
</script>
<style>
#container
{
width: 600px;
height: 100px;
position: relative;
background: white;
}
#bar1
{
width: 150px;
height: 30px;
position: absolute;
left: -144px;
background-color: white;
}
</style>
</head>
<body>
<p>
<button onclick="myMove()">Click Me</button>
</p>
<div id ="container">
<div id ="animate"><img src="imageGalleryBar.png" alt="Image Gallery" width="150" height="30" id="bar1" onmouseover="myMove()" /></div>
</div>
</body>
</html>
Thank you
You can't use the variable name location as it is a reserved word; what you're actually doing is setting the window.location variable to 0.
Rename it, or put it in a namespace or object.

Categories

Resources