How to make a draggable image in div? - javascript

I am trying to move a image in a div like a facebook cover page, but it is not moving smoothly with image tag . when I put this image in a div like a background image it is working
my js code is ..
var draggable = function(element) {
element.addEventListener('mousedown', function(e) {
e.stopPropagation();
if (e.target != element)
return;
var offsetX = e.pageX - element.offsetLeft;
var offsetY = e.pageY - element.offsetTop;
function move(e) {
var ele = document.getElementById('ele');
var width = 400-ele.clientWidth;
var height = 400-ele.clientHeight;
element.style.left = (e.pageX - offsetX) + 'px';
element.style.top = (e.pageY - offsetY) + 'px';
}
function stop(e) {
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', stop);
}
document.addEventListener('mousemove', move);
document.addEventListener('mouseup', stop);
});
}
function init() {
var ele = document.getElementById('ele');
draggable(ele);
}
and my html code which is not working is..
<body onload="init();">
<div id="testdiv" style="position:relative;left:100px;overflow:hidden;border:1px solid #ccc;width:400px;height:400px">
<img src="Desert.jpg" id="ele" style="position:absolute;"></img>
</div>
</body>
and this code is working..
<body onload="init();">
<div id="testdiv" style="position:relative;left:100px;overflow:hidden;border:1px solid #ccc;width:400px;height:400px">
<div id="ele" style="width:100%; height:100%; background-color: gray; position:absolute; background-image:url( 'Desert.jpg' );"></div>
</div>
</body>

You could refer to this question, which handles the same idea of dragging images, althought the question is slightly different. Check out his/her JSFiddle from question.
Check it out here!

<img> is a self-closing tag. You don't need the </img> as it's not valid. Remove that and it should work fine. Depending on your doctype you should use:
HTML5
<img src="Desert.jpg" id="ele" style="position:absolute;">
XHTML (note the / at the end of the tag)
<img src="Desert.jpg" id="ele" style="position:absolute;" />

Related

Animate div towards mouse coordinates using JavaScript on click

I am trying to get the ball element to both move and shrink towards the goals on mouse click.
I have created a function that grabs the coordinates of the mouse click in the goals, however I have been struggling with the ball animation.
I thought about using keyframes, but I don't know how to use keyframes in JavaScript.
I also tried doing a transform - which I know wouldn't work, but tried as you can see in the move() function.
This is my javascript/html file
function goal(){
var score = getScore();
increaseDifficulty(score)
document.getElementById("score").innerHTML = score + 1 ;
var b = getShotCordinates();
move(b[0],b[1]);
}
function save(){
resetScore();
}
function resetScore(){
document.getElementById("score").innerHTML = 0;
}
function getScore(){
return parseInt(document.getElementById("score").innerHTML);
}
function move(x,y){
const fxMove = `translate(${x}px, ${y}px);`;
const fxAnim = `transition: transform 0.5s; transform: translate(0, 0);`;
document.getElementById("ball").style.transform = translate(x,y);
}
function getShotCordinates(){
var e = window.event;
var Cordinates = [e.clientX, e.clientY];
console.log(Cordinates[0] + " - " + Cordinates[1])
return Cordinates;
}
<BODY>
<div id="canvas" class="field">
<div id="goals" class="goals" onclick="goal()">
</div>
<div id="goalkeeper" onclick="save()">
</div>
<div id="kick-off">
<div id="ball" class="ball">
</div>
</div>
<div id="score-container">
<div id="counter">
<h1 class="counter-text">Score</h1>
<h1 class="counter-score" id="score">0</h1>
</div>
</div>
</div>
<script src='js/script.js'></script>
</BODY>
Just in case, this is my canvas/UI
If you are looking for something like this:
const div = document.querySelector("div");
document.addEventListener("click", (e)=>{
console.log(e)
div.style.top = e.clientY + "px";
div.style.left = e.clientX + "px";
})
div{
width:50px;
height:50px;
background:red;
border-radius:50%;
position:absolute;
transition:.3s;
transform:translate(-50%, -50%);
}
<div></div>
Just give the ball position absolute, and on every click event change the top and the left of the ball with javascript.

