I want to show a clickable button over the mouse cursor, whenever the user hover's over an image.
Code I am using: codepen
const box = document.getElementById("box");
function movebox(e) {
box.style.left = event.clientX - 20 + 'px';
box.style.top = event.clientY - 20 + 'px';
box.style.display = 'block';
}
function removebox() {
box.style.display = 'none';
}
function click() {
console.log("clicked")
}
#maindiv {
border: 1px solid blue;
padding: 1px;
display: flex;
justify-content: center;
text-align: center;
align-items: center;
min-height: 100vh;
}
#maindiv img {
max-width: 400px;
max-height: 400px;
object-fit: scale-down;
border: 1px solid red;
}
#box {
position: absolute;
z-index: 100;
display: none;
}
<!-- bootstrap -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script><div id="maindiv">
<img src="https://images.unsplash.com/photo-1563884993747-a52423c68196?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1374&q=80" onmousemove="movebox(event)" onmouseout="removebox()" />
<button id="box" class="btn btn-primary" onclick="click()">click</button>
</div>
Problems:
Getting unwanted blinking effect on button.
I have tried using the pointer-events: none property on button, but it also disables the onclick events.
Your function can not be named "click" because when you call it you are calling the built in click method.
Updated your code to rely on CSS to show and hide the element. Added hove to the img and the button.
Fixed a bug where you did not account for scroll position.
const box = document.getElementById("box");
function movebox(e) {
box.style.left = window.scrollX + event.clientX - 20 + 'px';
box.style.top = window.scrollY + event.clientY - 20 + 'px';
}
function clickMe() {
console.log("clicked")
}
#maindiv {
border: 1px solid blue;
padding: 1px;
display: flex;
justify-content: center;
text-align: center;
align-items: center;
min-height: 100vh;
}
#maindiv img {
max-width: 400px;
max-height: 400px;
object-fit: scale-down;
border: 1px solid red;
}
#box {
position: absolute;
z-index: 100;
display: none;
transition: all .25s;
}
#maindiv img:hover + #box,
#box:hover
{
display: block;
}
<!-- bootstrap -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script><div id="maindiv">
<img src="https://images.unsplash.com/photo-1563884993747-a52423c68196?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1374&q=80" onmousemove="movebox(event)" />
<button id="box" class="btn btn-primary" onclick="clickMe()">click</button>
</div>
Related
It's very hard to explain. But I'll try, the whole canvas is offset. I'm not sure how this even happened or how to fix it. It's like when your mouse is in the top left corner of the page, and you started in the center, it matches up with the top left corner of the canvas element itself. Use the code snippets to see what I'm talking about.
let currentColor = null;
let inputs = document.getElementsByClassName("style2");
for (const input of inputs) {
input.addEventListener("click", (e) => {
if (e.detail !== 2) e.preventDefault();
});
}
let arr = [];
for (let i = 0; i < inputs.length + 1; i++) {
arr.push(i.toString());
}
arr.shift();
for (const input of inputs) {
input.addEventListener("input", (e) => {
const { value } = document.getElementById(e.target.id);
currentColor = value;
$("#selectedColor").css("background-color", value);
})
input.addEventListener("click", (e) => {
const { value } = document.getElementById(e.target.id);
currentColor = value;
$("#selectedColor").css("background-color", value);
})
}
var rangeslider = document.getElementById("sliderRange");
const setSize = document.getElementById("setSize")
const submit = document.getElementById("submit")
submit.addEventListener("click", (e) => {
rangeslider.value = setSize.value
})
const button = document.getElementById("clear")
// create canvas element and append it to document body
var canvas = document.getElementById('canvas');
// some hotfixes... ( ≖_≖)
// get canvas 2D context and set him correct size
var ctx = canvas.getContext('2d');
resize();
// last known position
var pos = { x: 0, y: 0 };
window.addEventListener('resize', resize);
button.addEventListener('click', clear)
document.addEventListener('mousemove', draw);
document.addEventListener('mousedown', setPosition);
document.addEventListener('mousemove', setPosition);
// new position from mouse event
function setPosition(e) {
let canvas = document.getElementById("canvas")
pos.x = e.clientX
pos.y = e.clientY
}
// resize canvas
function resize() {
ctx.canvas.width = 650;
ctx.canvas.height = 375;
}
function draw(e) {
// mouse left button must be pressed
if (e.buttons !== 1) return;
let canvas = document.getElementById('canvas');
console.log(pos)
ctx.beginPath(); // begin
ctx.lineWidth = rangeslider.value;
ctx.lineCap = 'round';
ctx.strokeStyle = currentColor;
ctx.moveTo(pos.x, pos.y); // from
setPosition(e);
ctx.lineTo(pos.x, pos.y); // to
ctx.stroke(); // draw it!
}
function clear() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
html, body {
height: 100%;
width: 100%;
font-family: sans-serif;
background-color: #B3B7B5;
/* overflow: hidden; */
}
.style2 {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: transparent;
width: 35px;
height: 35px;
border: none;
cursor: pointer;
}
.style2::-webkit-color-swatch {
border-radius: 50%;
border: 3px solid #000000;
}
.style2::-moz-color-swatch {
border-radius: 50%;
border: 3px solid #000000;
}
.box {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
gap: 5px;
max-width: 320px;
margin: 0 auto;
padding: 7.5px 10px;
}
.box1 {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
gap: 5px;
max-width: 9999px;
margin: 0 auto;
padding: 10px 10px;
}
.box5 {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
gap: 5px;
max-width: 650px;
margin: 0 auto;
padding: 10px 10px;
}
.box2 {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center;
gap: 5px;
max-width: 9999px;
margin: 0 auto;
padding: 10px 10px;
}
#selectedColor {
width: 100px;
height: 30px;
border: 3px solid black;
border-radius: 5px;
background-color: black;
}
.canvas {
height: 350px;
width: 650px;
border: 3px solid black;
border-radius: 5px;
background-color: white;
cursor: crosshair;
position: relative;
/* left: 50%; */
}
#clear {
width: 50px;
height: 35px;
font-size: 15px;
border-radius: 5px;
}
#submit {
width: 59px;
height: 23px;
margin: auto;
left: 35%;
border-radius: 5px;
position: relative;
}
.rangeslider {
width: 50%;
}
.myslider {
-webkit-appearance: none;
background: #FCF3CF ;
width: 50%;
height: 20px;
opacity: 2;
}
.myslider::-webkit-slider-thumb {
-webkit-appearance: none;
cursor: pointer;
background: #34495E ;
width: 5%;
height: 20px;
}
.myslider:hover {
opacity: 1;
}
.rangeslider {
left: 38%;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box5">
<canvas class="canvas" id="canvas"></canvas>
</div>
<div class="box1">
<button id="clear">Clear</button><br>
</div>
<div class="box1">
<div class="rangeslider">
<input type="range" min="1" max="100" value="5" class="myslider" id="sliderRange">
</div>
</div>
<div class=box1>
<div>
<input id="setSize" type="text" placeholder="Set Brush Size... (Max 100)">
<br>
<button type="submit" id="submit" for="setSize">Submit</button>
</div>
</div>
<div class="box">
<div class="container">
<input type="color" value="#000000" class="style2" id="1" />
</div>
<div class="container">
<input type="color" value="#ffffff" class="style2" id="2" />
</div>
<div class="container">
<input type="color" value="#ffffff" class="style2" id="3" />
</div>
<div class="container">
<input type="color" value="#ffffff" class="style2" id="4" />
</div>
<div class="container">
<input type="color" value="#ffffff" class="style2" id="5" />
</div>
</div>
<div class="box">
<label for="selectedColor">Current Color:</label>
<div id="selectedColor"></div>
</div>
<script src="script.js"></script>
</body>
</html>
I know this code is kind of weird but please bare with me.
This is actually a simple one to solve. You merely forgot to offset the clientX and clientY. You see, those coordinates are in window space therefore (0,0) will be the top left of your window. If your canvas is also in the top left then everything will seem all fine but in your case the canvas is center so the coordinates won't align. This can be fixed by subtracting the coordinates by the screen position of the canvas.
Here's an example:
function setPosition(e) {
let canvas = document.getElementById("canvas")
let bounds = canvas.getBoundingClientRect()
pos.x = e.clientX - bounds.x
pos.y = e.clientY - bounds.y
}
You can read more about getBoundingClientRect over at https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
The way of calculating the position of the mouse is not appropriate, it is necessary to take into account the deviation of the canvas compared to the viewport. You can't do it using getBoundingClientRect() :
function setPosition(e) {
const canvas = document.getElementById("canvas");
const bounds = canvas.getBoundingClientRect();
pos.x = e.clientX - bounds.left;
pos.y = e.clientY - bounds.top;
}
But you also have to fix the .canvas css class by removing width and height or by setting the same height than in the resize function.
https://codepen.io/Joulss/pen/BaPYgpZ?editors=1111
I am working on a match color game. After the guesses are completed the initialize function is called, which resets the program. After the first set of guesses, when the initialize function is called again, code below the initialize function (two setTimeouts), that asks the user where a color is does not fire again. Thanks for the help.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="styles.css">
</head>
<body style="pointer-events: none">
<div class="question">
<div class="questionbox">
<p>Where is:</p>
</div>
</div>
<div class="container">
<div class="container-box">
<div class="colorbox"></div>
<div class="colorbox"></div>
<div class="colorbox"></div>
<div class="colorbox"></div>
<div class="colorbox"></div>
<div class="colorbox"></div>
</div>
</div>
<div class="score-container">
<div class="score">Score: <span id="score">0</span></div>
</div>
<div class="button">
<button type="button" id="btn">Restart</button>
</div>
<script src="script.js"></script>
</body>
</html>
css
body {
margin: 0;
padding: 0;
box-sizing: border-box;
height: 100vh;
}
.container {
height: 100vh;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.question {
position: absolute;
height: 100vh;
width: 100%;
display: none;
flex-direction: column;
justify-content: center;
align-items: center;
}
.questionbox {
display: flex;
align-items: center;
justify-content: center;
border: 1px solid black;
background-color: red;
height: 400px;
width: 600px;
color: white;
font-size: 33px;
}
.container-box {
width: 600px;
display: flex;
flex-direction: row;
flex-wrap: wrap;
height: 400px;
}
.colorbox {
display: flex;
height: 200px;
width: 200px;
border: 1px solid black;
box-sizing: border-box;
}
.hide {
background-color: grey !important;
}
.open {
border: 40px white;
cursor: default;
}
.button {
width: 100vw;
display: flex;
flex-direction: row;
justify-content: center;
}
#btn {
display: flex;
position: absolute;
bottom: 50px;
justify-content: center;
text-align: center;
}
.score-container {
display: flex;
position: absolute;
width: 100vw;
justify-content: center;
bottom: 100px;
}
.border {
border: 8px solid #66ff00 !important;
}
.border-red {
border: 8px solid #EE4B2B !important;
}
javascript
let colors = ["red", "yellow", "blue", "green", "orange", "purple"],
$fullbox = $('.container'),
$popup = $('.question'),
gamecolor = [],
$restart = $('#btn'),
clicks = 0,
guessColor = [],
score = 0,
guess;
window.onload = initialize();
// initialize board
function initialize () {
clicks = 0;
$('.colorbox').removeClass('border');
$('.colorbox').removeClass('border-red');
$('.colorbox').each(function () {
$('body').css("pointer-events", "none");
$('.colorbox').removeClass('hide');
$(this).css("border", "2px solid black");
let randColor = colors[Math.floor(Math.random() * colors.length)];
$(this).css("background-color", `${randColor}`);
setTimeout(hide, 3000);
})
}
function hide() {
$('.colorbox').each(function () {
$(this).addClass('hide');
$('body').css("pointer-events", "auto");
$('.colorbox').css("pointer-events", "auto");
})
}
//restart
$('#btn').on('click', () => {
initialize();
})
setTimeout(() => {
$popup.css('display', 'flex');
guessColor = colors[Math.floor(Math.random() * colors.length)];
$('.questionbox').find('p').after(`<span> ${guessColor}?</span>`);
}, 2500)
setTimeout(() => {
$popup.css('display', 'none');
$('body').css("pointer-events", "auto");
}, 6000)
$('.container').on('click', '.colorbox', function () {
console.log($(this));
$(this).css("pointer-events", "none");
clicks++;
guess = $(this)[0].style.backgroundColor;
console.log(guess);
$(this).removeClass('hide');
console.log(guessColor);
console.log(guess);
if (guess === guessColor) {
score;
score++;
$('#score').html(score);
$(this).addClass('border');
} else {
$(this).addClass('border-red');
// $(this).css("border", "4px solid red");
}
if (clicks >= colors.length) {
setTimeout(initialize, 800);
$('body').css("pointer-events", "none");
}
console.log($(this));
});
If you mean the timeouts aren't firing again, you need to put them within initialize()'s scope. Otherwise they are one-time only.
function initialize () {
clicks = 0;
$('.colorbox').removeClass('border');
$('.colorbox').removeClass('border-red');
$('.colorbox').each(function () {
$('body').css("pointer-events", "none");
$('.colorbox').removeClass('hide');
$(this).css("border", "2px solid black");
let randColor = colors[Math.floor(Math.random() * colors.length)];
$(this).css("background-color", `${randColor}`);
setTimeout(hide, 3000);
});
setTimeout(() => {
$popup.css('display', 'flex');
guessColor = colors[Math.floor(Math.random() * colors.length)];
$('.questionbox').find('p').after(`<span> ${guessColor}?</span>`);
}, 2500)
setTimeout(() => {
$popup.css('display', 'none');
$('body').css("pointer-events", "auto");
}, 6000)
}
Right now my webpage has vertical snap to scroll to each of the three 100vh sections.
In the second section, I have 3 100vw divs lined up horizontally with { overflow-x: scroll }. So I went ahead and try to link the my button that would help translate x using the following code:
const button = document.getElementById('slide');
button.onclick = function () {
document.getElementById('wrapper').scrollLeft += 20;
};
I guess right now the numbers doesn't matter. I just want to see it moving, but I can't get it to move on-click. Any ideas?
codepen.io/brandoniscool/pen/vYBMZyM
300% width is set on the wrapper, so it is the wrapper parent (id special) which needs to scroll.
Setting scrollLeft on the special element works as expected. document.getElementById('special').scrollLeft += 20;
const button = document.getElementById('slide');
button.onclick = function () {
document.getElementById('special').scrollLeft += 20;
};
* {
margin: 0;
font-family: 'Montserrat', sans-serif;}
body {
scroll-snap-type: y mandatory;
overflow-x: hidden;
width: 100vw;
height: 100%;
}
section {
scroll-snap-align: start;
height: 100vh;
outline: 1px dashed lightgray;
background-color: #c1d37f;
overflow-x: scroll;
}
.verticalSection {
display: flex;
justify-content: center;
flex-direction: row;
height: inherit;
border: 0.5px dashed #664e4c;
box-sizing: border-box;
/* so the border doesnt increase over the 100% width and heights */
}
#wrapper {
height: 100%;
width: 300%;
display: flex;
}
.horizontalSection {
background-color: #f9d4bb;
height: 100%;
width: 100%;
display: flex;
justify-content: center;
flex-direction: row;
border: 0.5px dashed #664e4c;
box-sizing: border-box; /* so the border doesnt increase over the 100% width and heights */
}
h1 {
color: #664e4c;
font-size: 3em;
margin: auto;
}
<!DOCTYPE html>
<html>
<head>
<title>vertical snap and horizontal snap integration</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts.js"></script>
</head>
<body>
<section>
<div class="verticalSection"> <h1> BOX 1</h1> </div>
</section>
<section id="special">
<div id="wrapper">
<div class="horizontalSection"> <h1> BOX 2.1</h1> <button id="slide" type="button">Next</button></div>
<div class="horizontalSection"> <h1> BOX 2.2</h1> </div>
<div class="horizontalSection"> <h1> BOX 2.3</h1> </div>
</div>
</section>
<section>
<div class="verticalSection"> <h1> BOX 3</h1> </div>
</section>
</body>
</html>
I have a modal box which I can call okay but I can't close it, regardless of whether you click on the x or anywhere else on the screen. Sorry if I'm not describing it well enough - I'm very new.
I've tried the w3 schools demo and also other s/o examples and I just can't for the life of me figure out what I'm doing wrong. Full code supplied below as requested.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Benny the virtual blob</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="virtualpet.css">
<link href="https://fonts.googleapis.com/css?family=Barriecito|Special+Elite&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/de2b0ad954.js"></script>
</head>
<body>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<i class="fas fa-skull-crossbones"></i><br>
<p>"Oh, no! You killed Benny!"<br>
"He was <span id="dead">x</span> days young"</p>
</div>
</div>
<div class="container">
<h1>Benny the Blob</h1>
<p>Look after Benny, the blob. Play with him, feed him, care for him when he's sick. But if you ignore him for too long, he'll die. How long will you be able to keep him alive?</p>
<button type="button" class="btn reset">Birth Benny</button>
</div>
<div class="action">
<img id="age" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857600/virtual%20pet/item-box.png" alt="window for life span">
<img id="backing" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561670551/virtual%20pet/little-board.png" alt="pin board image">
<div id="bennyNormal" class="start"></div>
<p id="ageStatus" class="start" ><span id="days">0</span> days old</p>
<img id="heart" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561725918/virtual%20pet/l1.png" alt="health points image">
<img id="star" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s1.png" alt="happy points image">
<img id="hungry" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h1.png" alt="hunger points image">
<div id="tasks">
<img id="medicine" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857719/virtual%20pet/medicene.png" alt="medicine">
<img id="food" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857661/virtual%20pet/sandwich.png" alt="food">
<img id="toys" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857776/virtual%20pet/gamesbox.png" alt="toys">
<img id="drink" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857689/virtual%20pet/red-smoothie.png" alt="glass of juice">
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="virtualpet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
var resetBtn = document.querySelector(".reset");
var start = document.querySelectorAll(".start");
var ageing = document.getElementById("days");
var heart= document.getElementById("heart");
var star = document.getElementById("star");
var tummy = document.getElementById("hungry");
var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];
var content = document.getElementsByClassName("modal-content")
var dead = document.getElementById("dead");
$(document).ready(function () {
var count=0;
var c = count;
var cd = $('#days');
$(resetBtn).click(function(){
$(".start").toggle();
if ($(this).text() == "Birth Benny") {
$(this).text("Restart");
} else {
$(this).text("Birth Benny");
}});
var interv = setInterval(function() {
c++;
cd.html(c);
randomNum();
happyStatus();
hungerStatus();
healthStatus();
}, 60000);
var health = 4;
var happy = 4;
var hungry = 4;
function randomNum(){
//pick a 'health'
var h=Math.random();
//pick a happy
var s=Math.random();
//pick a hungry
var f=Math.random();
if (h <0.5) {
health--;
}
if (s <0.5) {
happy--;
}
if (f <0.5) {
hungry--;
}
};
function healthStatus(){
if (health===4){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725918/virtual%20pet/l1.png");
}if(health===3){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l2.png");
}if (health===2){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l3.png");
}if(health===1){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l4.png");
}if (health===0){
deathScreen();
}
};
function happyStatus(){
if (happy===4){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s1.png");
}if(happy===3){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s2.png");
}if (happy===2){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s3.png");
}if(happy===1){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s4.png");
}if (happy===0){
deathScreen();
}
};
function hungerStatus(){
if (hungry===4){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h1.png");
}if(hungry===3){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h2.png");
}if (hungry===2){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h3.png");
}if(hungry===1){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h4.png");
}if (hungry===0){
deathScreen();
}
};
function deathScreen(){
$(start).hide();
$('#myModal').modal('show');
$(dead).text(c);
clearInterval(interv);
};
$(span).on("click", function(){
$('#myModal').modal('toggle');
});
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
$('#myModal').modal('toggle');
}
}
});
body {
margin: 0;
text-align: center;
}
h1 {
font-family: 'Barriecito', cursive;
text-align: center;
}
p {
font-family: 'Special Elite', cursive;
text-align: left;
}
#ageStatus {
top: -850px;
left: 150px;
position: relative;
font-size: 2em;
display: none;
}
.container {
width: 600px;
margin: 0 auto;
text-align: center;
}
.btn{
background-color: pink!important;
font-family: 'Barriecito', cursive;
}
#backing {
width: 800px;
margin: 0 auto;
z-index: -10;
position: relative;
top: 0px;
display: none;
}
#bennyNormal {
width:327px;
height: 444px;
display: none;
background-image:url("https://res.cloudinary.com/dytmcam8b/image/upload/v1561677299/virtual%20pet/Sheet.png");
top: -450px;
left:250px;
position: relative;
transform: scale(0.5);
-webkit-animation: benny 3s steps(10) infinite;
-moz-animation: benny 1.5s steps(10) infinite;
-ms-animation: benny 1.5s steps(10) infinite;
-o-animation: benny 1.5s steps(10) infinite;
animation: benny 1.5s steps(10) infinite;
}
#-webkit-keyframes benny{
from{background-position:0px;}
to{background-position:-3270px;}
}
}
#keyframes normal{
from {background-position:0px;}
to {background-position:-3270px;}
}
#heart {
height: 150px;
width: 150px;
transform: scale(0.5);
top: -970px;
left: 400px;
position: relative;
display: none;
}
#star {
height: 150px;
width: 150px;
top: -970px;
left: 350px;
transform: scale(0.5);
position: relative;
display: none;
}
#hungry {
height: 80px;
width: 80px;
position: relative;
left: 330px;
top: -970px;
display: none;
}
#age {
width: 250px;
position: relative;
top: 180px;
left: 100px;
display: none;
}
#medicine {
width: 100px;
position: relative;
top: -870px;
left: 150px;
display: none;
}
#toys {
width: 100px;
position: relative;
top:-1000px;
left:-50px;
display: none;
}
.action {
position: relative;
height: 400px;
width: 800px;
margin: 0 auto;
}
#food {
width: 100px;
position: relative;
left: 440px;
top: -1000px;
display: none;
}
#drink{
width: 100px;
position: relative;
left: 240px;
top: -900px;
display: none;
}
.hidden {
display: block;
}
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 100; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(242, 114, 223); /* Fallback color */
background-color: rgb(242, 114, 223); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid rgb(242, 114, 223);
width: 20%;
font-family: 'Barriecito', cursive;
font-size: 2em;
text-align: center;
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
#dead {
text-align: center;
}
My x is non-responsive and neither can I click anywhere else on the screen to close it. There's no error message in Chrome developer. When I put my cursor over the x the link appears 'dead'.
Use .modal('toggle') according the docs here: https://getbootstrap.com/docs/4.0/components/modal/#modaltoggle
$('#myModal').modal('toggle');
But on the default modal behavior, when user click out the modal window (gray area) it is closed automatically, see this working here: https://jsfiddle.net/Lc8ayf9k/
Consider review the javascript and stylesheet references in your page
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
Try this
$('#myModal').modal('toggle');
If you are using Bootstrap, then the modal settings bootstrap.js file should be able to close the modal.
Here is an example of Bootstrap modal.
`<div id="myModal" class="modal fade" role='dialog'>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4>myModal</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" title="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>"Oh, no! You killed Benny!"<br>
"He was <span id="dead">x</span> days young"</p>
</div>
</div>
</div>
</div>`
If you need a custom JavaScript to close the modal, you can try out this script:
`<script type="text/javascript">
// Get the modal object
var modal = document.getElementById('myModal');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>`
I believe the way you attached your event listeners is wrong. If you're using vanilla javascript, you should assign the DOM inside a variable first:
var thisSpan = document.getElementById("close");
thisSpan.addEventListener("click", function(){
modal.style.display = "none";
});
With jQuery, it is a bit simpler, especially if you're using bootstrap modal plugin. You can follow the other solutions given by the fellow peers here. If it is a custom modal, then we can have a similar pattern as the previous code:
$("#close").on("click", function(){
modal.style.display = "none";
});
I would like to prevent a larger div from being dragged out of smaller div, like facebook does with it's profile images.
Does anyone have an idea of how I would go about to do this?
All the best, Laurens
In the following link I give an example of what i mean.
draggable_outside
PS: I'm sorry, I didn't get the JS section to work in the code snippet, it's my first post. I wrote it as a script in the HTML section.
.wrapper {
width: 400px;
height: 300px;
display: flex;
align-items: center;
justify-content: center;
}
.parent {
background: gray;
display: block;
width: 100px;
height: 100px;
}
.child {
position: absolute;
width: 200px;
height: 200px;
display: block;
background: blue;
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.child').draggable();
});
</script>
<div class="wrapper">
<div class="parent">
<div class="child">
</div>
</div>
</div
You can use jQuery draggable function as follows.
Here in drag event we reset x and y if they cross the boundaries.
See the fiddle here
.wrapper {
width: 400px;
height: 300px;
display: flex;
align-items: center;
justify-content: center;
}
.parent {
background: gray;
display: block;
width: 100px;
height: 100px;
}
.child {
position: absolute;
width: 200px;
height: 200px;
display: block;
background: blue;
opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.child').draggable(
{
drag: function(event, ui) {
var offset = $(this).offset();
var xPos = offset.left;
var yPos = offset.top;
$('#posX').text('x: ' + xPos);
$('#posY').text('y: ' + yPos);
// console.log(xPos);
// console.log(yPos);
if(ui.position.left>250)
{
ui.position.left=250;
}
if(ui.position.left<-40)
{
ui.position.left=-40;
}
if(ui.position.top<-90)
{
ui.position.top=-90;
}
if(ui.position.top>200)
{
ui.position.top=200;
}
}
});
});
</script>
<div class="wrapper">
<div class="parent">
<div class="child">
</div>
</div>
</div