How can I let the user choose a background color using hex and css gradients - javascript

I would like to make it so that the user can input a hex into one text box and another hex into a different text box. This would then use linear-gradient so that it would gradient the first color to the second color. In the code snippet is an example of what it may produce. I would prefer to only use css and html but can use javascript if neccessary. Thanks to anyone who attempts to solve this problem any bit. I will respond to any questions in case I am being vague.
body {
background: linear-gradient(to right, #ffb6ce, #ff00ea);
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>

I created an example.
const body = document.querySelector("body");
const startInput = document.querySelector("#start");
const endInput = document.querySelector("#end");
let startHex = "#fff";
let endHex = "#fff";
let gradient;
function styleBody(){
gradient = `linear-gradient(to right, ${startHex}, ${endHex})`;
body.style.background = gradient;
}
startInput.addEventListener("input", () => {
startHex = event.target.value;
styleBody();
});
endInput.addEventListener("input", () => {
endHex = event.target.value;
styleBody();
});
<input type="color" id="start">
<input type="color" id="end">

const colorPicker1 = document.querySelector("#picker1");
const colorPicker2 = document.querySelector("#picker2");
var firstColor = '#0F0';
var secondColor = '#F00'
document.body.addEventListener("input", gradientPick);
function gradientPick(event) {
if(event.target === colorPicker1){
firstColor = event.target.value;
}
if(event.target === colorPicker2){
secondColor = event.target.value;
}
document.body.style.background = `linear-gradient(${firstColor}, ${secondColor})`;
document.body.style.backgroundSize = "contain";
document.body.style.height = "100vh";
}
<input id="picker1" type="color" value="#ff0000">
<input id="picker2" type="color" value="#00ff00">

Related

i cant get the clicked elements child and change the div's background to that image

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF[![enter image description here][1]][1]-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Cubix Worlds Planner</title>
</head>
<body>
<div class="navbar">
<button class="btn">Reset</button>
</div>
<div class="blocks">
<button class="block"><img src="assets/blocks/items3.png"></button>
<button class="block"><img src="assets/blocks/items4.png"></button>
<button class="block"><img src="assets/blocks/items5.png"></button>
<button class="block"><img src="assets/blocks/items6.png"></button>
<button class="block"><img src="assets/blocks/items8.png"></button>
<button class="block"><img src="assets/blocks/items10.png"></button>
</div>
<div class="container">
</div>
<script src="main.js"></script>
</body>
</html>
main.js
const container = document.querySelector('.container');
const resetBtn = document.querySelector('.btn');
const { body } = document;
const blocklist = document.querySelector('.blocks');
const block = document.querySelector('.block');
let draw = false;
let blockimg = '';
function populate(size) {
document.querySelector('.block').addEventListener('click', e=>{
if (e.target.classList.contains('img')) {
blockimg = e.target.querySelector('img').getAttribute('src');
}
});
container.style.setProperty('--size', size);
for (let i = 0; i < size * size; i++) {
const div = document.createElement('div');
div.classList.add('pixel');
div.addEventListener('mouseover', function(){
if(!draw) return;
div.style.backgroundColor = blockimg;
});
div.addEventListener('mousedown', function(){
div.style.backgroundColor = blockimg;
});
container.appendChild(div);
}
}
window.addEventListener("mousedown", function(){
draw = true;
});
window.addEventListener("mouseup", function(){
draw = false;
});
function reset() {
container.innerHTML = '';
populate(100);
}
resetBtn.addEventListener('click', reset);
populate(100);
let zoomActivate = false;
window.addEventListener('keydown', (e) => {
if(e.key === 'z') {
zoomActivate = !zoomActivate;
}
});
window.addEventListener("mousemove", (e) => {
const { clientX: x, clientY: y } = e;
if(zoomActivate) {
body.style.transform = 'scale(2)';
body.style.transformOrigin = `${x}px ${y}px`;
} else {
body.style.transform = 'none';
}
});
Over the past few days, I have been attempting to create a website for pixel art. However, instead of using colors, I have opted to use blocks that can be placed on a canvas. Unfortunately, I have encountered an issue with the code I have written, as it does not allow me to select the specific block that I wish to place on the canvas. As a result, I am unable to properly generate the desired pixel art.
website preview
https://i.stack.imgur.com/ydp8M.png

How to make canvas lines visible when dragging (no libraries, only vanilla JS, React.JS if necessary.)

I'd like to add lines by two clicks, when moving the mouse the line should be visible. When click left mouse button again the line should be added. Only left button should draw.
How should I change my code to do this? (for now it allows to create lines,
but they aren't visible before mouseup).
Any help is appreciated! Thanks!
const canvasEl = document.getElementById('drawContainer')
canvasEl.style.position = 'absolute'
canvasEl.style.top = '12%'
canvasEl.style.left = '32%'
var lines = [], line;
const context = canvasEl.getContext('2d')
const collapseLinesBtn = document.getElementById('collapse_lines')
let startPosition = {x: 0, y: 0}
let lineCoordinates = {x: 0, y: 0}
let isDrawStart = false
const getClientOffset = (event) => {
const {pageX, pageY} = event.clicks ? event.clicks[0] : event
const x = pageX - canvasEl.offsetLeft
const y = pageY - canvasEl.offsetTop
return { x, y }
}
const initialDraw = () => {
context.beginPath() //allows to prevent previously created lines from delete
context.moveTo(startPosition.x, startPosition.y)
context.lineTo(lineCoordinates.x, lineCoordinates.y)
context.stroke()
line = [];
line.push([lineCoordinates.x, lineCoordinates.y]);
console.log(line)
}
const mouseDownListener = (e) => {
startPosition = getClientOffset(e)
//isDrawStart = true // isDrawStart = true + clearCanvas() + initialDraw() from const mouseMoveListener = one visible line when dragging + coordinates
context.beginPath();
context.moveTo(e.offsetX, e.offsetY);
context.lineTo(e.offsetX, e.offsetY);
}
const mouseMoveListener = (event) => {
if(!isDrawStart)
return
lineCoordinates = getClientOffset(event)
//clearCanvas()
//initialDraw()
//initialDraw(!isDrawStart())
}
const mouseUpListener = (e) => {
isDrawStart = false
context.lineTo(e.offsetX, e.offsetY);
context.stroke();
}
const clearCanvas = () => {
context.clearRect(0, 0, canvasEl.width, canvasEl.height)
}
canvasEl.addEventListener('mousedown', mouseDownListener)
canvasEl.addEventListener('mousemove', mouseMoveListener)
canvasEl.addEventListener('mouseup', mouseUpListener)
collapseLinesBtn.addEventListener('click', function clear() {
context.clearRect(0, 0, window.innerWidth, window.innerHeight);
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#collapse_lines {
position: absolute;
bottom: 75px;
left: 47%;
padding: 10px 25px;
font-size: 1rem;
}
</style>
<title>Test Task</title>
</head>
<body>
<div id="main_container">
<canvas id="drawContainer" width="700" height="700" style="border: 1px solid rgb(10, 10, 10)" ></canvas>
<button id="collapse_lines">collapse lines</button>
</div>
<script src="./app.js"></script>
</body>
</html>
In your mouseMoveListener just do something similar as you do in your mouseUpListener, without setting isDrawStart = false:
const mouseMoveListener = (event) => {
if(!isDrawStart)
return
lineCoordinates = getClientOffset(event)
// Clear the canvas each frame
clearCanvas()
// Similar to mouseUpListener
context.lineTo(lineCoordinates.x, lineCoordinates.y);
context.stroke();
}

Got a persistent change font size slider in Jquery but need help to turn into Vanilla js

Now I have this Jquery font rezising slider but need it in vanilla.js. It is working properly but I can not manage turning it into plain Javascript.
My code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="app.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="font-slider">
<input type="range" min="17" max="28" value="22" step="1" />
</div>
<div>
<h1>Changing Font Size</h2>
<p>I am just a boring text, existing here solely for the purpose of this demo</p>
<p>And I am just another one like the one above me, because two is better than having only one</p>
I am a link, don't click me!
</div>
<script>
var curSize = localStorage.getItem("saveSize");
if (curSize) {
var saveSize = curSize;
$('body').css('font-size', saveSize + 'px');
var setSize = $('body').css('font-size');
}
$('.font-slider input[type="range"]').on("input change", function () {
var newSize = $(this).val(),
defaultSize = $("body").css("font-size"),
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
$("body").css("font-size", newSize + "px");
localStorage.setItem("saveSize", newSize);
}
});
</script>
</body>
</html>
Try:
var curSize = localStorage.getItem("saveSize");
var slider = document.querySelector('.font-slider input[type="range"]')
var body = document.body
if (curSize) {
var saveSize = curSize;
body.style.fontSize = saveSize + 'px';
}
slider.addEventListener("input", function (e) {
var newSize = this.value,
defaultSize = body.style.getPropertyValue('font-size'),
minSize = 17,
maxSize = 28;
if (newSize <= maxSize && newSize >= minSize) {
body.style.fontSize = newSize + 'px';
localStorage.setItem("saveSize", newSize);
}
});

dynamically added div not appearing

I'm trying dynamically add a div to a page. This is in Chrome. I've looked at several instructions pages. Seems like this should work, but no joy. I added style attributes that would make it obviously apparent, just to get started. The code is executed, per "Inspect", but no element is appearing. Also the element does not show up in "Inspect/Elements/Find".
function CreateDragClone(partType) {
var cloneContainer = document.createElement("div");
cloneContainer.setAttribute("id", "cloneDiv");
//cloneContainer.setAttribute("class", "closeContainer");
cloneContainer.style.visibility = "visible";
cloneContainer.style.position = "absolute";
cloneContainer.style.borderStyle = "solid";
cloneContainer.style.borderColor = "red";
cloneContainer.style.borderWidth = "1px";
cloneContainer.style.top = "200px";
cloneContainer.style.left = "200px";
cloneContainer.style.zIndex = "100000";
document.body.append(cloneContainer);
}
With this code you should get a little red dot representing de borderWidth;
Your code is almost done, you just forgot to add width and height to the div element, on the other hand, camelCase shouldn't have the first letter in uppercase.
(function createDragClone() {
const cloneContainer = document.createElement("div");
cloneContainer.setAttribute("id", "cloneDiv");
cloneContainer.style.visibility = "visible";
cloneContainer.style.position = "absolute";
cloneContainer.style.borderStyle = "solid";
cloneContainer.style.borderColor = "red";
cloneContainer.style.borderWidth = "1px";
cloneContainer.style.top = "200px";
cloneContainer.style.left = "200px";
cloneContainer.style.width = "200px";
cloneContainer.style.height = "200px";
cloneContainer.style.zIndex = "100000";
document.body.append(cloneContainer);
})();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div></div>
</body>
</html>
You need to specify height and width to the created element.
One more thing, partType is passed as an argument but not being used, so you can remove it.
function CreateDragClone() {
var cloneContainer = document.createElement("div");
cloneContainer.setAttribute("id", "cloneDiv");
//cloneContainer.setAttribute("class", "closeContainer");
cloneContainer.style.visibility = "visible";
cloneContainer.style.position = "absolute";
cloneContainer.style.borderStyle = "solid";
cloneContainer.style.borderColor = "red";
cloneContainer.style.borderWidth = "1px";
cloneContainer.style.top = "200px";
cloneContainer.style.left = "200px";
cloneContainer.style.zIndex = "100000";
cloneContainer.style.width = "100px";
cloneContainer.style.height = "100px";
document.body.append(cloneContainer);
}
CreateDragClone();

Adding a background image under a background color function

I have the three functions running on my interactive pet (change background, dimmer lights, mouse follow). I'm trying to add an image to the background of the body, but every time I try it gets pushed to the top and the dirty/clean tank function doesn't work. Could someone tell me how to change the color sections of the first function below to switch between images instead of color codes? I think that would solve the immediate problem. :/
CSS Code:
//change background color: dirty/clean tank
setTimeout(function dirty() { //sets background color to murky green
document.body.style.backgroundColor = ****"#CCCC99";** //would like this to be an image**
var btn = document.body.appendChild(document.createElement('button'));
btn.appendChild(document.createTextNode("Clean the tank!"));
document.body.style.marginTop = "-1000px";
btn.onclick = function clean() {
btn.parentNode.removeChild(btn);
document.body.style.backgroundColor = **"#CCFFFF";//would like this to be an image**
setTimeout(dirty,27000); //how long it takes to make the tank dirty
};
},500); //first loading of clear blue timeout
//dim the lights
var dimmed = 0;
function toggleLights()
{
var dimmer = document.getElementById("dimmer");
if(dimmed == 0) dimmed = 1;
else dimmed = 0;
if(dimmed == 1)
{
dimmer.style.opacity = 0.8;
dimmer.style.visibility = "visible";
}
if(dimmed == 0)
{
dimmer.style.opacity = 0.0;
dimmer.style.visibility = "hidden";
}
}
//fish moves on mouse hover
$(document).ready(function() {
$("#swim").mousemove(function (event) {
var fish = $("#fish1");
var position = fish.position();
var mousey = event.pageX;
if (position.left > mousey) {
$("#fish1").html("<img src='images/happy.png' />");
} else {
$("#fish1").html("<img src='images/happyback.png'/>");
}
$("#fish1").stop().animate({
left: event.pageX,
top: event.pageY
}, 300);
});
});
HTML Code:
<HTML>
<HEAD>
<TITLE>Untitled</TITLE>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"
</script>
<script type="text/javascript" src="pet.js"></script>
<script type="text/javascript" src="core.js"></script>
</HEAD>
<div id="table">
<div id="dimmer" onClick="toggleLights()"></div>
<a href="javascript:toggleLights();"><img src="images/table-lamp.png" height="380px"
alt="table lamp"></a>
</div>
<div id="swim">
<div id="fish1"><img src="images/happy.png"/></div>
</div>
</BODY>
</HTML>
Add a starting <body> tag in your HTML, and change element classes with javascript, instead of style properties. That way you have more control over the styling through your CSS file.
So you would do something like:
document.body.className = 'state1';
And in your CSS
.state1{
background-image: url(the/image.jpg);
}
and so on...

Categories