How to execute a function when the scroll reaches an element?

I want to hide all elements but the first one so I use $(".item:not(:eq(0))").fadeOut();
I have elements with the same class "item":
<div class="item">First Item</div>
<div class="item">Second Item</div>
<div class="item">Third Item</div>
<div class="item">Fourth Item</div>
Then when I scroll to the next element which could be "second , third,fourth item" , I want to show it
I tried using :
function isScrolledIntoView(elem)
{
var centerY = Math.max(0,((jQuery(window).height()-
jQuery(elem).outerHeight()) / 2)
+ jQuery(window).scrollTop());
var elementTop = jQuery(elem).offset().top;
var elementBottom = elementTop + jQuery(elem).height();
return elementTop <= centerY && elementBottom >= centerY;
}
jQuery(window).on("scroll resize", function() {
jQuery(".news:not(:eq(0))").each(function(index, element) {
if (isScrolledIntoView(element)) {
jQuery(element).fadeIn(10000);
}
});
});
But it doesn't work with my method because the height of the body changes on showing the next item "Second Item" , So All the items are shown when I scroll to the "Second Item" or any other item.
How to hide the items but the first one and then fadIn() each on scrolling to it ?
This is using offset() in jquery. This demo will trigger function if
your element is completely in your viewport.
Tip:You need to take care of inner as well as outer height of element.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
body{
height:200vh;
}
#test {
top: 100vh;
padding: 10px;
width: 300px;
position: relative;
border: 1px solid black;
height:100;
}
</style>
</head>
<body>
<p>scroll to test</p>
<div id="test">
<p>Click the button to get offsetTop for the test div.</p>
</div>
<script>
$(document).ready(function(){
$(window).scroll(function(){
var x = $("#test").offset();
var height1 = $("#test").outerHeight();
var y = document.documentElement.scrollTop;
var z = (x.top + height1) - y;
if(z < $(window).height()){
alert("fumction");
}
});
});
</script>
</body>
</html>
It will be more easy to use the combination of waypoint.js and animate.css.
Add animated class to every element to be animated. You can use any of the animate.css effects.
Change the offset { offset: '80%' } to control when the animation can start.
<div class="animated waypoint-slideup">
</div>
$('.waypoint-slideup').waypoint(function () {
$(this).addClass('slideInUp');
}, { offset: '80%' });
Use this in the css file
.waypoint-slideup{
opacity:0;}
.waypoint-slideup.slideInUp{
opacity:1;}

jQuery page up and down scroll based on mouse position

