Detect when an image enters a div? - javascript

I am creating a maze game, and I want to detect when the image following the cursor reaches a certain div, the finishing point. I have the image following the mouse, and I have the container that the image will be in. When the image reaches the div, I want something to trigger, lets say an alert. How can I achieve this?
var startMove;
$(document).mousemove(function(e) {
var DIFF_SNAP = 10;
var DIFF_UNSNAP = 100;
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if (!startMove && Math.abs(difLeft) < DIFF_SNAP && Math.abs(difTop) < DIFF_SNAP) {
startMove = true;
$('html').removeClass('showCursor');
} else if (startMove && !(Math.abs(difLeft) < DIFF_UNSNAP && Math.abs(difTop) < DIFF_UNSNAP)) {
startMove = false;
}
if (startMove) {
$("#image").css({
left: e.pageX,
top: e.pageY
});
} else {
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function() {
startMove = false;
})
html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
height:auto;
}
div{
margin-left: 500px;
width: 200px;
height: 50px;
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>
<div></div>
Jsfiddle: https://jsfiddle.net/3x7cgLdr/25/

if ($('#TargetDiv').is(':hover')) {
// alert('hello');
$("#image").addClass("red");
}else{
$("#image").removeClass("red");
}
Using this .is() function with :hover selector inside the
if(startMove){
}
Section simply does that without any hassle the is() function Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
.is() function documentation
var startMove;
$(document).mousemove(function(e) {
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if (difLeft < 10 && difLeft > -10 && difTop < 10 && difTop > -10) {
startMove = true;
$('html').removeClass('showCursor');
}
if (startMove) {
$("#image").css({
left: e.pageX,
top: e.pageY
});
if ($('#TargetDiv').is(':hover')) {
// alert('hello');
$("#image").addClass("red");
} else {
$("#image").removeClass("red");
}
} else {
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function() {
startMove = false;
})
html {
cursor: none;
}
html.showCursor {
cursor: default;
}
#image {
position: absolute;
width: 25px;
height: auto;
}
#TargetDiv {
height: 100px;
width: 100px;
background: green;
margin: 100px auto;
}
.red {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png" />
<div id="TargetDiv">
</div>
I have added a class to set border red to the div when it hovers on the div with mouse and cursor image superimposed that is startMove="true".And removes when it is not hovered .I have commented the alert box;You can turn it on if you want

You already have a flag called startMove that is active whenever the cursor is dragged, use the mouseenter event on the target div as follows:
var startMove;
$(document).mousemove(function(e){
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if(difLeft < 10 && difLeft > -10 && difTop < 10 && difTop > -10 ){
startMove = true;
$('html').removeClass('showCursor');
}
if(startMove){
$("#image").css({left:e.pageX, top:e.pageY});
}
else{
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function(){
startMove = false;
})
$("#drop").mouseenter(function(){
if(startMove)
alert("Success");
});
.
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>
<div id="drop">
</div>
.
html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
z-index: 100;
height:auto;
}
#drop{
width:100px;
height:100px;
background:green;
position: absolute;
left:200px;
top: 300px;
z-index:99
}
see a demo: https://jsfiddle.net/hycd913y/

Related

image script not displaying

I have this code and the problem is the "main" and "left/right" image are not being displayed. I have gone through the entire logic and can't figure out what is wrong.
The code works if I replace else with else if(flag===1 && child[I].id=="left" || child[I].id=="right")
Expected output:
movement of mouse should change the image, this change is determined by the height of the <body> element.
Output getting:
only one image is displayed and does not changes no mater where I move my mouse.
[ also changing event from "mouseover" to "mousemove" does not help ]
so why isn't it working when I remove it, shouldn't at least "main" work??
PS: I'm unable to provide an image, please find another one.
'use strict';
(function() {
var wlen = screen.availWidth;
var whet = screen.availHeight;
var last = {};
var chk = 3;
var eye = document.getElementsByClassName("eyes");
var build = function(ele) {
if (ele.previousElementSibling !== null) ele.previousElementSibling.style = "none";
last = ele.style;
last.display = "block";
}
var anite = function() {
var x = event.screenX;
var y = event.screenY;
last.display = "none";
var child;
var flag;
y < whet / 3 ? flag = 2 : (y > 2 * whet / 3) ? flag = 0 : flag = 1;
x < wlen / 2 ? child = eye[1].childNodes : child = eye[0].childNodes;
for (let i = 0; i < child.length; i++) {
if (child[i].id) {
if (child[i].id == "main" && flag === 0) {
build(child[i]);
} else if (child[i].id.search(/a/i) === 0 && flag === 2) {
build(child[i]);
} else {
build(child[i]);
}
}
}
}
document.addEventListener("mouseover", anite, false);
})()
html,body {
height: 100%;
}
body {
display: flex;
align-items: center;
}
main {
width: 100%;
overflow: hidden;
}
.eyes {
width:50%;
float: left;
height: 300px;
}
#main {
background: url('eyes.png') no-repeat 0 0;
width: 1000px;
height: 254px;
display:none;
}
#left {
background: url('eyes.png') no-repeat 0 -254px;
width: 1000px;
height: 254px;
display:none;
}
#aLeft {
background: url('eyes.png') no-repeat 0 -508px;
width: 1000px;
height: 254px;
display:none;
}
#right {
background: url('eyes.png') no-repeat 0 -762px;
width: 1000px;
height: 254px;
display:none;
}
#aRight {
background: url('eyes.png') no-repeat 0 -1016px;
width: 1000px;
height: 280px;
display:none;
}
<html>
<head>
<title>Student Details</title>
</head>
<body>
<main>
<div class="eyes">
<!-- <img src="eyes.png" alt="eyes"> -->
<p id="main"></p>
<p id="right"></p>
<p id="aRight"></p>
</div>
<div class="eyes">
<p id="main"></p>
<p id="left"></p>
<p id="aLeft"></p>
</div>
</main>
</body>
</html>

