Drag and drop an image using jquery - javascript

I am trying to create a photo editor using drag and drop. The problem is that when i am trying to drag and drop the image in a div in html it reloads a new page instead of setting the image in the div. I want to put the image in the grey square.
<script type = "text/javascript">
$.event.props.push("dataTransfer");
$(function () {
function desenare(img) {
var cW = img.width, cH = img.height;
$("#editor")
.attr({ width: cW, height: cH });
var context = $("#editor")[0].getContext("2d");
context.drawImage(img, 0, 0);
var id = context.getImageData(0, 0, cW, cH);
var v = [];
for (var i = 0; i < 256; i++) {
v.push(0);
}
for (var y = 0; y < cH; y++) {
for (var x = 0; x < cW; x++) {
var i = (y * cW * 4) + x * 4;
var val = Math.round(
(id.data[i] + id.data[i + 1] + id.data[i + 2])/3);
v[val]++;
}
}
grafic(context, v, cW, cH);
}
function grafic(c, v, W, H) {
c.save();
var n = v.length;
var f = H / Math.max.apply(this, v);
var w = W / n;
c.rotate(Math.PI);
c.translate(-W, -H);
c.scale(-1, H / Math.max.apply(this, v));
c.fillStyle = "rgba(255,0,0,0.3)";
for (var i = 0; i < n; i++) {
c.fillRect(-i * w, 0, w, v[i]);
}
c.restore();
}
$(document)
.on('dragover', function (e) {
event.stopPropagation();
})
.on('drop', function (e) {
event.preventDefault();
var files = e.dataTransfer.files;
if (files.length > 0) {
var reader = new FileReader();
reader.onload = function (e) {
desenare($("#editor")
.attr("src", e.target.result)[0]);
};
reader.readAsDataURL(files[0]);
}
});
});
</script>

Please check the following code and source link for jQuery UI.
Draggable:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Draggable - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
#draggable { width: 150px; height: 150px; padding: 0.5em; }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#draggable" ).draggable();
} );
</script>
</head>
<body>
<div id="draggable" class="ui-widget-content">
<p>Drag me around</p>
</div>
</body>
</html>
Droppable:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Droppable - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
#draggable { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; }
#droppable { width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px; }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#draggable" ).draggable();
$( "#droppable" ).droppable({
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}
});
} );
</script>
</head>
<body>
<div id="draggable" class="ui-widget-content">
<p>Drag me to my target</p>
</div>
<div id="droppable" class="ui-widget-header">
<p>Drop here</p>
</div>
</body>
</html>
Source code: https://jqueryui.com/

Related

Change Text Color Every X Seconds JavaScript

