I am building a video game where fireballs drop from the top screen. The spaceship, moved by controllers, must avoid those fireballs in order win. My issue is that I do not know how to detect when the spaceship collides into fireballs. However, I found this link: Detect if animated object touched another object in DOM. I analysed this code and it seems it only works for his issue particularly. Do you guys know how to do this?
Code for image spaceship and fireball:
<img src="Photo/fireball.png" id="fireball">
<img src="Photo/Spaceship1.png" id="icon-p">
Code for spaceship:
let rect = icon
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 -= 10}
if (keys[39] || keys[68]) {pos.left += 10}
if (keys[38] || keys[90]) {pos.top -= 10}
if (keys[40] || keys[83]) {pos.top += 10}
var owidth = display.offsetWidth
var oheight = display.offsetHeight
var iwidth = rect.offsetWidth
var iheight = rect.offsetHeight
if (pos.left < 0) pos.left = -10
if (pos.top < 0) pos.top = -10
if (pos.left + iwidth >= owidth) pos.left = owidth-iwidth
if (pos.top + iheight >= oheight) pos.top= oheight-iheight
rect.setAttribute("data", owidth + ":" + oheight)
rect.style.left = pos.left + "px"; rect.style.top = pos.top + "px"}
let sens = setInterval(loop, 1000 / 60)
Code for fireball:
function fFireball(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))}
let fireballElement = document.querySelector("#fireball");
let fireball = {x: fFireball(fireballElement.offsetWidth), y: 0}
const fireLoop = function() {
fireball.y += 2
fireballElement.style.top = fireball.y + 'px'
if (fireball.y > window.innerHeight) {
fireball.x = fFireball(fireballElement.offsetWidth)
fireballElement.style.left = fireball.x + 'px'; fireball.y = 0}}
fireballElement.style.left = fireball.x + 'px'
let fireInterval = setInterval(fireLoop, 1000 / 100)
Thanks!
here I've integrated collision detection for your game. The most notable thing is in this function:
function checkCollision() {
var elem = document.getElementById("icon");
var elem2 = document.getElementById("fireball");
if ( detectOverlap(elem, elem2) && elem2.getAttribute('hit')=='false' ){
hits++; // detect hit and increase
elem2.setAttribute('hit', true); // set attribute to not have flooding
console.log( hits ); // console it just to see it
}
setTimeout( checkCollision, 20);
}
In lower window you can test demo that I've built for you without images but some random boxes as images :)
Good luck with game man, cool
//////////
"use strict"
//Stay on focus
function stayOnFocus() {
setTimeout(function() {
alert("Do not exit window or game progression will be lost!")
}, 1000)
}
let hits = 0
//"A" keypress plays Music
document.addEventListener('keydown', function(e) {
if (e.keyCode !== 173) {
//document.getElementById('audio').play()
}
})
//Input Validation
let icon = document.getElementById("icon")
let fireballElement = document.querySelector("#fireball")
var input = document.getElementById("input")
input.addEventListener("keydown", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("begin-timer").click()
}
})
//CountDown (3...2...1)
var count = 3
function countDown() {
function preventCountFast() {
document.getElementById("count").innerHTML = count
if (count > 0) {
count--
} else {
clearInterval(ncount);
document.getElementById("count").style.display = "none"
}
}
var ncount = setInterval(preventCountFast, 1000)
}
//Name displayed + space(switch between images) + parameter icon displayed
function Username(field) {
field = input.value
if (field == "") {
alert("Complete blanks");
return false
}
document.getElementById("askName").style.display = "none"
setTimeout(function() {
document.getElementById("name").innerHTML = "Player: " + field
icon.style.display = 'block';
fireballElement.style.display = "block"
const images = ["https://placehold.it/30x30", "https://placehold.it/90x90",
"https://placehold.it/120x40", "https://placehold.it/100x100"
]
document.body.onkeyup = function(e) {
if (e.keyCode === 32) {
hits++;
icon.src = images[hits % 5]
}
}
checkCollision();
}, 4000)
}
//Spaceship moves into space + prevent going out borders
let display = document.getElementById("body");
let rect = icon
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 -= 10
}
if (keys[39] || keys[68]) {
pos.left += 10
}
if (keys[38] || keys[90]) {
pos.top -= 10
}
if (keys[40] || keys[83]) {
pos.top += 10
}
var owidth = display.offsetWidth
var oheight = display.offsetHeight
var iwidth = rect.offsetWidth
var iheight = rect.offsetHeight
if (pos.left < 0) pos.left = -10
if (pos.top < 0) pos.top = -10
if (pos.left + iwidth >= owidth) pos.left = owidth - iwidth
if (pos.top + iheight >= oheight) pos.top = oheight - iheight
rect.setAttribute("data", owidth + ":" + oheight)
rect.style.left = pos.left + "px";
rect.style.top = pos.top + "px"
}
let sens = setInterval(loop, 1000 / 60)
//Parameter Sensibility
let param = document.getElementById("parameters")
let b2 = document.getElementById("body2")
document.getElementById("general").addEventListener("click", function() {
param.style.display = "block";
b2.style.display = "none"
})
function validateSens() {
b2.style.display = "block";
param.style.display = "none";
clearInterval(sens)
let sensibilty = parseFloat(document.getElementById("sensibilty").value)
switch (sensibilty) {
case 1:
sens = setInterval(loop, 1000 / 40);
break;
case 2:
sens = setInterval(loop, 1000 / 60);
break;
case 3:
sens = setInterval(loop, 1000 / 80);
break;
default:
alert("Sorry, a bug occured")
}
}
//Fireball script
function fFireball(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))
}
let fireball = {
x: fFireball(fireballElement.offsetWidth),
y: 0
}
const fireLoop = function() {
fireball.y += 2;
fireballElement.style.top = fireball.y + 'px'
if (fireball.y > window.innerHeight) {
fireball.x = fFireball(fireballElement.offsetWidth)
fireballElement.style.left = fireball.x + 'px';
fireball.y = 0;
fireballElement.setAttribute('hit', false );
}
}
fireballElement.style.left = fireball.x + 'px'
let fireInterval = setInterval(fireLoop, 1000 / 100)
function checkCollision() {
var elem = document.getElementById("icon");
var elem2 = document.getElementById("fireball");
if (detectOverlap(elem, elem2) && elem2.getAttribute('hit')=='false' ){
hits++; // detect hit
elem2.setAttribute('hit', true);
aler("hi")
}
setTimeout( checkCollision, 20);
}
// detect fn
var detectOverlap = (function() {
function getPositions(elem) {
var pos = elem.getBoundingClientRect();
return [
[pos.left, pos.right],
[pos.top, pos.bottom]
];
}
function comparePositions(p1, p2) {
var r1, r2;
r1 = p1[0] < p2[0] ? p1 : p2;
r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
}
return function(a, b) {
var pos1 = getPositions(a),
pos2 = getPositions(b);
return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
};
})();
body {
user-select: none;
margin: 0px;
height: 100vh;
padding: 0;
width: 100%;
background-image: url(Photo/bg.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
animation: intro-fade 3s;
background-size: cover;
overflow: hidden;
}
#askName {
display: block;
z-index: 1;
margin-left: auto;
margin-top: 12%;
margin-right: auto;
width: 400px;
text-align: center;
background-color: #737373;
opacity: 0.8;
border-radius: 15px;
padding: 40px 50px 40px 50px;
}
#askName:hover {
opacity: 0.9
}
#askName>label {
text-align: center;
font-size: 150%;
font-weight: lighter;
text-align: center;
}
#askName>input {
display: block;
font-size: 100%;
margin: 30px auto 20px auto;
border: none;
border-radius: 10px;
padding: 10px 20px 10px 20px;
}
#askName>button {
background-color: #e6e6e6;
cursor: pointer;
padding: 10px 20px 10px 20px;
border: none;
border-radius: 10px;
}
#count {
margin-top: 13%;
animation: count-down 16s;
font-weight: lighter;
font-family: cursive;
text-align: center;
color: black;
font-size: 200px;
}
h6 {
margin-right: 20px;
padding-top: 5px;
font-weight: normal;
font-family: sans-serif;
margin-top: 0px;
color: white;
text-align: center;
font-size: 190%;
cursor: default;
}
h6:hover {
font-size: 210%
}
#icon {
position: absolute;
top: 0;
left: 0;
cursor: none;
width: 9%;
}
#general {
position: absolute;
cursor: pointer;
min-width: 4%;
top: 10px;
width: 4%;
right: 10px;
}
#general:hover {
transform: rotate(-100deg)
}
#parameters {
text-align: center;
display: none;
animation: intro-fade 3s;
height: auto;
border: none;
background-color: #d9d9d9;
color: black;
position: absolute;
padding: 0px 60px 20px 60px;
left: 50%;
width: auto;
min-width: 200px;
top: 50%;
transform: translate(-50%, -50%);
border-radius: 13px;
}
h3 {
color: black;
font-weight: normal;
font-size: 150%;
}
#sensibilty {
display: block;
margin-right: auto;
margin-left: auto;
}
#validateSens {
margin-top: 20px;
border: none;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
#keyframes intro-fade {
from {
opacity: 0
}
to {
opacity: 1
}
}
#keyframes count-down {
from {
transform: scale(0)
}
to {
transform: scale(1)
}
}
<body id="body" onload="stayOnFocus()">
<img src="https://placehold.it/350x350" id="general">
<section id="parameters">
<h3> Choose your sensibility </h3>
<input type="range" id="sensibilty" min="1" max="3" value="2">
<button id="validateSens" onclick="validateSens()"> Submit </button>
</section>
<main id="body2">
<form id="askName" title="Write your name"> <label> Enter your username: </label>
<input id="input" type="text" maxlength="10" autofocus>
<button type="button" onclick="countDown(); return Username()" id="begin-timer"> Submit </button>
</form>
<h6 id="name"></h6>
<h2 id="count"></h2>
<img src="https://placehold.it/50x52" id="fireball" style="display:none; width:3%; position:absolute; cursor:none">
<img src="https://placehold.it/80x40" id="icon" style="display:none">
</main>
I'm trying to make am image scroll that uses control button and also slides automatically, my problem now is I need to know how to return the div to starting point when the div hit end on left side or on right side, what I could get so far is to know when the div hit an end but don't know how to return it to starting point in case of automatic sliding.
var n = 3; //total number of slides to be display at once
var totalDeal = 9; //total deals to be display
var sliderTotalWidth = 100; //in percentage append % later
var z = (100 / totalDeal) + '%'; //ddslides width
var x = totalDeal / n;
var counter = 1;
$(".dialyDealSlider").css('width', x + '00%');
//$(".ddslides").css('width', ddslidesWidth);
fillDailyDeal(totalDeal, z);
function fillDailyDeal(totalDeal, z) {
var imgUrl = '{$img}';
var ext = '.jpg';
var width = "width:" + z
for (var i = 1; i <= totalDeal; i++) {
var myDiv = $(
"<div class='ddslides' style='" + width + "' >" +
'<div class="dddesc">' +
'<div class="ddtitle">' +
'The is the title of the item it\'s a long title' +
'</div>' +
"<div class='ddprice'>$"+i+"00</div>" +
'<button class="ddview" title="View Item">view item</button>' +
'</div>' +
'<div class="ddimg">' +
'</div>' +
'<div class="vDivider"></div>' +
'<div class="ddSaleBadge">sold 44%</div>' +
'</div>');
$("#dialyDealSlider").append(myDiv);
}
}
$("#prev, #next").click(function() {
if (this.id == "next") {
counter++;
} else {
counter--;
}
//console.log(counter);
if (counter == x) {
alert('rigth end');
//$("#dialyDealSlider").css('left', '0px');
}
if (counter == 1) {
alert('left end');
}
var ddslidesWidth = $(".ddslides").width();
var dir = this.id == "next" ? '-=' : '+=';
var width = ddslidesWidth * n;
//alert(leftpos);
$("#dialyDealSlider").animate({
left: dir + width
}, 800);
});
my code is here JSFIDDLE: https://jsfiddle.net/sammyzeal/LqpL1n2g/
As we can see in the above fiddle, when we slide the div and the price is between $700 and $900 we hit an end then there's an alert, on this point if a user keeps on clicking this next button how do I scroll to the starting point which is between price $100 and $300, I hope my question is cleared and thanks in advance for any help
I just saw that you updated the code as i said , good work. So i wont hesitate to help now, you should make a separate slideNow() function that slides next or previous and you should increment/decrement the counter after checking the current or previous slides, if it is the last slide create a function separate to goToStart() to move to the first slide and if it is th first slide just return from there and do nothing, you can use the following script and test it with various combinations like, first going to the last slide by clicking and then on the last slide click next and see if it goes to the first on and then try clicking left from the first slide and verify if it goes left or stays still.
See a demo below
var n = 3; //total number of slides to be display at once
var totalDeal = 9; //total deals to be display
var sliderTotalWidth = 100; //in percentage append % later
var z = (100 / totalDeal) + '%'; //ddslides width
var x = totalDeal / n;
var counter = 1;
$(".dialyDealSlider").css('width', x + '00%');
//$(".ddslides").css('width', ddslidesWidth);
fillDailyDeal(totalDeal, z);
function fillDailyDeal(totalDeal, z) {
var imgUrl = '{$img}';
var ext = '.jpg';
var width = "width:" + z
for (var i = 1; i <= totalDeal; i++) {
var myDiv = $(
"<div class='ddslides' style='" + width + "' >" +
'<div class="dddesc">' +
'<div class="ddtitle">' +
'The is the title of the item it\'s a long title' +
'</div>' +
"<div class='ddprice'>$" + i + "00</div>" +
'<button class="ddview" title="View Item">view item</button>' +
'</div>' +
'<div class="ddimg">' +
'</div>' +
'<div class="vDivider"></div>' +
'<div class="ddSaleBadge">sold 44%</div>' +
'</div>');
$("#dialyDealSlider").append(myDiv);
}
}
$("#prev, #next").click(function() {
var target = this.id;
//console.log(counter);
if (counter == x && target == "next") {
counter = 1;
goToStart();
return;
}
if (counter == 1 && target == "prev") {
return;
}
if (target == "next") {
counter++;
} else {
counter--;
}
//slide the slides
slideNow(target, n);
});
function goToStart() {
$("#dialyDealSlider").animate({
left: 0
}, 800);
}
function slideNow(target, n) {
var ddslidesWidth = $(".ddslides").width();
var dir = target == "next" ? '-=' : '+=';
var width = ddslidesWidth * n;
//alert(leftpos);
$("#dialyDealSlider").animate({
left: dir + width
}, 800);
}
.dailyDeal {
height: 150px;
width: 100%;
margin-top: 15px;
padding: 0 !important;
}
.dialyDealBox {
float: left;
height: 150px;
padding: 0 !important;
overflow: hidden;
}
.dialyDealSlider {
width: 100%;
height: 150px;
position: absolute;
border: 1px solid #ddd;
}
.ddslides {
height: 150px;
width: 2%;
float: left;
background-color: #fff;
position: relative;
padding: 10px 0;
}
#media only screen and (max-width: 768px) {
.ddslides {
width: 16.66%;
}
}
#media (max-width:320px) {
.ddslides {
width: 33.33%;
}
}
.ddimg {
float: left;
margin: auto;
height: 100%;
width: 32%;
margin-right: 4px;
}
.ddimg>a>img {
height: 100%;
width: 100%;
}
.dddesc {
float: left;
margin: auto;
height: 100%;
width: 65%;
padding: 0 10px 0 15px;
}
.ddSaleBadge {
position: absolute;
top: 5px;
right: 5px;
width: 37px;
height: 38px;
padding: 5px 2px 4px 3px;
overflow: hidden;
background: url("/trobay/img/icon/label.png") no-repeat 50% 50%;
line-height: 14px;
text-align: center;
color: #fff;
}
.ddtitle {
margin-bottom: 10px;
}
.ddtitle>a {
font-size: 14px;
color: #666666;
text-decoration: none;
}
.ddtitle>a:hover {
color: #e4393c;
text-decoration: none;
}
.ddprice {
color: #e4393c;
font-size: 16px;
margin-bottom: 10px;
}
.ddview {
color: #fff;
background-color: #e4393c;
font-size: 14px;
border: 0;
outline: 0;
padding: 4px;
font-weight: bold;
}
.ddslider-prev {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 5px;
color: #666666;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
left: 0;
z-index: 10;
background-color: rgba(221, 221, 221, 1);
display: block;
}
.ddslider-next {
cursor: pointer;
position: absolute;
right: 0;
top: 50%;
width: auto;
margin-top: -22px;
padding: 5px;
color: #666666;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
z-index: 10;
background-color: rgba(221, 221, 221, 1);
display: block;
}
.vDivider {
height: 130px;
border-right: 1px dotted #666;
position: absolute;
top: 10px;
;
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="dailyDeal col-md-12">
<div class="dialyDealBox col-xs-10" id="dialyDealBox">
<div class="dialyDealSlider" id="dialyDealSlider">
</div>
<div class="ddslider-prev" id="prev">❮</div>
<div class="ddslider-next" id="next">❯</div>
</div>
</div>
</div>
I want to save and restore data from div - that is container of other divs,
In order to make it I use local storage and JSON like this:
window.onload = restoreJason;
function makeJson(){
var canvas = document.getElementById("canvas");
var shapes = canvas.querySelectorAll("div[class='drag']");
var divs = new Object();
for(var i=0; i<shapes.length; ++i){
divs[shapes[i].getAttribute('innerHTML')] = shapes[i].innerHTML;
}
localStorage.setItem("divs", JSON.stringify(divs));
}
function restoreJason(){
var divs = JSON.parse(localStorage.getItem("divs"));
var canvas = document.getElementById("canvas");
var shapes = canvas.querySelectorAll("div[class='drag']");
for(var i = 0; i<shapes.length; i++){
shapes[i].value = divs[shapes[i].getAttribute("innerHTML")];
}
console.log(divs);
}
However, I don't know how to access the innerHTML of the elements and save it or restore it.
What do you think I shall do?
(To be more detailed - I need to save the content of the div when user click on "save", and load it when the user click "load". This is a snippest of it...)
NOTICE: the "canvas" is just the id of the main div, and not a real "canvas".
function randomizeColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
}
function randomizeRectangle() {
var width = Math.random() * 700 + 50;
var height = Math.random() * 250 + 50;
if (height <= 20) {
height = 20;
}
var posX = Math.round(Math.random() * window.innerWidth);
var posY = Math.round(Math.random() * window.innerHeight);
var randomRecObj = {
"width": width + "px",
"height": height + "px",
"posX": posX,
"posY": posY
};
return randomRecObj;
}
function makeShape() {
var rect = randomizeRectangle();
var rectDOM = document.createElement("div");
rectDOM.className = "rectangle";
rectDOM.style.border = "1px solid black";
rectDOM.style.width = rect.width;
rectDOM.style.height = rect.height;
rectDOM.style.background = randomizeColor();
rectDOM.style.top = rect.posY + "px";
rectDOM.style.left = rect.posX + "px";
//rectDOM.addEventListener("click", selectShape);
// rectDOM.style.transform =rect.rotation;
return rectDOM;
}
function randRect() {
var rectDOM = makeShape();
var canvas = document.getElementById("canvas");
canvas.appendChild(rectDOM);
}
function randOval() {
var ovalDOM = makeShape();
ovalDOM.style.borderRadius = "50%";
var canvas = document.getElementById("canvas");
canvas.appendChild(ovalDOM);
}
function changeColor(){
}
function cancelSelection() {
var selected = document.getElementsByClassName("selected");
while (selected) {
selected[0].classList.remove(selected[0]);
}
}
function removeShape(event) {
var selectedShapes = document.getElementsByClassName("selected");
var len = selectedShapes.length;
while (len > 0) {
selectedShapes[0].parentNode.removeChild(selectedShapes[0]);
--len;
}
}
function removeCorners(rectDom) {
var corners = document.getElementsByClassName("corners");
var len = corners.length;
while (len > 0) {
corners[0].classList.remove("corners");
--len;
}
}
.header{
background: #4ABDAC;
color: #fff;
margin: 1px;
}
hr{
border-top: 3px double #2a3132;
}
ul{
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #90afc5;
}
li{
float: left;
border: 2px solid #336b87;
padding: 3px;
margin: 3px;
}
li>a{
display: block;
color: #2a3132;
text-decoration: none;
padding: 10px 14px;
}
#color{
margin-left: 150px;
}
#rect{
margin-left: 100px;
}
li>a:hover{
color: #763626;
cursor: pointer;
}
#canvas{
background: #66a5ad;
position: relative;
height: 1200px;
width: 100%;
}
.corners{
position: absolute;
height: 10px;
width: 10px;
background:#fff;
border: 1px solid black;
display: none;
}
.selected .corners{
display: inline-block;
}
.cornerUpLeft{
top: -5px;
left: -5px;
}
.cornerUpRight{
top: -5px;
right: -5px;
}
.cornerBtmLeft{
bottom: -5px;
left: -5px;
}
.cornerBtmRight{
bottom: -5px;
right: -5px;
}
.rectangle{
position: absolute;
}
.colorBox{
border: 1px solid black;
height: 20px;
width: 20px;
list-style: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sketch Board - Eyal Segal Project</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet">
<script src="js/sketch.js"></script>
</head>
<body>
<h1 class="header">Sketch Board</h1>
<div>
<ul class="toolbar">
<li><a>Load</a></li>
<li id="Save"><a>Save</a></li>
<li id="rect"><a onclick="randRect()">Rectangle</a></li>
<li><a onclick="randOval()">Oval</a></li>
</ul>
<hr>
</div>
<div class="canvas" id="canvas">
</div>
</body>
</html>
All you need to do is set the .innerHTML of the div id="canvas" into localStorage. There's no need for JSON or loops at all.
Also, don't use inline HTML event attributes (onclick). Instead, do all your JavaScript separately using modern, standards based event handling.
Lastly, there is no need for <a> elements to be able to respond to a click event. Actually, your a elements are invalid as they don't have a name or href attribute anyway. The li elements can simply be set up for click events.
This is the code to do it but it won't execute here in the Stack Overflow snippet environment, but you can see it working here.
// Get reference to the "canvas"
var can = document.getElementById("canvas");
// Save the content of the canvas to localStorage
function saveData(){
localStorage.setItem("canvas", can.innerHTML);
}
// Get localStorage data
function restoreData(){
can.innerHTML = localStorage.getItem("canvas");
}
// get load and save references
var load = document.getElementById("load");
var save = document.getElementById("save");
// Set up event handlers
load.addEventListener("click", restoreData);
save.addEventListener("click", saveData);
// Get references to the rect and oval "buttons" and set their event handlers
var rect = document.getElementById("rect");
rect.addEventListener("click", randRect);
var oval = document.getElementById("oval");
oval.addEventListener("click", randOval);
function randomizeColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
}
function randomizeRectangle() {
var width = Math.random() * 700 + 50;
var height = Math.random() * 250 + 50;
if (height <= 20) {
height = 20;
}
var posX = Math.round(Math.random() * window.innerWidth);
var posY = Math.round(Math.random() * window.innerHeight);
var randomRecObj = {
"width": width + "px",
"height": height + "px",
"posX": posX,
"posY": posY
};
return randomRecObj;
}
function makeShape() {
var rect = randomizeRectangle();
var rectDOM = document.createElement("div");
rectDOM.className = "rectangle";
rectDOM.style.border = "1px solid black";
rectDOM.style.width = rect.width;
rectDOM.style.height = rect.height;
rectDOM.style.background = randomizeColor();
rectDOM.style.top = rect.posY + "px";
rectDOM.style.left = rect.posX + "px";
//rectDOM.addEventListener("click", selectShape);
// rectDOM.style.transform =rect.rotation;
return rectDOM;
}
function randRect() {
var rectDOM = makeShape();
var canvas = document.getElementById("canvas");
canvas.appendChild(rectDOM);
}
function randOval() {
var ovalDOM = makeShape();
ovalDOM.style.borderRadius = "50%";
var canvas = document.getElementById("canvas");
canvas.appendChild(ovalDOM);
}
function changeColor(){
}
function cancelSelection() {
var selected = document.getElementsByClassName("selected");
while (selected) {
selected[0].classList.remove(selected[0]);
}
}
function removeShape(event) {
var selectedShapes = document.getElementsByClassName("selected");
var len = selectedShapes.length;
while (len > 0) {
selectedShapes[0].parentNode.removeChild(selectedShapes[0]);
--len;
}
}
function removeCorners(rectDom) {
var corners = document.getElementsByClassName("corners");
var len = corners.length;
while (len > 0) {
corners[0].classList.remove("corners");
--len;
}
}
.header{
background: #4ABDAC;
color: #fff;
margin: 1px;
}
hr{
border-top: 3px double #2a3132;
}
ul{
list-style: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #90afc5;
}
li{
float: left;
border: 2px solid #336b87;
padding: 3px;
margin: 3px;
}
li>a{
display: block;
color: #2a3132;
text-decoration: none;
padding: 10px 14px;
}
#color{
margin-left: 150px;
}
#rect{
margin-left: 100px;
}
li>a:hover{
color: #763626;
cursor: pointer;
}
#canvas{
background: #66a5ad;
position: relative;
height: 1200px;
width: 100%;
}
.corners{
position: absolute;
height: 10px;
width: 10px;
background:#fff;
border: 1px solid black;
display: none;
}
.selected .corners{
display: inline-block;
}
.cornerUpLeft{
top: -5px;
left: -5px;
}
.cornerUpRight{
top: -5px;
right: -5px;
}
.cornerBtmLeft{
bottom: -5px;
left: -5px;
}
.cornerBtmRight{
bottom: -5px;
right: -5px;
}
.rectangle{
position: absolute;
}
.colorBox{
border: 1px solid black;
height: 20px;
width: 20px;
list-style: none;
}
<h1 class="header">Sketch Board</h1>
<div>
<ul class="toolbar">
<li id="load">Load</li>
<li id="save">Save</li>
<li id="rect">Rectangle</li>
<li id="oval">Oval</li>
</ul>
<hr>
</div>
<div class="canvas" id="canvas">
</div>
It works fine in desktop browsers but if I use in iPad/Android/any mobile device, then it will not drag. I already use jQuery touch punch.
var currentSlide = 8;
var onMouseDown = function(event) {
var elements = (allElementsFromPoint(event.pageX, event.pageY));
for (var i = 0; i < elements.length; i++) {
if ($(elements[i]).hasClass("slide-canvas-layer")) {
if (tool == "pencil" || tool == "brush") {
canvas.addEventListener('mousemove', onPaint, false);
}
}
}
};
var onMouseUp = function(event) {
var elements = (allElementsFromPoint(event.pageX, event.pageY));
for (var i = 0; i < elements.length; i++) {
if ($(elements[i]).hasClass("slide-canvas-layer")) {
canvas.removeEventListener('mousemove', onPaint, false);
}
}
};
var onTouchStart = function(event) {
var elements = (allElementsFromPoint(event.touches[0].pageX, event.touches[0].pageY));
for (var i = 0; i < elements.length; i++) {
if ($(elements[i]).hasClass("slide-canvas-layer")) {
if (tool == "pencil" || tool == "brush") {
canvas.addEventListener('touchmove', onPaint, false);
}
}
}
};
var onTouchEnd = function(event) {
var elements = (allElementsFromPoint(event.changedTouches[0].pageX, event.changedTouches[0].pageY));
for (var i = 0; i < elements.length; i++) {
if ($(elements[i]).hasClass("slide-canvas-layer")) {
canvas.removeEventListener('mousemove', onPaint, false);
canvas.removeEventListener('touchmove', onPaint, false);
}
}
};
window.onload = function() {
$(".menu-left-tool-box-button").bind('click', function(e) {
tool = $(this).val();
setTool(this);
});
$(".coversheet").draggable({
containment: "parent",
scroll: false
});
$(".coversheet").find(".coversheet-plus-minus-button").bind('click', function(e) {
switch ($(this).val()) {
case "+":
$(this).parent().parent().css({
width: ($(this).parent().parent().width() + 50) + "px",
height: ($(this).parent().parent().height() + 50) + "px"
});
break;
case "-":
if ($(this).parent().parent().width() > 100) {
$(this).parent().parent().css({
width: ($(this).parent().parent().width() - 50) + "px",
height: ($(this).parent().parent().height() - 50) + "px"
});
}
break;
}
});
$(".menu-left-tool-box-button-child-pencil").bind('click', function(e) {
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(this).addClass("menu-left-tool-box-button-child-pencil-active");
ctx.lineWidth = parseInt($(this).attr("value"));
ctx.strokeStyle = "#000";
ctx.globalAlpha = 1;
octx.lineWidth = parseInt($(this).attr("value"));
octx.strokeStyle = "#000";
octx.globalAlpha = 1;
tool = "pencil";
setTool($(".menu-left-tool-box-button[value=pencil]"));
});
$(".menu-left-tool-box-button-child-brush").bind('click', function(e) {
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
$(this).addClass("menu-left-tool-box-button-child-brush-active");
$(".menu-left-tool-box-button[value=brush]").css({
backgroundImage: 'url(./images/' + $(this).attr("color") + '_paint.png)'
});
ctx.strokeStyle = $(this).attr("value");
ctx.globalAlpha = 1;
ctx.lineWidth = 20;
octx.strokeStyle = $(this).attr("value");
octx.globalAlpha = 1;
octx.lineWidth = 20;
tool = "brush";
setTool($(".menu-left-tool-box-button[value=brush]"));
});
$(".menu-right-button").bind('click', function(e) {
switch ($(this).val()) {
case "checkAnswer":
var total = $(".cell-clickable").length;
var right = 0;
$(".cell-clickable").each(function() {
switch ($(this).attr("value")) {
case "cell-clickable-dot1":
if ($(this).hasClass("cell-clickable-dot1")) {
right++;
$(this).find(".cell-clickable-button").removeClass("true-image").removeClass("false-image").addClass("true-image").removeClass("hide");
} else {
if ($(this).hasClass("cell-clickable-dot2")) {
$(this).find(".cell-clickable-button").removeClass("true-image").removeClass("false-image").addClass("false-image").removeClass("hide");
}
}
break;
case "cell-clickable-dot2":
if ($(this).hasClass("cell-clickable-dot2")) {
right++;
$(this).find(".cell-clickable-button").removeClass("true-image").removeClass("false-image").addClass("true-image").removeClass("hide");
} else {
if ($(this).hasClass("cell-clickable-dot1")) {
$(this).find(".cell-clickable-button").removeClass("true-image").removeClass("false-image").addClass("false-image").removeClass("hide");
}
}
break;
}
if (total == right) {
$(".cell-clickable-dot1").css({
backgroundColor: "rgba(61, 203, 27,0.5)",
boxShadow: "0px 0px 0px 5px rgb(61, 203, 27)"
});
$(".cell-clickable").find(".cell-clickable-button").addClass("hide");
}
});
}
});
$(".menu-left-preview-box-preview").bind('click', function(e) {
window.location = "page" + ($(this).index() + 1) + ".html";
});
var native_width = 0;
var native_height = 0;
var magnifyIsMouseDown = false;
$(".magnify").parent().mousedown(function(e) {
magnifyIsMouseDown = true;
});
$(".magnify").mousemove(function(e) {
if (isDragging) {
if (!native_width && !native_height) {
var image_object = new Image();
image_object.src = $(".small").attr("src");
native_width = image_object.width;
native_height = image_object.height;
} else {
var magnify_offset = $(this).offset();
var mx = e.pageX - magnify_offset.left;
var my = e.pageY - magnify_offset.top;
if ($(".large").is(":visible")) {
var rx = Math.round(mx / $(".small").width() * native_width - $(".large").width() / 2) * -1;
var ry = Math.round(my / $(".small").height() * native_height - $(".large").height() / 2) * -1;
var bgp = rx + "px " + ry + "px";
var px = mx - $(".large").width() / 2;
var py = my - $(".large").height() / 2;
$(".large").css({
left: px,
top: py,
backgroundPosition: bgp
});
}
}
}
});
var isDragging = false;
$(".magnify").parent().mouseup(function(e) {
isDragging = false;
});
$(".magnify").parent().mousedown(function(e) {
// $(".large").fadeOut(100);
isDragging = true;
});
$(".large").fadeIn(100);
manageSlide();
}
function allElementsFromPoint(x, y) {
var element, elements = [];
var old_visibility = [];
while (true) {
element = document.elementFromPoint(x, y);
if (!element || element === document.documentElement) {
break;
}
elements.push(element);
old_visibility.push(element.style.visibility);
element.style.visibility = 'hidden';
}
for (var k = 0; k < elements.length; k++) {
elements[k].style.visibility = old_visibility[k];
}
elements.reverse();
return elements;
}
function manageSlide() {
$("#slide-number").text(currentSlide);
$(".slide").addClass("hide");
$(".slide").removeClass("hide");
$(".menu-left-preview-box-preview").removeClass("menu-left-preview-box-preview-active");
$(".menu-left-preview-box-preview").eq(currentSlide - 1).addClass("menu-left-preview-box-preview-active");
$(".slide-canvas-layer").addClass("hide");
$(".slide-canvas-layer-opacity").addClass("hide");
tool = null;
setTool();
initCanvas();
}
var zoomScale = 1;
function setTool(sender) {
$(".menu-left-tool-box-button").removeClass("tool-box-button-active");
switch (tool) {
case "pencil":
$(".slide-canvas-layer").removeClass("hide");
$(".slide-canvas-layer-opacity").removeClass("hide");
$(sender).addClass("tool-box-button-active");
var flag = false;
$(".menu-left-tool-box-button-child-pencil").each(function() {
if ($(this).hasClass("menu-left-tool-box-button-child-pencil-active")) {
flag = true;
}
});
if (!flag) {
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(".menu-left-tool-box-button-child-pencil").eq(0).addClass("menu-left-tool-box-button-child-pencil-active");
ctx.lineWidth = parseInt($(".menu-left-tool-box-button-child-pencil").eq(0).attr("value"));
ctx.strokeStyle = "#000";
ctx.globalAlpha = 1;
octx.lineWidth = parseInt($(".menu-left-tool-box-button-child-pencil").eq(0).attr("value"));
octx.strokeStyle = "#000";
octx.globalAlpha = 1;
}
break;
case "brush":
$(".slide-canvas-layer").removeClass("hide");
$(".slide-canvas-layer-opacity").removeClass("hide");
$(sender).addClass("tool-box-button-active");
var flag = false;
$(".menu-left-tool-box-button-child-brush").each(function() {
if ($(this).hasClass("menu-left-tool-box-button-child-brush-active")) {
flag = true;
}
});
if (!flag) {
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
$(".menu-left-tool-box-button-child-brush").eq(0).addClass("menu-left-tool-box-button-child-brush-active");
ctx.strokeStyle = $(".menu-left-tool-box-button-child-brush").eq(0).attr("value");
ctx.globalAlpha = 1;
ctx.lineWidth = 20;
octx.strokeStyle = $(".menu-left-tool-box-button-child-brush").eq(0).attr("value");
octx.globalAlpha = 1;
octx.lineWidth = 20;
}
break;
case "coversheet":
if ($(".slide").find(".coversheet").hasClass("hide")) {
$(".slide").find(".coversheet").removeClass("hide");
} else {
$(".slide").find(".coversheet").addClass("hide");
}
break;
case "back":
if (currentSlide > 1) {
currentSlide--;
window.location = "page" + currentSlide + ".html";
}
break;
case "next":
if (currentSlide < $(".menu-left-preview-box-preview").length) {
currentSlide++;
window.location = "page" + currentSlide + ".html";
}
break;
case "restart":
location.reload();
break;
case "zoom":
zoomScale += 0.10;
$("#slide-content").css({
transform: "scale(" + zoomScale + ")",
webkitTransform: "scale(" + zoomScale + ")",
mozTransform: "scale(" + zoomScale + ")"
});
$(".slide-canvas-layer").addClass("hide");
$(".slide-canvas-layer-opacity").addClass("hide");
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
tool = null;
break;
case "reduse":
if (zoomScale > .20) {
zoomScale -= 0.10;
}
$("#slide-content").css({
transform: "scale(" + zoomScale + ")",
webkitTransform: "scale(" + zoomScale + ")",
mozTransform: "scale(" + zoomScale + ")"
});
$(".slide-canvas-layer").addClass("hide");
$(".slide-canvas-layer-opacity").addClass("hide");
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
tool = null;
break;
default:
$(".slide-canvas-layer").addClass("hide");
$(".slide-canvas-layer-opacity").addClass("hide");
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
tool = null;
break;
}
}
var prevTool = null;
var tool = null;
var cumulativeOffset = function(element) {
var top = 0,
left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return {
top: top,
left: left
};
};
var canvas = null,
ctx = null;
var ocanvas = null,
octx = null;
var firstTimeDocumentEvent = false;
var mouse = {
x: 0,
y: 0
};
var last_mouse = {
x: 0,
y: 0
};
function initCanvas() {
document.body.addEventListener('mousedown', onMouseDown, false);
document.body.addEventListener('mouseup', onMouseUp, false);
document.body.addEventListener('touchstart', onTouchStart, false);
document.body.addEventListener('touchend', onTouchEnd, false);
document.body.addEventListener('touchleave', onTouchEnd, false);
document.body.addEventListener('touchcancel', onTouchEnd, false);
canvas = document.querySelector('.slide-canvas-layer');
ctx = canvas.getContext('2d');
ocanvas = document.querySelector('.slide-canvas-layer-opacity');
octx = ocanvas.getContext('2d');
var sketch = document.querySelector('#slide-content');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width')) - 15;
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
ocanvas.width = parseInt(sketch_style.getPropertyValue('width')) - 15;
ocanvas.height = parseInt(sketch_style.getPropertyValue('height'));
$(canvas).css({
marginTop: (-1 * parseInt(sketch_style.getPropertyValue('height'))) + "px"
});
$(ocanvas).css({
marginTop: (-1 * parseInt(sketch_style.getPropertyValue('height'))) + "px"
});
canvas.addEventListener('mousemove', function(e) {
e.preventDefault();
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
var offSet = cumulativeOffset(this);
mouse.x = e.pageX - offSet.left;
mouse.y = e.pageY - offSet.top;
}, false);
ocanvas.addEventListener('mousemove', function(e) {
e.preventDefault();
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
var offSet = cumulativeOffset(this);
mouse.x = e.pageX - offSet.left;
mouse.y = e.pageY - offSet.top;
}, false);
canvas.addEventListener('touchmove', function(e) {
e.preventDefault();
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
var offSet = cumulativeOffset(this);
mouse.x = e.touches[0].pageX - offSet.left;
mouse.y = e.touches[0].pageY - offSet.top;
}, false);
ocanvas.addEventListener('touchmove', function(e) {
e.preventDefault();
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
var offSet = cumulativeOffset(this);
mouse.x = e.touches[0].pageX - offSet.left;
mouse.y = e.touches[0].pageY - offSet.top;
}, false);
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
octx.lineWidth = 3;
octx.lineJoin = 'round';
octx.lineCap = 'round';
}
var mouseDownOn = null;
var onPaint = function() {
if (tool == "pencil") {
ctx.beginPath();
ctx.moveTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.closePath();
ctx.stroke();
} else if (tool == "brush") {
octx.beginPath();
octx.moveTo(last_mouse.x, last_mouse.y);
octx.lineTo(mouse.x, mouse.y);
octx.closePath();
octx.stroke();
}
};
.hide {
display: none!important;
}
body {
font-family: Verdana;
}
body > * {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#wrapper {
width: 1000px;
height: 550px;
background-color: #cecbcb;
margin: auto;
}
#menu-left {
height: 100%;
width: 100px;
float: left;
}
#menu-left-tool-box {
height: 60%;
width: 100%;
box-shadow: 0px 1px 0px 0px #b2b0b0;
text-align: center;
}
.menu-left-tool-box-button {
width: 35px;
height: 35px;
background-color: transparent;
margin: 4px;
padding: 0;
outline: none;
border-width: 1px;
background-position: center;
background-repeat: no-repeat;
}
.menu-left-tool-box-button:hover {
transform: scale(1.05);
-webkit-transform: scale(1.05);
-moz-transform: scale(1.05);
cursor: pointer;
}
.tool-box-button-active {
background-color: rgba(30, 182, 18, 0.3);
}
.menu-left-tool-box-button-child-pencil {
width: 10px;
height: 10px;
margin: 0.5px;
padding: 0;
border-width: 1px;
background-size: contain;
float: left;
}
.menu-left-tool-box-button-child-pencil-active {
box-shadow: 0px 0px 0px 1px #000;
}
.menu-left-tool-box-button-child-brush {
width: 10px;
height: 10px;
margin: 0.5px;
padding: 0;
border-width: 1px;
background-size: contain;
float: left;
}
.menu-left-tool-box-button-child-brush-active {
box-shadow: 0px 0px 0px 1px #000;
}
#menu-left-preview-box {
height: 40%;
width: 100%;
overflow-x: hidden;
text-align: center;
overflow-y: auto;
}
.menu-left-preview-box-preview {
width: 38px;
height: 31px;
background-color: transparent;
box-shadow: 0px 0px 1px 0px #b2b0b0;
border: none;
outline: none;
}
.menu-left-preview-box-preview-active {
box-shadow: 0px 0px 1px 1px #13bb0c;
}
#content {
height: 100%;
width: 850px;
background-color: #d4a1a5;
box-shadow: -1px 0px 0px 0px #b2b0b0;
overflow: auto;
float: left;
}
.slide {
height: 100%;
width: 100%;
background-color: #d4a1a5;
}
.slide-title {
height: 35px;
width: 820px;
padding: 15px;
}
.slide-title-content {
height: 35px;
background-color: red;
border-radius: 20px;
}
.slide-title-content-eye {
height: 25px;
width: 25px;
border-radius: 100px;
margin: 5px;
border-width: 1px;
outline: none;
background-position: center;
background-repeat: no-repeat;
float: left;
}
.slide-title-content-text {
height: 25px;
margin: 5px;
float: left;
color: white;
}
.slide-content {
height: 470px;
width: 100%;
overflow: auto;
}
.false-image {
background-image: url('./images/false.jpg');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.true-image {
background-image: url('./images/true.jpg');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.slide-canvas-layer {
position: fixed;
z-index: 999;
}
.slide-canvas-layer-opacity {
position: fixed;
z-index: 999;
opacity: 0.5;
}
.coversheet {
height: 100px;
width: 100px;
background-color: white;
position: absolute;
z-index: 1000;
}
.coversheet-plus-minus {
background-color: #000;
width: 71px;
height: 50px;
line-height: 50px;
/*position: absolute;*/
right: 0;
}
.coversheet-plus-minus-button {
background-color: transparent;
color: white;
border: none;
margin: 0;
font-size: 18px;
margin: 2px;
padding: 7px;
}
#menu-right {
height: 100%;
width: 50px;
box-shadow: -1px 0px 0px 0px #b2b0b0;
float: right;
}
.menu-right-button {
height: 30px;
width: 30px;
border-radius: 100px;
margin: 10px;
border-width: 1px;
outline: none;
background-position: center;
background-repeat: no-repeat;
background-color: transparent;
}
#menu-right-image {
height: 160px;
width: 100%;
position: relative;
top: 240px;
}
/**********OVERRIDE CSS*/
.ui-state-hover,
.ui-state-active {
background-color: rgba(57, 187, 31, 0.5);
border: none;
}
/***********/
#slide-content {
height: 100%;
width: 100%;
transform-origin: left top;
-webkit-transform-origin: left top;
-moz-transform-origin: left top;
}
.magnify {
position: relative;
background-color: #d4a1a5;
height: 100%;
margin: auto;
}
.large {
width: 133px;
height: 133px;
position: absolute;
border-radius: 100%;
box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25);
background: url('https://lh3.googleusercontent.com/t789bbPUzJzrVs6cDPZNtiDxX9NCEWggBIW1IDCbeJllWjMOXy5ILBBFCYu9UjKJLsmCyubMREZjTZnelGwMyup8nVLP-VeMUg8oF0mCXN7gkcOweuJYVYTuj3Cx4rhuoOy8jvM-v83vrmT0-bn1tJx2YdLraQ9p7X82jL8rz9iLSNUgVv36Lxs9rfKpBGTyM7_8rzBsZonWXmcMTgInDdhL5mWx-J97bPOyJ9XA1bltKNRposrL69pdQW1WOAUWKj-uTT5K5z6GjaLeT-vN7gJSCb0NFUauszdao_Z5GFSyKOHWWjChXY3Q5CKBtg7Ir-uXoi4UFArTlHNPvuXCnJQptWv-L0TtZ2RrKpMgjimPoBKsGFjUxzYcY95kfZjGlm5-7V5Uut_Nw58Rk0bCz1EWUrW8nzDfawdilyJkDMn3dIhqlzJ8NGGZ5-2hwJTUOIyfrIQat7273nAPCkid6553CiLF57RGptiCxonWn5CZbpU4O7E8nudVMLPiYNY-nuupA-GOhh8-v6heBza6ijkGIpyyTFLieNBO9IjFTw=s220-no') no-repeat;
background-color: #d4a1a5;
display: none;
margin: auto;
}
/*To solve overlap bug at the edges during magnification*/
.small {
display: block;
width: 100%;
}
.large-image {
background: url('https://photos-1.dropbox.com/t/2/AAAnwmx1QvCzmWFYW5i8a3u_gOPGCt19gs_lBJOqwCS93A/12/134709958/png/32x32/1/_/1/2/icon_magnify_glass.png/EK_Up2cYgQQgBygH/R1kBQnLrN-RrPOYcREvqvMMrOMI-rfEOs5ZVgV-3Ayo?size=1024x768&size_mode=2') no-repeat;
height: 112%;
width: 114%;
position: absolute;
top: 73%;
left: 70%;
}
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
<div class="slide-content">
<div id="slide-content">
<div class="magnify" style="width: 266px;">
<div class="large" style="display: none; left: 195.615px; top: 79.0139px; background-position: -150px -54px;">
<div class="large-image"></div>
</div>
<img class="small" src="https://lh3.googleusercontent.com/gzHg89Pc4MtSrIeH__viNCTdBDDemmYf5VDG7vnZzRiaqWBKOKEzHH0PtlpLu8vyA27dg0q7-pmxAggQEF3p5JsDCPWjbux1uQJGLDNTSLsB7MVJG_cBWDDZqkdcshbeCfXCC4UCQMe1ogugc1R8zduLOfeONFnbhGObEFmBzBF60E6ff8lN8BBoZSxPGW_p3LvTdC4k49ULEVZR9QlJDo_JuMUIM-kSBtrN6WEtQ0RRJPUnqIrwmWj3ec_37hdSSzdPHmYLaNPTbJ1wF3dY8wYn5sJG6tdxk7qp-gI-q7xcFEK2huR6YwJtKTpx5U6mn2tr8Vs00vuvHf1fzi-_40ZWA3XNKWh8syUbTs-WYob7Xb4mSKCr5P4QTfUtHFwHuREv45j24LRdSe5_8B_YWCnIB6wG5x4PbNUEn70OlYSvVgS_rYEkeVqMcY0hQCJuIivfkBacTYFrTF61obq1ixtYSmkyhp8CV3atCsHFm2JwKIlJBZ5fwwnZICfKDITDt1qYsb64TrhNL7Wg7BHSazQ6Tkr3exVtQZ6yp57PsQ=s220-no">
</div>
</div>
<canvas class="slide-canvas-layer-opacity hide" width="835" height="470" style="margin-top: -470px;"></canvas>
<canvas class="slide-canvas-layer hide" width="835" height="470" style="margin-top: -470px;"></canvas>
</div>
I updated your Jsfiddle (new one here), there were some issues with your code when running on mobile.
1. mousedown/mouseup/mousemove versus touchstart/touchend/touchmove
Changed your mouseup and mousedown functions to be triggered also by touchstart and touchend
Old:
$(".magnify").parent().mouseup(function(e) {
isDragging = false;
});
$(".magnify").parent().mousedown(function(e) {
isDragging = true;
});
New:
$(".magnify").parent().on("mouseup touchend",function(e) {
isDragging = false;
});
$(".magnify").parent().on("mousedown touchstart",function(e) {
isDragging = true;
});
Similarly for mousemove
Old:
$(".magnify").mousemove(function(e) {
New:
$(".magnify").on("mousemove touchmove",function(e) {
2. event's pageX and pageY undefined in mobile
In your code
var mx = e.pageX - magnify_offset.left;
var my = e.pageY - magnify_offset.top;
are NaN on mobile because e.pageX and e.pageY are undefined, so I adapted your code for touch events following this answer to Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event? :
if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
mx = touch.pageX - magnify_offset.left;
my = touch.pageY - magnify_offset.top;
}
var currentSlide = 8;
var onMouseDown = function(event) {
var elements = (allElementsFromPoint(event.pageX, event.pageY));
for (var i = 0; i < elements.length; i++) {
if ($(elements[i]).hasClass("slide-canvas-layer")) {
if (tool == "pencil" || tool == "brush") {
canvas.addEventListener('mousemove', onPaint, false);
}
}
}
};
var onMouseUp = function(event) {
var elements = (allElementsFromPoint(event.pageX, event.pageY));
for (var i = 0; i < elements.length; i++) {
if ($(elements[i]).hasClass("slide-canvas-layer")) {
canvas.removeEventListener('mousemove', onPaint, false);
}
}
};
var onTouchStart = function(event) {
var elements = (allElementsFromPoint(event.touches[0].pageX, event.touches[0].pageY));
for (var i = 0; i < elements.length; i++) {
if ($(elements[i]).hasClass("slide-canvas-layer")) {
if (tool == "pencil" || tool == "brush") {
canvas.addEventListener('touchmove', onPaint, false);
}
}
}
};
var onTouchEnd = function(event) {
var elements = (allElementsFromPoint(event.changedTouches[0].pageX, event.changedTouches[0].pageY));
for (var i = 0; i < elements.length; i++) {
if ($(elements[i]).hasClass("slide-canvas-layer")) {
canvas.removeEventListener('mousemove', onPaint, false);
canvas.removeEventListener('touchmove', onPaint, false);
}
}
};
window.onload = function() {
$(".menu-left-tool-box-button").bind('click', function(e) {
tool = $(this).val();
setTool(this);
});
$(".coversheet").draggable({
containment: "parent",
scroll: false
});
$(".coversheet").find(".coversheet-plus-minus-button").bind('click', function(e) {
switch ($(this).val()) {
case "+":
$(this).parent().parent().css({
width: ($(this).parent().parent().width() + 50) + "px",
height: ($(this).parent().parent().height() + 50) + "px"
});
break;
case "-":
if ($(this).parent().parent().width() > 100) {
$(this).parent().parent().css({
width: ($(this).parent().parent().width() - 50) + "px",
height: ($(this).parent().parent().height() - 50) + "px"
});
}
break;
}
});
$(".menu-left-tool-box-button-child-pencil").bind('click', function(e) {
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(this).addClass("menu-left-tool-box-button-child-pencil-active");
ctx.lineWidth = parseInt($(this).attr("value"));
ctx.strokeStyle = "#000";
ctx.globalAlpha = 1;
octx.lineWidth = parseInt($(this).attr("value"));
octx.strokeStyle = "#000";
octx.globalAlpha = 1;
tool = "pencil";
setTool($(".menu-left-tool-box-button[value=pencil]"));
});
$(".menu-left-tool-box-button-child-brush").bind('click', function(e) {
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
$(this).addClass("menu-left-tool-box-button-child-brush-active");
$(".menu-left-tool-box-button[value=brush]").css({
backgroundImage: 'url(./images/' + $(this).attr("color") + '_paint.png)'
});
ctx.strokeStyle = $(this).attr("value");
ctx.globalAlpha = 1;
ctx.lineWidth = 20;
octx.strokeStyle = $(this).attr("value");
octx.globalAlpha = 1;
octx.lineWidth = 20;
tool = "brush";
setTool($(".menu-left-tool-box-button[value=brush]"));
});
$(".menu-right-button").bind('click', function(e) {
switch ($(this).val()) {
case "checkAnswer":
var total = $(".cell-clickable").length;
var right = 0;
$(".cell-clickable").each(function() {
switch ($(this).attr("value")) {
case "cell-clickable-dot1":
if ($(this).hasClass("cell-clickable-dot1")) {
right++;
$(this).find(".cell-clickable-button").removeClass("true-image").removeClass("false-image").addClass("true-image").removeClass("hide");
} else {
if ($(this).hasClass("cell-clickable-dot2")) {
$(this).find(".cell-clickable-button").removeClass("true-image").removeClass("false-image").addClass("false-image").removeClass("hide");
}
}
break;
case "cell-clickable-dot2":
if ($(this).hasClass("cell-clickable-dot2")) {
right++;
$(this).find(".cell-clickable-button").removeClass("true-image").removeClass("false-image").addClass("true-image").removeClass("hide");
} else {
if ($(this).hasClass("cell-clickable-dot1")) {
$(this).find(".cell-clickable-button").removeClass("true-image").removeClass("false-image").addClass("false-image").removeClass("hide");
}
}
break;
}
if (total == right) {
$(".cell-clickable-dot1").css({
backgroundColor: "rgba(61, 203, 27,0.5)",
boxShadow: "0px 0px 0px 5px rgb(61, 203, 27)"
});
$(".cell-clickable").find(".cell-clickable-button").addClass("hide");
}
});
}
});
$(".menu-left-preview-box-preview").bind('click', function(e) {
window.location = "page" + ($(this).index() + 1) + ".html";
});
var native_width = 0;
var native_height = 0;
var magnifyIsMouseDown = false;
$(".magnify").parent().mousedown(function(e) {
magnifyIsMouseDown = true;
});
$(".magnify").on("mousemove touchmove",function(e) {
if (isDragging) {
if (!native_width && !native_height) {
var image_object = new Image();
image_object.src = $(".small").attr("src");
native_width = image_object.width;
native_height = image_object.height;
} else {
var magnify_offset = $(this).offset();
var mx = e.pageX - magnify_offset.left;
var my = e.pageY - magnify_offset.top;
if (e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel') {
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
mx = touch.pageX - magnify_offset.left;
my = touch.pageY - magnify_offset.top;
}
if ($(".large").is(":visible")) {
var rx = Math.round(mx / $(".small").width() * native_width - $(".large").width() / 2) * -1;
var ry = Math.round(my / $(".small").height() * native_height - $(".large").height() / 2) * -1;
var bgp = rx + "px " + ry + "px";
var px = mx - $(".large").width() / 2;
var py = my - $(".large").height() / 2;
$(".large").css({
left: px,
top: py,
backgroundPosition: bgp
});
}
}
}
});
var isDragging = false;
$(".magnify").parent().on("mouseup touchend", function(e) {
isDragging = false;
});
$(".magnify").parent().on("mousedown touchstart", function(e) {
console.log("mousedown");
// $(".large").fadeOut(100);
isDragging = true;
});
$(".large").fadeIn(100);
manageSlide();
}
function allElementsFromPoint(x, y) {
var element, elements = [];
var old_visibility = [];
while (true) {
element = document.elementFromPoint(x, y);
if (!element || element === document.documentElement) {
break;
}
elements.push(element);
old_visibility.push(element.style.visibility);
element.style.visibility = 'hidden';
}
for (var k = 0; k < elements.length; k++) {
elements[k].style.visibility = old_visibility[k];
}
elements.reverse();
return elements;
}
function manageSlide() {
$("#slide-number").text(currentSlide);
$(".slide").addClass("hide");
$(".slide").removeClass("hide");
$(".menu-left-preview-box-preview").removeClass("menu-left-preview-box-preview-active");
$(".menu-left-preview-box-preview").eq(currentSlide - 1).addClass("menu-left-preview-box-preview-active");
$(".slide-canvas-layer").addClass("hide");
$(".slide-canvas-layer-opacity").addClass("hide");
tool = null;
setTool();
initCanvas();
}
var zoomScale = 1;
function setTool(sender) {
$(".menu-left-tool-box-button").removeClass("tool-box-button-active");
switch (tool) {
case "pencil":
$(".slide-canvas-layer").removeClass("hide");
$(".slide-canvas-layer-opacity").removeClass("hide");
$(sender).addClass("tool-box-button-active");
var flag = false;
$(".menu-left-tool-box-button-child-pencil").each(function() {
if ($(this).hasClass("menu-left-tool-box-button-child-pencil-active")) {
flag = true;
}
});
if (!flag) {
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(".menu-left-tool-box-button-child-pencil").eq(0).addClass("menu-left-tool-box-button-child-pencil-active");
ctx.lineWidth = parseInt($(".menu-left-tool-box-button-child-pencil").eq(0).attr("value"));
ctx.strokeStyle = "#000";
ctx.globalAlpha = 1;
octx.lineWidth = parseInt($(".menu-left-tool-box-button-child-pencil").eq(0).attr("value"));
octx.strokeStyle = "#000";
octx.globalAlpha = 1;
}
break;
case "brush":
$(".slide-canvas-layer").removeClass("hide");
$(".slide-canvas-layer-opacity").removeClass("hide");
$(sender).addClass("tool-box-button-active");
var flag = false;
$(".menu-left-tool-box-button-child-brush").each(function() {
if ($(this).hasClass("menu-left-tool-box-button-child-brush-active")) {
flag = true;
}
});
if (!flag) {
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
$(".menu-left-tool-box-button-child-brush").eq(0).addClass("menu-left-tool-box-button-child-brush-active");
ctx.strokeStyle = $(".menu-left-tool-box-button-child-brush").eq(0).attr("value");
ctx.globalAlpha = 1;
ctx.lineWidth = 20;
octx.strokeStyle = $(".menu-left-tool-box-button-child-brush").eq(0).attr("value");
octx.globalAlpha = 1;
octx.lineWidth = 20;
}
break;
case "coversheet":
if ($(".slide").find(".coversheet").hasClass("hide")) {
$(".slide").find(".coversheet").removeClass("hide");
} else {
$(".slide").find(".coversheet").addClass("hide");
}
break;
case "back":
if (currentSlide > 1) {
currentSlide--;
window.location = "page" + currentSlide + ".html";
}
break;
case "next":
if (currentSlide < $(".menu-left-preview-box-preview").length) {
currentSlide++;
window.location = "page" + currentSlide + ".html";
}
break;
case "restart":
location.reload();
break;
case "zoom":
zoomScale += 0.10;
$("#slide-content").css({
transform: "scale(" + zoomScale + ")",
webkitTransform: "scale(" + zoomScale + ")",
mozTransform: "scale(" + zoomScale + ")"
});
$(".slide-canvas-layer").addClass("hide");
$(".slide-canvas-layer-opacity").addClass("hide");
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
tool = null;
break;
case "reduse":
if (zoomScale > .20) {
zoomScale -= 0.10;
}
$("#slide-content").css({
transform: "scale(" + zoomScale + ")",
webkitTransform: "scale(" + zoomScale + ")",
mozTransform: "scale(" + zoomScale + ")"
});
$(".slide-canvas-layer").addClass("hide");
$(".slide-canvas-layer-opacity").addClass("hide");
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
tool = null;
break;
default:
$(".slide-canvas-layer").addClass("hide");
$(".slide-canvas-layer-opacity").addClass("hide");
$(".menu-left-tool-box-button-child-pencil").removeClass("menu-left-tool-box-button-child-pencil-active");
$(".menu-left-tool-box-button-child-brush").removeClass("menu-left-tool-box-button-child-brush-active");
tool = null;
break;
}
}
var prevTool = null;
var tool = null;
var cumulativeOffset = function(element) {
var top = 0,
left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while (element);
return {
top: top,
left: left
};
};
var canvas = null,
ctx = null;
var ocanvas = null,
octx = null;
var firstTimeDocumentEvent = false;
var mouse = {
x: 0,
y: 0
};
var last_mouse = {
x: 0,
y: 0
};
function initCanvas() {
document.body.addEventListener('mousedown', onMouseDown, false);
document.body.addEventListener('mouseup', onMouseUp, false);
document.body.addEventListener('touchstart', onTouchStart, false);
document.body.addEventListener('touchend', onTouchEnd, false);
document.body.addEventListener('touchleave', onTouchEnd, false);
document.body.addEventListener('touchcancel', onTouchEnd, false);
canvas = document.querySelector('.slide-canvas-layer');
ctx = canvas.getContext('2d');
ocanvas = document.querySelector('.slide-canvas-layer-opacity');
octx = ocanvas.getContext('2d');
var sketch = document.querySelector('#slide-content');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width')) - 15;
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
ocanvas.width = parseInt(sketch_style.getPropertyValue('width')) - 15;
ocanvas.height = parseInt(sketch_style.getPropertyValue('height'));
$(canvas).css({
marginTop: (-1 * parseInt(sketch_style.getPropertyValue('height'))) + "px"
});
$(ocanvas).css({
marginTop: (-1 * parseInt(sketch_style.getPropertyValue('height'))) + "px"
});
canvas.addEventListener('mousemove', function(e) {
e.preventDefault();
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
var offSet = cumulativeOffset(this);
mouse.x = e.pageX - offSet.left;
mouse.y = e.pageY - offSet.top;
}, false);
ocanvas.addEventListener('mousemove', function(e) {
e.preventDefault();
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
var offSet = cumulativeOffset(this);
mouse.x = e.pageX - offSet.left;
mouse.y = e.pageY - offSet.top;
}, false);
canvas.addEventListener('touchmove', function(e) {
e.preventDefault();
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
var offSet = cumulativeOffset(this);
mouse.x = e.touches[0].pageX - offSet.left;
mouse.y = e.touches[0].pageY - offSet.top;
}, false);
ocanvas.addEventListener('touchmove', function(e) {
e.preventDefault();
last_mouse.x = mouse.x;
last_mouse.y = mouse.y;
var offSet = cumulativeOffset(this);
mouse.x = e.touches[0].pageX - offSet.left;
mouse.y = e.touches[0].pageY - offSet.top;
}, false);
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
octx.lineWidth = 3;
octx.lineJoin = 'round';
octx.lineCap = 'round';
}
var mouseDownOn = null;
var onPaint = function() {
if (tool == "pencil") {
ctx.beginPath();
ctx.moveTo(last_mouse.x, last_mouse.y);
ctx.lineTo(mouse.x, mouse.y);
ctx.closePath();
ctx.stroke();
} else if (tool == "brush") {
octx.beginPath();
octx.moveTo(last_mouse.x, last_mouse.y);
octx.lineTo(mouse.x, mouse.y);
octx.closePath();
octx.stroke();
}
};
.hide {
display: none!important;
}
body {
font-family: Verdana;
}
body > * {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#wrapper {
width: 1000px;
height: 550px;
background-color: #cecbcb;
margin: auto;
}
#menu-left {
height: 100%;
width: 100px;
float: left;
}
#menu-left-tool-box {
height: 60%;
width: 100%;
box-shadow: 0px 1px 0px 0px #b2b0b0;
text-align: center;
}
.menu-left-tool-box-button {
width: 35px;
height: 35px;
background-color: transparent;
margin: 4px;
padding: 0;
outline: none;
border-width: 1px;
background-position: center;
background-repeat: no-repeat;
}
.menu-left-tool-box-button:hover {
transform: scale(1.05);
-webkit-transform: scale(1.05);
-moz-transform: scale(1.05);
cursor: pointer;
}
.tool-box-button-active {
background-color: rgba(30, 182, 18, 0.3);
}
.menu-left-tool-box-button-child-pencil {
width: 10px;
height: 10px;
margin: 0.5px;
padding: 0;
border-width: 1px;
background-size: contain;
float: left;
}
.menu-left-tool-box-button-child-pencil-active {
box-shadow: 0px 0px 0px 1px #000;
}
.menu-left-tool-box-button-child-brush {
width: 10px;
height: 10px;
margin: 0.5px;
padding: 0;
border-width: 1px;
background-size: contain;
float: left;
}
.menu-left-tool-box-button-child-brush-active {
box-shadow: 0px 0px 0px 1px #000;
}
#menu-left-preview-box {
height: 40%;
width: 100%;
overflow-x: hidden;
text-align: center;
overflow-y: auto;
}
.menu-left-preview-box-preview {
width: 38px;
height: 31px;
background-color: transparent;
box-shadow: 0px 0px 1px 0px #b2b0b0;
border: none;
outline: none;
}
.menu-left-preview-box-preview-active {
box-shadow: 0px 0px 1px 1px #13bb0c;
}
#content {
height: 100%;
width: 850px;
background-color: #d4a1a5;
box-shadow: -1px 0px 0px 0px #b2b0b0;
overflow: auto;
float: left;
}
.slide {
height: 100%;
width: 100%;
background-color: #d4a1a5;
}
.slide-title {
height: 35px;
width: 820px;
padding: 15px;
}
.slide-title-content {
height: 35px;
background-color: red;
border-radius: 20px;
}
.slide-title-content-eye {
height: 25px;
width: 25px;
border-radius: 100px;
margin: 5px;
border-width: 1px;
outline: none;
background-position: center;
background-repeat: no-repeat;
float: left;
}
.slide-title-content-text {
height: 25px;
margin: 5px;
float: left;
color: white;
}
.slide-content {
height: 470px;
width: 100%;
overflow: auto;
}
.false-image {
background-image: url('./images/false.jpg');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.true-image {
background-image: url('./images/true.jpg');
background-size: contain;
background-repeat: no-repeat;
background-position: center;
}
.slide-canvas-layer {
position: fixed;
z-index: 999;
}
.slide-canvas-layer-opacity {
position: fixed;
z-index: 999;
opacity: 0.5;
}
.coversheet {
height: 100px;
width: 100px;
background-color: white;
position: absolute;
z-index: 1000;
}
.coversheet-plus-minus {
background-color: #000;
width: 71px;
height: 50px;
line-height: 50px;
/*position: absolute;*/
right: 0;
}
.coversheet-plus-minus-button {
background-color: transparent;
color: white;
border: none;
margin: 0;
font-size: 18px;
margin: 2px;
padding: 7px;
}
#menu-right {
height: 100%;
width: 50px;
box-shadow: -1px 0px 0px 0px #b2b0b0;
float: right;
}
.menu-right-button {
height: 30px;
width: 30px;
border-radius: 100px;
margin: 10px;
border-width: 1px;
outline: none;
background-position: center;
background-repeat: no-repeat;
background-color: transparent;
}
#menu-right-image {
height: 160px;
width: 100%;
position: relative;
top: 240px;
}
/**********OVERRIDE CSS*/
.ui-state-hover,
.ui-state-active {
background-color: rgba(57, 187, 31, 0.5);
border: none;
}
/***********/
#slide-content {
height: 100%;
width: 100%;
transform-origin: left top;
-webkit-transform-origin: left top;
-moz-transform-origin: left top;
}
.magnify {
position: relative;
background-color: #d4a1a5;
height: 100%;
margin: auto;
}
.large {
width: 133px;
height: 133px;
position: absolute;
border-radius: 100%;
box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25);
background: url('https://lh3.googleusercontent.com/t789bbPUzJzrVs6cDPZNtiDxX9NCEWggBIW1IDCbeJllWjMOXy5ILBBFCYu9UjKJLsmCyubMREZjTZnelGwMyup8nVLP-VeMUg8oF0mCXN7gkcOweuJYVYTuj3Cx4rhuoOy8jvM-v83vrmT0-bn1tJx2YdLraQ9p7X82jL8rz9iLSNUgVv36Lxs9rfKpBGTyM7_8rzBsZonWXmcMTgInDdhL5mWx-J97bPOyJ9XA1bltKNRposrL69pdQW1WOAUWKj-uTT5K5z6GjaLeT-vN7gJSCb0NFUauszdao_Z5GFSyKOHWWjChXY3Q5CKBtg7Ir-uXoi4UFArTlHNPvuXCnJQptWv-L0TtZ2RrKpMgjimPoBKsGFjUxzYcY95kfZjGlm5-7V5Uut_Nw58Rk0bCz1EWUrW8nzDfawdilyJkDMn3dIhqlzJ8NGGZ5-2hwJTUOIyfrIQat7273nAPCkid6553CiLF57RGptiCxonWn5CZbpU4O7E8nudVMLPiYNY-nuupA-GOhh8-v6heBza6ijkGIpyyTFLieNBO9IjFTw=s220-no') no-repeat;
background-color: #d4a1a5;
display: none;
margin: auto;
}
/*To solve overlap bug at the edges during magnification*/
.small {
display: block;
width: 100%;
}
.large-image {
background: url('https://photos-1.dropbox.com/t/2/AAAnwmx1QvCzmWFYW5i8a3u_gOPGCt19gs_lBJOqwCS93A/12/134709958/png/32x32/1/_/1/2/icon_magnify_glass.png/EK_Up2cYgQQgBygH/R1kBQnLrN-RrPOYcREvqvMMrOMI-rfEOs5ZVgV-3Ayo?size=1024x768&size_mode=2') no-repeat;
height: 112%;
width: 114%;
position: absolute;
top: 73%;
left: 70%;
}
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
<div class="slide-content">
<div id="slide-content">
<div class="magnify" style="width: 266px;">
<div class="large" style="display: none; left: 195.615px; top: 79.0139px; background-position: -150px -54px;">
<div class="large-image"></div>
</div>
<img class="small" src="https://lh3.googleusercontent.com/gzHg89Pc4MtSrIeH__viNCTdBDDemmYf5VDG7vnZzRiaqWBKOKEzHH0PtlpLu8vyA27dg0q7-pmxAggQEF3p5JsDCPWjbux1uQJGLDNTSLsB7MVJG_cBWDDZqkdcshbeCfXCC4UCQMe1ogugc1R8zduLOfeONFnbhGObEFmBzBF60E6ff8lN8BBoZSxPGW_p3LvTdC4k49ULEVZR9QlJDo_JuMUIM-kSBtrN6WEtQ0RRJPUnqIrwmWj3ec_37hdSSzdPHmYLaNPTbJ1wF3dY8wYn5sJG6tdxk7qp-gI-q7xcFEK2huR6YwJtKTpx5U6mn2tr8Vs00vuvHf1fzi-_40ZWA3XNKWh8syUbTs-WYob7Xb4mSKCr5P4QTfUtHFwHuREv45j24LRdSe5_8B_YWCnIB6wG5x4PbNUEn70OlYSvVgS_rYEkeVqMcY0hQCJuIivfkBacTYFrTF61obq1ixtYSmkyhp8CV3atCsHFm2JwKIlJBZ5fwwnZICfKDITDt1qYsb64TrhNL7Wg7BHSazQ6Tkr3exVtQZ6yp57PsQ=s220-no">
</div>
</div>
<canvas class="slide-canvas-layer-opacity hide" width="835" height="470" style="margin-top: -470px;"></canvas>
<canvas class="slide-canvas-layer hide" width="835" height="470" style="margin-top: -470px;"></canvas>
</div>
I have a slider with a pop-up that shows the current value of the slider.
but I want it only appears if I click on the slider and disappears when I do not click
is there a way to do it?
Below is my css js and html code
html:
<input type="range" id="myrange" name="myrange" class="zoom-range" min="0.25" max="2.00" step="0.01"/>
<output id="rangeHover" for="myrange" onmouseover="value = myrange.valueAsNumber;"></output>
js:
function modifyOffset() {
var el, newPoint, newPlace, offset, siblings, k;
width = this.offsetWidth;
newPoint = (this.value - this.getAttribute("min")) / (this.getAttribute("max") - this.getAttribute("min"));
offset = -1;
if (newPoint < 0) { newPlace = 0; }
else if (newPoint > 1) { newPlace = width; }
else { newPlace = width * newPoint + offset; offset -= newPoint;}
siblings = this.parentNode.childNodes;
for (var i = 0; i < siblings.length; i++) {
sibling = siblings[i];
if (sibling.id == this.id) { k = true; }
if ((k == true) && (sibling.nodeName == "OUTPUT")) {
outputTag = sibling;
}
}
outputTag.style.left = newPlace + "px";
outputTag.style.marginLeft = offset + "%";
outputTag.innerHTML = this.value;
}
function modifyInputs() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].getAttribute("type") == "range") {
inputs[i].onchange = modifyOffset;
// the following taken from http://stackoverflow.com/questions/2856513/trigger-onchange-event-manually
if ("fireEvent" in inputs[i]) {
inputs[i].fireEvent("onchange");
} else {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
inputs[i].dispatchEvent(evt);
}
}
}
}
window.onload = modifyInputs;
css:
output {
position: absolute;
background-image: linear-gradient(#FAFAD2, #FAFAD2);
width: 30px;
height: 15px;
text-align: center;
color: black;
border-radius: 5px;
display: block;
bottom: 120%;
margin-top:5000px;
font-size:11px;
left: 100%;
}
output:after {
content: "";
position: absolute;
width: 0px;
height: 0px;
border-top: 10px solid #FAFAD2;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
top: 100%;
left: 100%;
margin-left: -26px;
margin-top: -1px;
}
#rangeHover{
display: block;
position: relative;
margin: -50px;
padding-right:10px;
padding-left:10px;
}
Thanks for help!
you could add to css:
output
{
display:none
}
input:hover + output
{
display:block;
}
UPDATE
tooltip visible on click:
input:active+ output
{
display:block;
}