Developing image slider using jQuery and javascript

Below is my code in that i have developed three functions to get desired image by scrolling and i am having "prev" and "next" divs to move images.It looks good for me but there must be something wrong which is not letting it works.
<!DOCTYPE html>
<html>
<head><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" >
var imageArr = document.getElementsByClassName('slide');
var offset = imageArr.length-1;
var currentImage, prevImage, nextImage;
function getCurrentImage() {
currentImage = imageArr[offset];
}
function getPrevImage() {
if(offset == 0)
offset = imageArr.length-1;
else
offset = offset-1;
prevImage = imageArr[offset];
}
function getNextImage() {
if(offset == imageArr.length-1)
offset = 0;
else
offset = offset+1;
nextImage = imageArr[offset];
}
$("document").ready(function(){
$(".prev").click(function(){
$(function(){
getCurrentImage();
});
$(function(){
getPrevImage();
});
$(currentImage).css({right:0px});
$(prevImage).css({left:0px});
$(currentImage).animate({width:'80%',width:'60%',width:'40%',width:'20%',width:'0'});
$(prevImage).animate({width:'20%',width:'40%',width:'60%',width:'80%',width:'100%'});
});
$(".next").click(function(){
$(function(){
getCurrentImage();
});
$(function(){
getNextImage();
});
$(currentImage).css({right:0});
$(nextImage).css({left:0px});
$(currentImage).animate({width:'80%',width:'60%',width:'40%',width:'20%',width:'0%'});
$(nextImage).animate({width:'20%',width:'40%',width:'60%',width:'80%',width:'100%'});
});
});
</script>
<style>
.container {
width : 90%;
margin-left: 5%;
margin-right: 5%;
height : 400px;
border : 2px solid black;
position: relative;
}
img {
width:100%;
height:400px;
position: absolute;
}
.prev, .next {
position :relative;
cursor : pointer;
width : 4%;
height: 70px;
border : 1px solid black;
margin-top: -250px;
font-size: 40px;
color:#fff;
padding-left:10px;
background: #000;
opacity: .5;
}
.next {
float:right;
margin-right: 0px;
}
.prev{
float:left;
margin-left: 0px;
}
.prev:hover, .next:hover{
opacity: 1;
}
</style>
</head>
<body>
<div class="container">
<img src="slide1.jpg" class="slide" />
<img src="slide2.jpg" class="slide" />
<img src="slide3.jpg" class="slide" />
<img src="slide4.jpg" class="slide" />
</div>
<div class="prev" >❮</div>
<div class="next" >❯</div>
</body>
</html>
You have syntax errors
in $().css({right: 0px}); should by $().css({right: '0px'});
Getting html elements also must be after $("document").ready, because your html elements do not exist before.
It works for me:
$("document").ready(function(){
var imageArr = document.getElementsByClassName('slide');
var offset = imageArr.length-1;
var currentImage, prevImage, nextImage;
function getCurrentImage() {
currentImage = imageArr[offset];
}
function getPrevImage() {
if(offset == 0)
offset = imageArr.length-1;
else
offset = offset-1;
prevImage = imageArr[offset];
}
function getNextImage() {
if(offset == imageArr.length-1)
offset = 0;
else
offset = offset+1;
nextImage = imageArr[offset];
}
$(".prev").click(function(){
$(function(){
getCurrentImage();
});
$(function(){
getPrevImage();
});
$(currentImage).css({right: '0px'});
$(prevImage).css({left: '0px'});
$(currentImage).animate({width:'80%',width:'60%',width:'40%',width:'20%',width:'0'});
$(prevImage).animate({width:'20%',width:'40%',width:'60%',width:'80%',width:'100%'});
});
$(".next").click(function(){
$(function(){
getCurrentImage();
});
$(function(){
getNextImage();
});
$(currentImage).css({right: '0px'});
$(nextImage).css({left: '0px'});
$(currentImage).animate({width:'80%',width:'60%',width:'40%',width:'20%',width:'0%'});
$(nextImage).animate({width:'20%',width:'40%',width:'60%',width:'80%',width:'100%'});
});
});