New to javascript. I am writing this website and I want to randomly change the color of the logo periodically whilst the mouse hovers over it. So it goes color1, then waits x milliseconds, then color2 and so on until the mouse is not hovering over it anymore. So far I am only able to change the logo to one randomly chosen color. Furthermore I think the way I am using 'mouseover' and 'mouseout' seems pretty confusing and inefficient, is there a better way to use them?
My code (I've left only the essentials)
!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<link href="styles.css" rel="stylesheet">
<title>My Webpage</title>
<script>
document.addEventListener('DOMContentLoaded', function listen() {
var logo = document.querySelector('.logo-btn');
logo.addEventListener("mouseover", event => setTimeout(changeColor(event), 500));
logo.addEventListener("mouseout", event => resetColor(event));
})
function changeColor (event) {
var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"]
var color = colors[Math.floor(Math.random() * colors.length)];
var logo = event.target;
logo.style.color = color;
}
function resetColor (event) {
var logo = event.target;
logo.style.color = "black";
}
</script>
</head>
<body>
<header>
<div class="header-logo">
<a href="x">
<button class="logo-btn">Logo</button>
</a>
</div>
</body>
</html>
header {
background-color: #fff;
height: 80px;
position: relative;
}
.header-logo {
font-size: 50px;
position: absolute;
bottom: -15px;
left: 40px;
}
.logo-btn {
background-color: transparent;
border: none;
text-align: bottom;
}
```
Thank you very much!
You had done it pretty much right. All you needed was to use setInterval instead of setTimeout. Also, you need to store the interval in a variable and clear it on mouseout so that the text does not keep changing the color.
let interval;
document.addEventListener('DOMContentLoaded', function listen() {
var logo = document.querySelector('.logo-btn');
logo.addEventListener("mouseover", event => {interval = setInterval(()=>changeColor(event), 500)});
logo.addEventListener("mouseout", event => resetColor(event));
})
function changeColor(event) {
var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"]
var color = colors[Math.floor(Math.random() * colors.length)];
var logo = event.target;
logo.style.color = color;
}
function resetColor(event) {
var logo = event.target;
logo.style.color = "black";
clearInterval(interval);
}
header {
background-color: #fff;
height: 80px;
position: relative;
}
.header-logo {
font-size: 50px;
position: absolute;
bottom: -15px;
left: 40px;
}
.logo-btn {
background-color: transparent;
border: none;
text-align: bottom;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<link href="styles.css" rel="stylesheet">
<title>My Webpage</title>
</head>
<body>
<header>
<div class="header-logo">
<a href="x">
<button class="logo-btn">Logo</button>
</a>
</div>
</header>
</body>
</html>
A recursive function can be a solution for your problem.
You set mouseOver variable on 1 when mouse is over, and on 0 when mouse is out.
You also call setColor on mouseover and check if mouse is over with mouseOver flag.
Now you call setColor that set a new color every time it's called based on selected variable
var logo = document.querySelector('.logo-btn');
logo.addEventListener("mouseover", event => {setColor(event); mouseOver = 1});
logo.addEventListener("mouseout", event => resetColor(event));
var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"],
selected = 0,
mouseOver = 0
function setColor(e){
e.target.style.backgroundColor = colors[selected]
if(mouseOver){
setTimeout(function(){
if(colors.length > selected + 1){
selected = 0
}
else{
selected ++
}
setColor(e)
}, 500)
}
}
function resetColor(event){
selected = 0
mouseOver = 0
e.target.style.backgroundColor = colors[selected]
}
It should be like this...
let colors = [1,2,3],
element = document.querySelector('whatever-your-logo'),
colorIndex = 0;
function changeColor(){
//set color
element.style.color = colors[colorIndex];
//change to next color
colorIndex++;
// if it's last color then back to first colorIndex
if(colorIndex >= colors.length-1) colorIndex = 0;
}
//Interval
let priod = 1000; //in ms
let interval = setInterval(changeColor, priod);
//done...

Having issue's on image position after user selects reset

I have some image assets (folders in this example), where I can drag around and then use the "reset" button to essentially clean them up. However, after you reset the positions and try to drag again, it takes you all the way back to where you dragged it previously? Odd right??? Any help is greatly appreciated!
Again, looking to just solve for:
Let the user drag a folder/image
Let the user reset/clean-up
Let the user drag again, but starting from "reset"
"use strict";
// Reset Folder position on Clean Up
$(".reset-position").click(function () {
// Reset position
$(".resize-drag").removeAttr("style").css("transition", ".5s");
setTimeout(function () {
$(".resize-drag").removeAttr("style");
}, 600);
});
interact(".resize-drag")
.draggable({
onmove: window.dragMoveListener,
})
.resizable({
preserveAspectRatio: false,
edges: { left: false, right: false, bottom: false, top: false },
})
.on("resizemove", function (event) {
var target = event.target,
x = parseFloat(target.getAttribute("data-x")) || 0,
y = parseFloat(target.getAttribute("data-y")) || 0;
// update the element's style
target.style.width = event.rect.width + "px";
target.style.height = event.rect.height + "px";
// translate when resizing from top or left edges
x += event.deltaRect.left;
y += event.deltaRect.top;
target.style.webkitTransform = target.style.transform =
"translate(" + x + "px," + y + "px)";
target.setAttribute("data-x", x);
target.setAttribute("data-y", y);
target.textContent = event.rect.width + "×" + event.rect.height;
});
function dragMoveListener(event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute("data-x")) || 0) + event.dx,
y = (parseFloat(target.getAttribute("data-y")) || 0) + event.dy;
// translate the element
target.style.webkitTransform = target.style.transform =
"translate(" + x + "px, " + y + "px)";
// update the posiion attributes
target.setAttribute("data-x", x);
target.setAttribute("data-y", y);
}
:root {
--font-color: #000;
--font-size: 13px;
}
html,
body {
overflow: hidden;
background:white;
}
p {
font-size: var(--font-size);
text-align: center;
padding-top: 5px;
color: var(--font-color) !important;
}
.folder-container-1 {
width: 82px;
position: absolute;
right: 30px;
top: 10%;
cursor: pointer;
}
#folders {
width: 82px;
display: flex;
align-content: center;
justify-content: center;
}
#folders:active {
opacity: 0.7;
transform: rotate(4deg);
background: rgba(0, 0, 0, 0.5);
border-radius: 4px;
border: 1px solid grey;
}
.resize-drag {
box-sizing: border-box;
touch-action: none !important;
user-select: none !important;
}
.resize-container {
width: 100%;
height: 240px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>Folder Reset Position</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<div class="folder-container-1">
<div class="folder-1 resize-drag projects-folder" data-target="#myProjects">
<img src="https://i.ibb.co/C2W4qR0/folder.png" id="folders" title="folder" alt="folder" />
<p>Folder 1</p>
</div>
<div class="folder-1 resize-drag components-folder" data-target="#myComponents">
<img src="https://i.ibb.co/C2W4qR0/folder.png" id="folders" title="folder" alt="folder" />
<p>Folder 2</p>
</div>
<div class="folder-1 resize-drag about-folder" data-target="#aboutMe">
<img src="https://i.ibb.co/C2W4qR0/folder.png" id="folders" title="folder" alt="folder" />
<p>Folder 3</p>
</div>
<button class="reset-position">Reset</button>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/interact.js/1.2.6/interact.min.js"></script>
<script src="/script.js"></script>
<script src="/drag.js"></script>
</html>
You have the data-x/data-y attribute still attached to the draggable even after reset. Try removing that and it should work fine.
I'm quite not sure why you need setTimeout to remove the style attribute though. I have added an extra statement to remove data-x and data-y. Maybe you can clean that up to a single statement
$(".reset-position").click(function () {
// Reset position
$(".resize-drag").removeAttr("style").css("transition", ".5s");
$(".resize-drag").removeAttr('data-x data-y');
setTimeout(function () {
$(".resize-drag").removeAttr("style");
}, 600);
});

Background Images changing with a click

I am trying to change my 4 background images on mouseclick.
At the moment the same image appears 4 times on the screen (1 in each corner).
I would like to have only one image appearing on the whole screen and others replacing it when I click on the current image; and so on and so forth as you click again.
I am unsure what is wrong with my code at the moment.
HTML:
<!DOCTYPE html>
<html lang="fr" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title> CODE </title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="js/jquery.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/sketch.js"></script>
</head>
<body>
<div id="body" class="imageOne"></div>
</body>
</html>
JS:
var bodyObj,
className,
index;
bodyObj = document.getElementById('body');
index = 1;
className = [
'imageOne',
'imageTwo'
];
function updateIndex() {
if (index === 0) {
index = 1;
} else {
index = 0;
}
}
bodyObj.onclick = function(e) {
e.currentTarget.className = className[index];
updateIndex();
}
CSS:
html, body, #body {
height: 100%;
width: 100%;
}
#body.imageOne {
background-image: url("img1.png");
}
#body.imageTwo {
background-image: url("img2.png");
}
#body.imageTwo {
background-image: url("img3.png");
}
#body.imageTwo {
background-image: url("img4.png");
}
Rather than using classes for each image, it would be good to store them in an array and then change it programmatically. Please find the snippet below.
let imgList = [
'https://dummyimage.com/200x200/000/fff&text=image+1',
'https://dummyimage.com/200x200/000/fff&text=image+2', 'https://dummyimage.com/200x200/000/fff&text=image+3', 'https://dummyimage.com/200x200/000/fff&text=image+4'
];
let currentIndex = 0;
function changeImg() {
$('#body').css('backgroundImage', `url(${imgList[currentIndex]})`);
currentIndex++;
if (currentIndex == imgList.length) currentIndex = 0;
}
changeImg();
$('#body').on('click', changeImg);
#body {
width: 200px;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="body" class="imageOne"></div>
Here is another way (using classes as you did):
var bodyObj = document.getElementById('body'),
index = 0,
className = [
'imageOne',
'imageTwo',
'imageThree',
'imageFour'
];
bodyObj.onclick = function(e) {
index = (index + 1) % className.length;
e.currentTarget.className = className[index];
}
html,body,#body { margin: 0; height: 100%; width: 100%; }
#body { background-position: center; background-size: cover; }
#body.imageOne { background-image: url("https://picsum.photos/id/9/536/354"); }
#body.imageTwo { background-image: url("https://picsum.photos/id/3/536/354"); }
#body.imageThree { background-image: url("https://picsum.photos/id/1/536/354"); }
#body.imageFour { background-image: url("https://picsum.photos/id/2/536/354"); }
<div id="body" class="imageOne"></div>
I tried this one which works pretty well!
var index = 0;
var className = ['imageOne',
'imageTwo',
'imageThree',
'imageFour',
'imageFive'];
$(document).ready(function() {
$("#main").on("click", function() {
index = (index + 1) % className.length;
$(this).attr('class', className[index]);
});
});

How to move an drag and drop item to a certain position, when located over canvas?

I am working on a Tablet-environment with draggable objects.
The drag & drop works, it is even possible to drag several objects at once, when implemented.
References are :
Reference 1 & Reference 2
This is how the current version of my code looks like:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta
name='viewport'
content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
/>
<!--
Refernces:
* https://wiki.selfhtml.org/wiki/JavaScript/Tutorials/Drag_and_Drop
* https://mobiforge.com/design-development/touch-friendly-drag-and-drop
-->
<style>
#container {
width: 200px;
height: 200px;
position: relative;
background: yellow;
top: 100px
}
main1 {
position: relative;
}
div1 {
position: absolute;
top: 0px;
left: 100px;
height: 72px;
width: 72px;
background: red;
border: 0px solid #666;
margin: 0;
padding: 0;
}
</style>
<title>Clean up</title>
</head>
<body>
<div id ="container">
</div>
<main1 id="main1">
<div1 class="draggable" id="d1-0""></div1>
</main1>
<script>
var nodeList = document.getElementsByClassName('draggable');
for(var i=0;i<nodeList.length;i++) {
var obj = nodeList[i];
obj.addEventListener('touchmove', function(event) {
var touch = event.targetTouches[0];
// Place element where the finger is
event.target.style.left = touch.pageX + 'px';
event.target.style.top = touch.pageY + 'px';
event.preventDefault();
}, false);
}
</script>
</body>
</html>
The idea is, that the red box (div1) can be moved, dragged and dropped everywhere on the screen. But it needs to be moved to its very initial starting position, when it enters the yellow canvas. (The idea is to "clean up" and "move objects back to where they came from".)
You should use jQuery UI's draggable and touch punch for mobile friendliness
Let me know if this is close to what you're looking for and we can adjust as needed
$(document).ready(function() {
$('#div1').draggable();
$('#container').droppable({
drop: function( event, ui ) {
alert("You dropped the red on the yellow");
}
});
$(document).on("click", "#animateBtn", function() {
//Simple animate w/ just specifying the offsets
//$('#div1').animate({top:"250px", left:"250px"});
//Other animate options
$('#div1').animate({
top:"15px",
left:"15px"
}, {
duration:555, //Animation time in pixels
easing:"easeOutQuart" //See https://api.jqueryui.com/easings/
});
});
});
#container {
width: 200px;
height: 200px;
position: relative;
background: yellow;
top: 100px
}
body {
position: relative;
}
#div1 {
position: absolute;
top: 0px;
left: 100px;
height: 72px;
width: 72px;
background: red;
border: 0px solid #666;
margin: 0;
padding: 0;
}
#animateBtn {
position:fixed;
right:10px;
bottom:10px;
display:inline-block;
padding:3px 5px;
background-color:green;
color:white;
border-radius:6px
}
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta
name='viewport'
content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
/>
<title>Drag and Drop</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
</head>
<body>
<div id="container"></div>
<div class="draggable" id="div1"></div>
<div id="animateBtn">Animate</div>
</body>
</html>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta
name='viewport'
content='width=50px, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,'
/>
<title>Drag and Drop</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
<style>
#container {
width: 200px;
height: 200px;
position: relative;
background: yellow;
top: 100px
}
body {
position: relative;
}
#div1 {
position: absolute;
top: 100px;
left: 100px;
height: 72px;
width: 72px;
background: red;
border: 0px solid #666;
margin: 0;
padding: 0;
}
</style>
<title>Clean up</title>
</head>
<body>
<div id="container"></div>
<div class="draggable" id="div1"></div>
<!--<div id="animateBtn">Animate</div>-->
<script>
$(document).ready(function() {
$('#div1').draggable();
$('#container').droppable({
drop: function() {
$('#div1').animate({top:"100px", left:"100px"});
}
});
});
</script>
</body>
</html>
I didn't see a mention of jQuery but w3schools has a working example that goes without. Could you some touchup though:
/**
* Make object draggable
* #param {Element} element
*/
const addDraggable = (element)=> {
let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
const dragMouseDown = e => {
e = e || window.event;
e.preventDefault();
// get the mouse cursor position at startup:
[pos3, pos4] = [e.clientX, e.clientY];
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;
};
const elementDrag = e => {
console.log(e.clientX, e.clientY);
e = e || window.event;
e.preventDefault();
// calculate the new cursor position:
[pos1, pos2] = [pos3 - e.clientX, pos4 - e.clientY];
[pos3, pos4] = [e.clientX, e.clientY];
// set the element's new position:
[element.style.top, element.style.left] =
[(element.offsetTop - pos2) + "px", (element.offsetLeft - pos1) + "px"];
};
const closeDragElement = _ => {
// stop moving when mouse button is released:
document.onmouseup = null;
document.onmousemove = null;
};
element.onmousedown = dragMouseDown;
}
document.addEventListener("DOMContentLoaded", event=> {
_('#logo-top').addEventListener('click', event=> {
event.stopPropagation();
_('#logo-top').classList.toggle('active');
_('nav').forEach( n=> n.classList.toggle('collapsed') );
_('main').classList.toggle('extended');
});
addDraggable( _('#help-text') );
_( '#help' ).addEventListener( 'click', ()=>{ _('#help-text').classList.toggle('active')} );
_( '#help-text-close' ).addEventListener( 'click', ()=>{_('#help-text').classList.toggle('active')} );
});
Another way would be to use the Drag Operations

JQuery Parallax Background moving with mouseover

I have implemented horizontal parallax background following this tutorial.
I want to have the same effect vertically . Please Help.
This is my code so far,
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
var currentX = '';
var movementConstant = .015;
$(document).mousemove(function(e) {
if(currentX == '') currentX = e.pageX;
var xdiff = e.pageX - currentX;
currentX = e.pageX;
$('.parallax div').each(function(i, el) {
var movement = (i + 1) * (xdiff * movementConstant);
var newX = $(el).position().left + movement;
$(el).css('left', newX + 'px');
});
});
</script>
<style>
.parallax {
position: absolute;
width: 100%;
height: 800px;
overflow: hidden;
left: 0;
}
.water {
position: absolute;
width: 100%;
height: 800px;
left:0;
background-repeat: no-repeat;
background-position: top center;
}
.water-layer1 {
background-image: url(water-layer-1.png);
}
.water-layer2 {
background-image: url(water-layer-2.png);
}
.water-layer3 {
background-image: url(water-layer-3.png);
}
.water-layer4 {
background-image: url(water-layer-4.png);
}
</style>
</head>
<body>
<div class="parallax">
<div class="water water-layer4"></div>
<div class="water water-layer3"></div>
<div class="water water-layer2"></div>
<div class="water water-layer1"></div>
</div>
</body>
</html>
I'm on mobile so I can't test... try this:
<script>
var currentY = '';
var movementConstant = .015;
$(document).mousemove(function(e) { if(currentY == '') currentY = e.pageY;
var ydiff = e.pageY - currentY;
currentY = e.pageY;
$('.parallax div').each(function(i, el) { var movement = (i + 1) * (ydiff * movementConstant);
var newY = $(el).position().top + movement; $(el).css('top', newY + 'px'); }); });
</script>

Categories