$(document).ready(function() {
var mouseX;
var mouseY;
$(document).mousemove(function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
$("#maincontainer").mousemove(function() {
// $('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
$('#DivToShow').html("Y " + mouseY + " --- " + "X " + mouseX);
if (mouseY > 230) {
$('html, body').animate({
scrollBottom: $elem.height()
}, 800);
}
});
});
pls help, I am trying to make a auto page up and down scroll based on pointer position. when pointer coming to bottom of browser, page need to scroll down 60px ++. not a single scroll to end of page.
Try this solution.
On mousemove, get the clientY and the window height. If the difference is less than 60, then scroll 60 more than the current scrollTop:
$(document).on('mousemove', function(e) {
var y = e.clientY;
var h = $(window).height();
var n = h - y;
if (n < 60) {
var t = parseFloat($(window).scrollTop());
console.log(t);
$('html,body').animate({scrollTop:t + 60 + 'px'},200);
} else {
$('html,body').stop();
}
});
#wrapper,
.section {
width:100%;
float:left;
}
.section {
height:80px;
border:1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="wrapper">
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
<div class="section"></div>
</div>

Getting mouse click position on image in javascript?

I wrote below code to get co-ordinate of x/y in JAVASCRIPT , it's not working .
I want to create a color picker using this image
when ever some one click on button pick color then it prompts a window with color and button cancel , When user clicked on image than i need to find x/y co-ordinate so that i can specify which color it is .
Problem is that these alerts are not working
alert(e.clientX - offsetl);
alert(e.clientY - offsett);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
#dialogoverlay{
display: none;
opacity: .8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display:none;
position: fixed;
background: #f2f2f2;
border-radius:5px;
z-index: 10;
}
#dialogboxhead{background:white;height:40px;margin:10px;}
#text {float:left; text-align:center;margin:10px; font-size:19px;}
#cancel{float:left;margin:9px;}
#image{
margin-top:0px;
padding:10px;
}
</style>
<script type="text/javascript">
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (550 * .5)+"px";
dialogbox.style.top = "100px";
dialogbox.style.display = "block";
}
this.cancel = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
function position(e){
var offsetl = document.getElementById('image').offsetLeft;
var offsett = document.getElementById('image').offsetTop;
alert(offsetl);
alert(offsett);
alert(e.clientX - offsetl);
alert(e.clientY - offsett);
}
</script>
</head>
<body>
<div id="dialogoverlay"></div>
<div id="dialogbox">
<div id="dialogboxhead">
<p id="text">Select color</p>
<input type="button" onClick="Alert.cancel()" id="cancel" name="Cancel" value="Cancel"/>
</div>
<div>
<img id="image" src="color.png" onClick="position()"/>
</div>
</div>
<button onclick="Alert.render('Hello World');" >pick color </button>
</body>
</html>
I recommend use jQuery and attach click event handler in you image. The event object return in jQuery include two properties, pageX and pageY. This properties contains mouse position relative to the top edge of the document (jQuery Event Object). The code look like this:
$(document).ready(function () {
$('img#image').click(position);
});
function position(e) {
var offsetX = e.pageX,
offsetY = e.page;
}
The sample is in JSFiddle http://jsfiddle.net/zV3dH/.
I hope this help you.
Try this code buddy.. Sure it works
function getClickPos(e) {
return {x:e.clientX,y:e.clientY};
}
Now u can use it like this:
document.querySelector("#img").onclick = function(e) {
var pos= getClickPos(e);
alert(pos.x);
};

JavaScript slides in but fails to slide out

I have this simple JavaScript code that is supposed to side a div in and a div out. it is working perfectly when it comes to sliding in. By working perfectly is sliding the div easily. However when you click slideout the div just disappears from the browser. I don't know why and I cant find a fault. My code is here
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
function slideIt()
{
var stopPosition = 50;
var slidingDiv = "";
slidingDiv = document.getElementById("d3");
if (parseInt(slidingDiv.style.left) < stopPosition )
{
slidingDiv.style.left = parseInt(slidingDiv.style.left) + 2 + "px";
setTimeout(slideIt, 1);
}
}
function slideOut()
{
var startPosition =-150;
var slidingDiv = "";
slidingDiv = document.getElementById("d4");
if (parseInt(slidingDiv.style.left) > startPosition )
{
slidingDiv.style.left = parseInt(slidingDiv.style.left) - 2 + "px";
setTimeout(slideOut(), 1);
}
}
</script>
<div id="d1" onclick="slideIt();">Slide in</div>
<div id="d2" onclick="slideOut();">Slide out</div>
<div id="d3" style="position: absolute; left:-150px; top:300px" >horizontally sliding div</div>
<div id="d4" style="position: absolute; left:150px; top:300px">horizontally sliding div</div>
</body>
</html>
You don't need to invoke slideOut in the second timeout. Remove the parentheses.
setTimeout(slideOut, 1);
Here is a demonstration: http://jsfiddle.net/cctqf/

Categories

Resources