Programatically resize the H div and C div along with the resizer

When I click-drag (#cssNav) to the right, it is not moving proportionately along with the #html and #css div.
This might be something very obvious, but still am not able to figure it out, what am I missing here, please help?
Note: I don't want to use display:flex
codepen
$("#htmlNav").on("mousedown", dragStartH);
$("#cssNav").on("mousedown", dragStartH);
$("#jsNav").on("mousedown", dragStartH);
function dragStartH(e) {
e.preventDefault();
dragMeta = {};
dragMeta.pageX0 = e.pageX;
dragMeta.elem = this;
dragMeta.offset0 = $(this).offset();
dragMeta.codeWindow = "#" + $(e.target).attr("id").replace("Nav", "");
function handle_dragging(e) {
var change = e.pageX - dragMeta.pageX0;
var left = dragMeta.offset0.left + change;
$(dragMeta.elem).offset({ left: left });
$("#css").width($("#css").width() - change + "px");
$("#html").width($("#html").width() + change + "px");
}
function handle_mouseup(e) {
$("body")
.off("mousemove", handle_dragging)
.off("mouseup", handle_mouseup);
}
$("body").on("mouseup", handle_mouseup).on("mousemove", handle_dragging);
}
$(document).ready(function() {
var widthPercent = ($(window).width() - 30) / 3;
$("#html").width(widthPercent + "px");
$("#css").width(widthPercent + "px");
$("#js").width(widthPercent + "px");
});
html, body {
height: 100%;
margin: 0;
}
.container{
width:100%;
height: 100%;
background-color:#343;
display: flex;
flex-direction: column;
color: #fff;
margin: 0;
}
#preview, #code{
background-color:#433;
height: 50%;
width: 100%;
margin: 0;
}
#code{
border-bottom: #333 solid 2px;
width: 100%
}
#previewNav, #codeNav{
background-color:#bbb;
height: 10px;
width: 100%;
cursor: row-resize;
}
#html{
background-color: #BFB;
}
#css{
background-color: #FBB;
}
#js{
background-color: #BBF;
}
#html, #css, #js{
float: left;
width: 32%;
height: 100%;
}
#htmlNav, #cssNav, #jsNav{
background-color:#bbb;
float: left;
height:100%;
width: 10px;
cursor: col-resize;
z-index:10;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="codeNav"></div>
<div id="code">
<div id="htmlNav"></div>
<div id="html">H</div>
<div id="cssNav"></div>
<div id="css">C</div>
<div id="jsNav"></div>
<div id="js">J</div>
</div>
<div id="previewNav"></div>
<div id="preview">P</div>
</div>
This is how I would do it:
Keep track of which handle you press with navTypeand check if the user is holding its mouse down with dragging.
Then when the user moves the mouse in the document and it is holding its mouse down (dragging) it will move the #html, #css and #js accordingly
Change your javascript into this:
var mouseX, prevMouseX, navType, change;
var dragging = false;
$("#cssNav").mousedown(function () {
dragging = true;
navType = "css";
});
$("#jsNav").mousedown(function () {
dragging = true;
navType = "js";
});
$(document).mousemove(function (e) {
mouseX = e.pageX;
if(dragging){
e.preventDefault();
change = mouseX - prevMouseX;
if(navType == "css" && ($("#css").width() - (change)) > 0 && ($("#html").width() + (change)) > 0){
var hw = $("#html").width();
var cw = $("#css").width();
$("#html").width(hw + change);
$("#css").width(cw - change);
} else if(navType == "js" && ($("#css").width() + (change)) > 0 && ($("#js").width() - (change)) > 0){
var cw = $("#css").width();
var jw = $("#js").width();
$("#css").width(cw + change);
$("#js").width(jw - change);
}
}
prevMouseX = mouseX;
}).mouseup(function () {
dragging = false;
}).mouseleave(function () {
dragging = false;
});

