Call functions instead of reloading page - javascript

Basically I have this function that picks two different random images from a folder. At the moment I'm using onClick="window.location.reload() to run the function everytime you click.
Is there anyway I can call the funcion onClick without refreshing the page?
Thanks in advance.
body {
border: 0;
color: #000;
background: #fff;
margin: 0;
padding: 0;
font: 2.1vw/1.2em HelveticaNeue, Arial, sans-serif;
letter-spacing: .02em
}
.logo {
cursor: pointer;
position: fixed;
top: 0;
left: 0;
width: 100vw;
text-align: center;
z-index: 100
}
#one,
#two {
position: fixed;
width: 50vw;
top: 0;
display: table
}
#one {
left: 0;
text-align: right
}
#two {
right: 0;
text-align: left
}
.inner {
display: table-cell;
vertical-align: middle;
height: 100vh;
width: 100vw
}
<script>
var IMG = new Array()
IMG[0] = 'https://cdn.shopify.com/s/files/1/0224/5205/products/Siser_EasyWeed_Bright_Red_2048x.jpg?v=1523704262'
IMG[1] = 'http://thezilla.com/wp-content/uploads/2015/07/blue.png'
IMG[2] = 'http://d18nh7ureywlth.cloudfront.net/wp-content/uploads/6901-vibrant-green.jpg'
var j = 0
var p = IMG.length;
var preBuffer = new Array()
for (i = 0; i < p; i++) {
preBuffer[i] = new Image()
preBuffer[i].src = IMG[i]
}
var WI1 = Math.floor(Math.random() * p);
var WI2 = Math.floor(Math.random() * (p - 1));
if (WI2 >= WI1) {
WI2 += 1;
}
function showImage1() {
document.write('<img src="' + IMG[WI1] + '">');
}
function showImage2() {
document.write('<img src="' + IMG[WI2] + '">');
}
</script>
<div class=logo onClick="window.location.reload()"><span class=inner>( RANDOM DYPTICHS )</span></div>
<div id=one><span class=inner><script>showImage1();</script></span></div>
<div id=two><span class=inner><script>showImage2();</script></span></div>

Ideally, there is no need to use ajax either.
I simply used an addEventListener('click'...) and encapsulated your code.
Click on the screen and the images will change randomly.
To Note: Take into a habit of adding (;) where is needed, Javascript is not strict (unless using "use strict") on colons but it can cause a lot of bugs in the future. Also, use commas (' or ") in your attributes in HTML.
Read Javascript Style Guide written by W3 Schools, they do a
good job explaining to newbies about famous javascript conventions
around the globe.
var IMG = new Array(
'https://i.picsum.photos/id/562/200/200.jpg?hmac=F4ylYRNFPH6rDzYo48_NUieJXXI2yaMl9ElwGeFQHZo',
'https://i.picsum.photos/id/650/200/200.jpg?hmac=gu3C13pBxCSHokbnumczMYlmWRLt3CFGx1sDaPpfRnk',
'https://i.picsum.photos/id/67/200/200.jpg?hmac=sN5XCCMqqmBvgDbYmAowWy2VToCkSYP5igDL_iRxK3M');
function getRandomImagePair() {
var j = 0;
var p = IMG.length;
var preBuffer = new Array();
for (i = 0; i < p; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = IMG[i];
}
WI1 = Math.floor(Math.random() * p);
WI2 = Math.floor(Math.random() * (p - 1));
if (WI2 >= WI1) {
WI2 += 1;
}
document.querySelector('#imgOne').src = IMG[WI1];
document.querySelector('#imgTwo').src = IMG[WI2];
}
getRandomImagePair();
document.querySelector('.logo .inner').addEventListener('click', e => {
getRandomImagePair();
});
body {
border: 0;
color: #000;
background: #fff;
margin: 0;
padding: 0;
font: 2.1vw/1.2em HelveticaNeue, Arial, sans-serif;
letter-spacing: .02em
}
.logo {
cursor: pointer;
position: fixed;
top: 0;
left: 0;
width: 100vw;
text-align: center;
z-index: 100;
}
#one,
#two {
position: fixed;
width: 50vw;
top: 0;
display: table
}
#one {
left: 0;
text-align: right
}
#two {
right: 0;
text-align: left
}
.inner {
display: table-cell;
vertical-align: middle;
height: 100vh;
width: 100vw
}
<div class='logo'><span class='inner'>( RANDOM DYPTICHS )</span></div>
<div id='one'><span class='inner'><img id="imgOne" src="#" /></span></div>
<div id='two'><span class='inner'><img id="imgTwo" src="#" /></span></div>

Related

Array in JavaScript is undefined

I am very new to JavaScript but have good experience with C and java. For whatever reason my code below will not fill in the array with values other than undefined. I'm trying to simply fill an array with a random set of numbers for a blackjack game
let randomSuite;
let randomNum
let count = 0;
var cards = new Array(56);
window.onload = function main(){
const suites = [
"H",
"D",
"S",
"C"
];
for(let i = 0 ; i < 56 ; i++){
randomNum = (Math.random * 12) + 1;
randomSuite = Math.random * 3;
cards.push = randomNum;
console.log(cards[i]);
count++;
}
alert(cards[1]);
}
function hitFunc(){
alert("works " + cards[0]);
}
*{
margin: 0;
padding : 0;
font-family: sans-serif;
}
.main{
width: 100%;
height: 100vh;
background-color:black;
}
.img1{
position: relative;
z-index: -1;
margin: 10px auto 20px;
display: block;
width: 75%;
height: 75%;
}
.img2{
position: relative;
z-index: 1;
margin: 10px auto 20px;
display: block;
bottom: 200px;
right: 400px;
width: 7%;
height: 7%;
}
.hitButton {
z-index: 1;
position: relative;
text-align: center;
left: 225px;
bottom: 550px;
}
.center {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
color: aliceblue;
object-position: center;
}
Here's what I have. The alerts are used to show that the function is being completed. Any help is appreciated Please leave an explanation as well. This is my first post on stack overflow let me know if there's anyway to improve the quality of my post.
Math.random is a function; use Math.random()
Same for push, use cards.push(randomNum)
You were defining an array with 56 spots new array(56) but since you're using push you'll need to create an empty array so you're pussing to the desired index. Otherwise, instead of push, just set it on the index: cards[i] = randomNum
No need for the count variable since the loop iterator (i) has the same value
let randomSuite;
let randomNum
var cards = new Array();
window.onload = function main(){
const suites = [
"H",
"D",
"S",
"C"
];
for(let i = 0 ; i < 56 ; i++){
randomNum = (Math.random() * 12) + 1;
randomSuite = Math.random() * 3;
cards.push(randomNum);
}
console.log(cards)
}
*{
margin: 0;
padding : 0;
font-family: sans-serif;
}
.main{
width: 100%;
height: 100vh;
background-color:black;
}
.img1{
position: relative;
z-index: -1;
margin: 10px auto 20px;
display: block;
width: 75%;
height: 75%;
}
.img2{
position: relative;
z-index: 1;
margin: 10px auto 20px;
display: block;
bottom: 200px;
right: 400px;
width: 7%;
height: 7%;
}
.hitButton {
z-index: 1;
position: relative;
text-align: center;
left: 225px;
bottom: 550px;
}
.center {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
color: aliceblue;
object-position: center;
}
Call functions with parenthesis
Math.random() and push() are functions not variables therefore you need to call them using ().
push() will append to the array
push() will append a value to the array. You already initialize an array with 10 values. Pushing new values will increase the array size but not add values in the first 10 spots.
const array = new Array(10);
for(let i = 0; i < 10; i++){
array.push(i);
}
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Solution
You should instead use array[i] = value; to set a value on a given position.
const array = new Array(10);
for(let i = 0; i < 10; i++){
array[i] = i;
}
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you want to have a more functional way of doing this as is typical for JavaScript you could use map():
const array = [...new Array(10)].map((_, index) => index);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Can I undo or delete some javascript code after running it