Prevent shaking on hard scroll while animating scrollTop

I am scrolling section to section, but if I scroll harshly with the mouse (not just one easy scroll) or I scroll harshly on the laptop touchpad, it shakes up and down before the scrolling animation starts or even jumps 2 sections!
Is it possible to make it scroll smoothly and always one section only (not jump 2 sections) regardless of how hard someone scrolls and basically disable scrolling while the animation is taking place?
My code (JSFiddle):
var isAnimated = false;
var nbhdLength = $('.nbhd').length;
var lastSectionId = nbhdLength - 1;
var allHeight = (nbhdLength - 1) * window.innerHeight;
var up = true;
function setHeights() {
$('.nbhd').css('height', window.innerHeight);
}
setHeights();
$('html').mousewheel(function(e) {
var up = e.deltaY > 0;
if (up) {
console.log('up');
up = true;
} else {
console.log('down');
up = false;
// console.log(up);
}
if (!up && $('#id' + lastSectionId).hasClass('scrolledto') || (!up && !$('.scrolledto').length)) {
$('.scrolledto').removeClass('scrolledto');
return;
}
if (isAnimated) return;
isAnimated = true;
var currentSectionId = $('.nbhd.scrolledto').data('id');
up ? currentSectionId-- : currentSectionId++;
if (currentSectionId < 0) currentSectionId = 0;
if (!$('.scrolledto').length) currentSectionId = lastSectionId;
$('.scrolledto').removeClass('scrolledto');
var section = $('#id' + currentSectionId);
section.addClass('scrolledto');
var pos = section.offset().top;
$('body, html').animate({
scrollTop: pos
}, 1000, function() {
setTimeout(function() {
isAnimated = false;
}, 100)
console.log($(window).scrollTop());
});
});
.div {
width: 100%;
}
.red {
background: red;
}
.yellow {
background: yellow;
}
.green {
background: green;
}
.blue {
background: blue;
}
.abovefooter {
background: gray;
height: 200px;
}
.footer {
background: black;
height: 350px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
<div id="id0" data-id="0" class="nbhd red scrolledto"></div>
<div id="id1" data-id="1" class="nbhd yellow"></div>
<div id="id2" data-id="2" class="nbhd green"></div>
<div id="id3" data-id="3" class="nbhd blue"></div>
<div class="abovefooter"></div>
<div class="footer"></div>
You need to prevent the default mouseWheel event from happening, using javascript to perform the desired effect instead.
$('html').mousewheel(function(e) {
e.preventDefault();
//...
}
Demo: https://jsfiddle.net/b67uw0cx/1/

How to implement a sliding animation in javascript correctly?

In my pursuit to learn javascript I am making the same slider, but with the animation on javascript (using css it is not an issue for me - it was made on the site google), as the one below:
Original Google slider (animation with css):
http://www.google.com/about/datacenters/inside/
My work so far:
http://jsfiddle.net/TS7Xu/3/
<!-- language-all: lang-html -->
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#promo{
display:block;
height: 354px;
width: 790px;
}
.promo-item {
width: 81px;
height: 354px;
float: left;
}
.promo-item.wide {
width: 613px;
}
.threeP {
background-color: rgb(206, 203, 203);
}
.oneP {
background-color: rgb(241, 220, 182);
}
.twoP {
background-color: rgb(187, 217, 226);
}
</style>
</head>
<body>
<div id="promo">
<div class="promo-item twoP wide" id="twoP">
<div>
</div>
</div>
<div class="promo-item threeP" id="threeP">
<div>
</div>
</div>
<div class="promo-item oneP" id="oneP">
<div>
</div>
</div>
</div>
<script type="text/javascript">
var oneP = document.getElementById('oneP');
var twoP = document.getElementById('twoP');
var threeP = document.getElementById('threeP');
step = 1;
function expandPanel1(){
var h = oneP.clientWidth + step;
oneP.style.width = h+"px";
if (h < 614 || h !=614) {
setTimeout("expandPanel1()", 5);
} else { oneP.style.width = 613+"px"; }
}
function expandPanel2(){
var h = twoP.clientWidth + step;
twoP.style.width = h+"px";
if (h < 614 || h !=614) {
setTimeout("expandPanel2()", 5)
} else { twoP.style.width = 613+"px"; }
}
function expandPanel3(){
var h = threeP.clientWidth + step;
threeP.style.width = h+"px";
if (h < 614 || h !=614) {
setTimeout("expandPanel3()", 5)
} else { threeP.style.width = 613+"px"; }
}
//---------------------------------------------
function expandPanel1Minus(){
var h = oneP.clientWidth - step;
oneP.style.width = h+"px";
if (h > 80 || h !=80) {
setTimeout("expandPanel1Minus()", 5)
} else { oneP.style.width = 81+"px"; }
}
function expandPanel2Minus(){
var h = twoP.clientWidth - step;
twoP.style.width = h+"px";
if (h > 80 || h !=80) {
setTimeout("expandPanel2Minus()", 5)
} else { twoP.style.width = 81+"px"; }
}
function expandPanel3Minus(){
var h = threeP.clientWidth - step;
threeP.style.width = h+"px";
if (h > 80 || h !=80) {
setTimeout("expandPanel3Minus()", 5)
} else { threeP.style.width = 81+"px"; }
}
//---------------------------------------------
oneP.onmouseover = function () {
expandPanel1()
expandPanel3Minus()
expandPanel2Minus()
}
twoP.onmouseover = function () {
expandPanel2()
expandPanel3Minus()
expandPanel1Minus()
}
threeP.onmouseover = function () {
expandPanel3()
expandPanel2Minus()
expandPanel1Minus()
}
</script>
I know this example has errors because if a long drive with the mouse on the slider, it begins to "violently" run :) I deliberately lowered animation speed.
Can someone give me some guidance on how to implement this correctly?
Here's a pure JS implementation - JSFiddle link. In case the fiddle didn't get saved, here's the JS bit only. The rest of the HTML is same as the OP. the function go is called on body load.
var f, s, t;
var which;
function go() {
f = document.getElementById('oneP');
s = document.getElementById('twoP');
t = document.getElementById('threeP');
which = s;
f.onmouseover = function() {
foo(this)
};
s.onmouseover = function() {
foo(this)
};
t.onmouseover = function() {
foo(this)
};
}
function foo(e) {
if (e.clientWidth < 613) {
e.style.width = (e.clientWidth) + 10 + "px";
which.style.width = (which.clientWidth - 10) + "px";
setTimeout(function() {
foo(e);
}, 5);
}
else if (e.clientWidth > 613) {
e.style.width = "613px";
which.style.width = "81px";
which = e;
}
}​
There is a bit of work left I think, the animation is not fast enough so it is possible to mouse over on another section while the animation is running. I leave that bit to you :)
If you want to save a lot of time, you should do it with jQuery. Try this http://jsfiddle.net/QXRVb/ sollution. In that example, I didn't preferd to resizing divs. I used Z-indexes and jQuery animate to move them. In that way its easier to make a right position for them.
<style>
#promo{
width:900px;
height:300px;
position:absolute;
top:0px;
left:0px;
overflow:hidden;
}
#oneP{
width:600px;
height:300px;
position:absolute;
top:0px;
left:0px;
background:#999;
z-index:1;
}
#twoP{
width:600px;
height:300px;
position:absolute;
top:0px;
left:150px;
background:#ddd;
z-index:0;
}
#threeP{
width:600px;
height:300px;
position:absolute;
top:0px;
left:750px;
background:#666;
z-index:1;
}
</style>
<html>
<div id="promo">
<div id="oneP">
</div>
<div id="twoP">
</div>
<div id="threeP">
</div>
</div>
</html>
<script>
$('#oneP').mouseover(function() {
$('#oneP').animate({
left: 0
},200);
$('#threeP').animate({
left: 750
},200);
$('#twoP').animate({
left: 450
},200);
});
$('#twoP').mouseover(function() {
$('#oneP').animate({
left: -450
},200);
$('#threeP').animate({
left: 750
},200);
$('#twoP').animate({
left: 150
},200);
});
$('#threeP').mouseover(function() {
$('#threeP').animate({
left: 300
},200);
$('#oneP').animate({
left: -450
},200);
$('#twoP').animate({
left: -150
},200);
});​
</script>`
With this method you can easily put image tag inside divs.

Categories