I am 3th year at college and for web design class we are manually drawing canvas elements. Which is very boring for me so I tried to make some 2D paint where I can do it by mouse where on the other end it writes code by itself.
I managed to do this much even tho is not "much" but now I am wondering is there a way to undo some script to remove it from the code? One way would be to append new canvas and do moves by one less but is there something to delete existing ones but not to recreate new ones over and over again?
In this example down below (try by full screen), when I add new lines I add new moves to the array and when I finish at the starting point I can draw new element. But every time I add new line I re create or draw lines over existing ones and new lines so it shows as one element where I could fill style and so on.
By doing that you will see that the adding lines over existing ones create a little darker bolder line, and because of that I would like to know if there is some way to delete or undo those lines and add whole new ones without puting em over existing ones.
$(document).ready(function(){
var mainCanvas = $('#mainCanvas')[0].getContext('2d');
var coordsCanvas = $('#coordsCanvas')[0].getContext('2d');
var moves = [];
$('#newCoords').click(function(){
var mainCanvasWidth = $('#mainCanvas').width();
$(this).parent().prepend('<input class="input-class" id="x-n0" placeholder="X number of blocks"><input class="input-class" id="y-n0" placeholder="Y number of blocks"> <span class="notes">Note: canvas full width is: '+Math.floor(mainCanvasWidth)+'px. </span><button id="saveCoords">Save</button>')
$(this).remove();
});
$(document).on('click','#saveCoords',function(){
var x = $(this).siblings('input#x-n0').val(),
y = $(this).siblings('input#y-n0').val(),
mainCanvasWidth = $('#mainCanvas').width(),
mainCanvasHeight = $('#mainCanvas').height(),
xWidthPx = Math.floor(mainCanvasWidth/x),
yHeightPx = Math.floor(mainCanvasHeight/y);
$('#coordsCanvas, #mainCanvas').attr('width', Math.floor(xWidthPx*x));
$('#coordsCanvas, #mainCanvas').attr('height', Math.floor(yHeightPx*y));
var marginLeftRight = 'calc(50% - '+Math.floor(xWidthPx*x)/2+'px)';
$('#coordsCanvas, #mainCanvas').css({'width':Math.floor(xWidthPx*x)+'px','height':Math.floor(yHeightPx*y)+'px','left': marginLeftRight, 'top':'10vh'});
for(var i=0; i<x-1; i++){
coordsCanvas.beginPath();
coordsCanvas.moveTo(Math.floor(xWidthPx+(xWidthPx*i)), 0);
coordsCanvas.lineTo(Math.floor(xWidthPx+(xWidthPx*i)), Math.floor(yHeightPx*y));
coordsCanvas.stroke();
coordsCanvas.closePath();
}
for(var i=0; i<y-1; i++){
coordsCanvas.beginPath();
coordsCanvas.moveTo(0 ,Math.floor(yHeightPx+(yHeightPx*i))+1);
coordsCanvas.lineTo(Math.floor(xWidthPx*x), Math.floor(yHeightPx+(yHeightPx*i))+1);
coordsCanvas.stroke();
coordsCanvas.closePath();
}
$(this).parent().html('<label for="#mouse-position"><input type="checkbox" id="mouse-position">Show mouse position</label><span class="notes">X = '+Math.floor(xWidthPx)+'px; Y = '+Math.floor(yHeightPx)+'px;</span><div class="tools"><button id="line">Lines</button></div>');
});
$(document).on( "change", "#mouse-position", function() {
if($('input[id="mouse-position"]:checked').length === 1){
$('#mouse-coords').css('display','block');
}else{
$('#mouse-coords').css('display','none');
}
});
$(document).on( "click", "#line", function() {
$(this).css('background','silver');
$('#mainCanvas').css({'cursor':'url(./pen.png) 0 24, auto'});
});
$(document).on( "click", "#mainCanvas", function(e) {
var cursor = $('#mainCanvas').css('cursor');
var strokeStyle = $('#strokestyle').val();
if(~cursor.indexOf('pen.png')){
var posX = $(this).position().left,
posY = $(this).position().top;
if(moves[0]==='beginPath'){
if(Object.keys(moves[1])[0]==='moveTo'){
var len = moves.length-1,
nowpos = Math.floor((e.pageX - posX)) + ',' + Math.floor((e.pageY - posY)),
renderDrawing = [];
renderDrawing.push({'func': 'beginPath', init: function(){ mainCanvas.beginPath(); }});
if(moves[len]!=="stroke" || moves[len]!=="closePath"){
for(var ee=1; ee<moves.length; ee++){
if(Object.keys(moves[ee])[0]==="moveTo"){
var mtp = moves[ee]['moveTo'],
pos = mtp.split(',');
renderDrawing.push({func: 'moveTo', val: pos, init: function(){
mainCanvas.moveTo(this.val[0], this.val[1]);
}});
}else if(Object.keys(moves[ee])[0]==="lineTo"){
var mtp = moves[ee]['lineTo'],
pos = mtp.split(',');
renderDrawing.push({func: 'lineTo', val: pos, init: function(){
mainCanvas.lineTo(this.val[0], this.val[1]);
}});
}
}
var nowX = Math.floor((e.pageX - posX));
var nowY = Math.floor((e.pageY - posY));
var nowXY = nowX + ',' + nowY;
moves.push({'lineTo':nowXY});
renderDrawing.push(
{func: 'lineTo', val: nowXY, init: function(){
mainCanvas.lineTo(this.val.split(',')[0], this.val.split(',')[1]);
}},
{func: 'stroke', init: function(){ mainCanvas.stroke(); }},
{func: 'closePath', init: function(){ mainCanvas.closePath(); }});
for(var q=0; q<renderDrawing.length; q++){
if(renderDrawing[q]['func']!=="beginPath" && renderDrawing[q]['func']!=="closePath" && renderDrawing[q]['func']!=="stroke"){
renderDrawing[q].init();
}else renderDrawing[q].init();
}
console.log(moves);
if(Object.keys(moves[len])[0]==="lineTo" && nowpos===moves[1]['moveTo']){
moves = [];
}
}
}
}else{
mainCanvas.beginPath();
mainCanvas.moveTo(Math.floor(e.pageX - posX) , Math.floor(e.pageY - posY));
moves.push('beginPath',{'moveTo':Math.floor((e.pageX - posX)) + ',' + Math.floor((e.pageY - posY))});
console.log(moves);
}
}
});
$(document).on('mousemove', "#mainCanvas", function(e){
var parentOffset = $('#mainCanvas').offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
$('#mouse-coords').css({
left: e.pageX + 20,
top: e.pageY
}).text( "X: " + Math.floor(relX) + ", Y: " + Math.floor(relY) );
});
});
* {
margin: 0;
padding: 0;
list-style: none;
text-decoration: none;
box-sizing: border-box;
}
body {
overflow: hidden;
font-size: 100%;
}
.container {
width: 100vw;
height: 100vh;
padding-right: 5vw;
padding-left: 5vw;
padding-top: 10vh;
padding-bottom: 5vh;
overflow: hidden;
position: relative;
}
canvas {
width: 90vw;
height: 85vh;
border: 1px solid #000;
float: left;
}
.toolsBar {
width: calc(100% - 10vw);
position: absolute;
top: 5px;
left: 5vw;
border: 1px solid #000;
height: calc(10vh - 10px);
overflow: hidden;
overflow-y: auto;
}
button {
color: #fff;
background: skyblue;
border: 0;
border-radius: 5px;
margin: 5px;
padding: 15px;
cursor: pointer;
float: left;
}
.input-class {
border-radius: 5px;
margin: 5px;
padding: 15px;
float: left;
border: 1px solid #e0e0e0;
outline: none;
}
.notes {
display: inline-block;
height: 60px;
text-align: center;
float: left;
color: red;
line-height: 60px;
}
#mouse-coords {
position: absolute;
display: none;
background: #000;
padding: 2px;
color: #fff;
}
label[for="#mouse-position"] {
display: inline-block;
height: 60px;
text-align: center;
line-height: 60px;
font-size: 1.2rem;
float: left;
padding: 5px;
}
label>input {
height: 1.2rem;
width: 1.2rem;
}
.coordsCanvas {
position: absolute;
z-index: 100;
}
#mainCanvas {
background: rgba(255,255,255,.5);
position: absolute;
z-index: 200;
}
.tools {
width: auto;
overflow: hidden;
overflow-y: auto;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="toolsBar">
<button id="newCoords">X & Y</button>
</div>
<div id="mouse-coords"></div>
<canvas class="coordsCanvas" id="coordsCanvas"></canvas>
<canvas id="mainCanvas"></canvas>
</div>

How to create grid and place elements randomly inside column?

I have a responsive grid that is created with js and css. Inside each column in the grid I want to place elements (the red squares), but the squares should be placed randomly and only inside some of the columns. There is 50 columns, so let's say I want to place 20 squares randomly inside columns so that the squares can't overlap. How do I achieve this in the best way?
js
var grid = document.getElementById("grid");
for(var i = 0; i < 50; i++) {
var square = document.createElement("div");
square.className = 'square';
grid.appendChild(square);
var child = document.createElement("div");
child.className = 'child';
square.appendChild(child);
}
fiddle
First add an ID to each square, then the idea is to generate a random number between 0 and 49 to be able to access those squares. Each time you add a square, you have to store its index to check whether it has already been added. Only stop until 20 squares is added.
var field = document.getElementById("field");
for (var i = 0; i < 50; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
field.appendChild(square);
}
var squaresPlaced = []; // Stores the squares index placed
while (squaresPlaced.length < 20) { // Stop only if 20 squares is added
var randomIndex = parseInt(49 * Math.random()); // Generate a random number between 0 and 49
// Only add the square if it doesn't exist already
if (squaresPlaced.indexOf(randomIndex) === -1) {
squaresPlaced.push(randomIndex);
document.getElementById('square' + randomIndex).style.borderColor = 'red';
}
}
html,
body {
margin: 0;
height: 100%;
}
#field {
width: 60vw;
height: 60vw;
margin: 0 auto;
font-size: 0;
position: relative;
}
#field>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
#field>div.circle {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #f00;
border-radius: 100px;
}
<div id="field"></div>
ANSWER UPDATE
is it possible to prevent a circle to appear next to another?
Yes, it's enough to change how to generate random numbers. Change this line:
if(arr.indexOf(randomnumber) > -1) continue;
to:
if(arr.indexOf(randomnumber) > -1 || arr.indexOf(randomnumber + 1) > -1
|| arr.indexOf(randomnumber - 1) > -1) continue;
Also if I want to add more shapes, can I just create and append another shape and then clone that in the foreach?
Yes. I added an oval figure.
My proposal is:
generate 20 random different numbers
clone and move the circle adjusting the size
hide all generated circles:
var field = document.getElementById("field");
for (var i = 0; i < 50; i++) {
var square = document.createElement("div");
square.className = 'square';
field.appendChild(square);
}
for (var i = 0; i < 50; i++) {
var circle = document.createElement("div");
circle.className = (Math.random() >= 0.5) ? 'circle' : 'oval';
field.appendChild(circle);
}
var arr = [];
while (arr.length < 20) {
var randomnumber = Math.ceil(Math.random() * 50) - 1;
if (arr.indexOf(randomnumber) > -1 || arr.indexOf(randomnumber + 1) > -1
|| arr.indexOf(randomnumber - 1) > -1) continue;
arr[arr.length] = randomnumber;
}
arr.forEach(function (rnd, idx) {
$('#field > .circle, #field > .removed, #field > .oval, #field > .ovalremoved').eq(rnd)
.css({border: '1px solid #0000cc'}).clone()
.css({width: '100%', height: '100%'})
.appendTo($('.square').eq(rnd));
})
html, body {
margin: 0;
height: 100%;
}
#field {
width: 60vw;
height: 60vw;
margin: 0 auto;
font-size: 0;
position: relative;
}
#field > div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
div.circle {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #f00;
border-radius: 100px;
}
div.oval {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #f00;
border-radius: 100px / 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="field"></div>

How to save innerHTML of div in a local storage?

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>

JS slider tooltip

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;
}

Categories

Resources