Using fixPageXY(e) and onmousemove() and the image wont move? - javascript

Is there something im missing here? I just want to select the image by clicking on it, it should drag with the mouse(no mouse key held down) until its clicked onto I different part of the screen. Ive used function fixPageXY(e) with a onmousemove function, followed a tutorial and still nothing.
<script type="text/javascript">
function fixPageXY(e) {
if (e.pageX == null && e.clientX != null ) {
var html = document.documentElement;
var body = document.body;
e.pageX = e.clientX + (html.scrollLeft || body && body.scrollLeft || 0);
e.pageX -= html.clientLeft || 0;
e.pageY = e.clientY + (html.scrollTop || body && body.scrollTop || 0);
e.pageY -= html.clientTop || 0;
}
}
}
document.getElementById('ball').onmousedown = function() {
this.style.position = 'absolute';
var self = this;
document.onmousemove = function(e) {
e = e || event;
fixPageXY(e);
// put ball center under mouse pointer. 25 is half of width/height
self.style.left = e.pageX-25+'px';
self.style.top = e.pageY-25+'px';
}
this.onmouseup = function() {
document.onmousemove = null;
}
}
</script>
My image is simply,
<body onload="onmousemove();onmouseup();">
<img id="ball" src="ball.png" style="width:100px;height:100px;"/>
</body>
Im using google chrome, could this be an issue? many thanks for your help in advance.

There were a few syntax errors within your code, which if you are running Chrome you can just hit F12 on your keyboard and it will bring up the console allowing you to read whatever errors may be there. Here's a fiddle with just a few tweaks made to your code that allows it to run smoothly... and by tweaks, I mean there was an extra closing bracket after defining the function and the functions you called in body onload cannot me accessed that way so I deleted that and it worked.

This code work fine :
function fixPageXY(e) {
if(e.pageX == null && e.clientX != null ) {
var html = document.documentElement, body = document.body;
e.pageX = e.clientX + (html.scrollLeft || body && body.scrollLeft || 0);
e.pageX -= html.clientLeft || 0;
e.pageY = e.clientY + (html.scrollTop || body && body.scrollTop || 0);
e.pageY -= html.clientTop || 0;
}
}
document.getElementById("ball2").onmousedown = function () {
this.style.position = "absolute";
var self = this;
document.onmousemove = function (e) {
e = e || event;
fixPageXY (e);
self.style.left = e.pageX-25+'px';
self.style.top = e.pageY-25+'px';
}
this.onmouseup = function () {
document.onmousemove = null;
}
}
document.getElementById("ball2").ondragstart = function () { return false; }

Related

Implement click and drag to rotate 3D object - vue.js

I have a button, which I click to activate the rotation function. After that, every time I hover over the object with the mouse, the object rotates as I want it to.
Now I want to change this and make the object rotate just by clicking it and moving the mouse (while still holding the mouse button). When I realease the mouse button I want it to stop rotating.
My code:
HTML:
<div class="model__3d" ref="panel3d">
<a class="button" #click.prevent="rotatemouse()">360</a>
Code js:
rotatemouse() {
document.querySelector('.model__3d').addEventListener('mousedown', () =>{
document.onmousemove = handleMouseMove;
});
//document.onmouseup = function () {
document.querySelector('.model__3d').addEventListener('mouseup', () =>{
document.onmousemove = null;
});
//function handleMouseMove(event) {
document.querySelector('.model__3d').addEventListener('mousemove', (event) =>{
let eventDoc, doc, body;
event = event || window.event;
if (event.pageX == null && event.clientX != null) {
eventDoc = (event.target && event.target.ownerDocument) || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0 );
}
if(maxX == 0){
maxX = event.pageX;
}
if(maxY == 0){
maxY = event.pageY;
}
if(event.pageX > maxX){
console.log("Right");
this.model.rotation.y = this.model.rotation.y + 0.08;
maxX = event.pageX;
}
else {
console.log("Left");
this.model.rotation.y = this.model.rotation.y - 0.08;
maxX = event.pageX;
}
if(event.pageY > maxY){
console.log("Up");
if(this.model.rotation.x < 0.32)
this.model.rotation.x = this.model.rotation.x + 0.08;
console.log(this.model.rotation.x);
maxY = event.pageY;
}
else {
console.log("Down");
if(this.model.rotation.x > -0.25)
this.model.rotation.x = this.model.rotation.x - 0.08;
console.log(this.model.rotation.x);
maxY = event.pageY;
}
});
}
Thanks!
You can have the desired behaviour by using a combination of
#mousemove, #mousedown, #mouseup
new Vue({
el: '#app',
data: {
captureToggle: false,
x: 0,
y: 0
},
methods: {
mo: function(evt) {
if (this.captureToggle) {
this.x = evt.x
this.y = evt.y
}
},
captureOn: function() {
this.captureToggle = true
},
captureOff: function() {
this.captureToggle = false
}
}
})
#app {
margin: 50px;
}
.mouseArea {
height: 100px;
width: 300px;
border: solid thin;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
<div class="mouseArea" #mousedown="captureOn" #mouseup="captureOff" #mousemove="mo"></div>
<div>x : {{x}}</div>
<div>y : {{y}}</div>
</div>

Horizontal scrolling of a div using mouse and touch

Let's say I have a white-space: nowrap; div with overflow: hidden;. Its content is, of course, much longer than the div is, and needs to be scrolled to get revealed.
I was using this library, but it does not work for mobile devices with touch input. Do you know any alternative or ways to implement this feature?
Finally, my wish is fullfilled. Here I modified dragscroll.js library to enable touch support.
/* Modified dragscroll.js by Undust4able */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports);
} else {
factory((root.dragscroll = {}));
}
}(this, function (exports) {
var _window = window;
var _document = document;
var mousemove = 'mousemove';
var mouseup = 'mouseup';
var mousedown = 'mousedown';
var touchmove = 'touchmove';
var touchup = 'touchend';
var touchdown = 'touchstart';
var EventListener = 'EventListener';
var addEventListener = 'add'+EventListener;
var removeEventListener = 'remove'+EventListener;
var dragged = [];
var reset = function(i, el) {
for (i = 0; i < dragged.length;) {
el = dragged[i++];
el = el.container || el;
el[removeEventListener](mousedown, el.md, 0);
_window[removeEventListener](mouseup, el.mu, 0);
_window[removeEventListener](mousemove, el.mm, 0);
el[removeEventListener](touchdown, el.td, 0);
_window[removeEventListener](touchup, el.tu, 0);
_window[removeEventListener](touchmove, el.tm, 0);
}
// cloning into array since HTMLCollection is updated dynamically
dragged = [].slice.call(_document.getElementsByClassName('dragscroll'));
for (i = 0; i < dragged.length;) {
(function(el, lastClientX, lastClientY, pushed, scroller, cont){
(cont = el.container || el)[addEventListener](
mousedown,
cont.md = function(e) {
if (!el.hasAttribute('nochilddrag') ||
_document.elementFromPoint(
e.pageX, e.pageY
) == cont
) {
pushed = 1;
lastClientX = e.clientX;
lastClientY = e.clientY;
e.preventDefault();
}
}, 0
);
(cont = el.container || el)[addEventListener](
touchdown,
cont.td = function(e) {
if (!el.hasAttribute('nochilddrag') ||
_document.elementFromPoint(
e.pageX, e.pageY
) == cont
) {
pushed = 1;
e.preventDefault();
e = e.targetTouches[0];
lastClientX = e.clientX;
lastClientY = e.clientY;
}
}, 0
);
_window[addEventListener](
mouseup, cont.mu = function() {pushed = 0;}, 0
);
_window[addEventListener](
touchup, cont.tu = function() {pushed = 0;}, 0
);
_window[addEventListener](
mousemove,
cont.mm = function(e) {
if (pushed) {
(scroller = el.scroller||el).scrollLeft -=
(- lastClientX + (lastClientX=e.clientX));
scroller.scrollTop -=
(- lastClientY + (lastClientY=e.clientY));
}
}, 0
);
_window[addEventListener](
touchmove,
cont.tm = function(e) {
if (pushed) {
e = e.targetTouches[0];
(scroller = el.scroller||el).scrollLeft -=
(- lastClientX + (lastClientX=e.clientX));
scroller.scrollTop -=
(- lastClientY + (lastClientY=e.clientY));
}
}, 0
);
})(dragged[i++]);
}
}
if (_document.readyState == 'complete') {
reset();
} else {
_window[addEventListener]('load', reset, 0);
}
exports.reset = reset;
}));
Make a container div with overflow-y: hidden;overflow-x: scroll; and set it to whatever pre-determined height you want.
Then have your inner div that will house the content set to position:absolute; and set its width to whatever size you need the accommodate your content.
The content will scroll with the mouse and by touch.
Sounds kinda like you're going for a netflix style side scroller - check out this codepen I've done up that shows what I was just talking about.
http://codepen.io/hoonin_hooligan/pen/aZBxRG

Javascript | Creating a popup that triggers just before the page is closed

I have already created a popup overlay and currently have it set to when you click a button. However, I want it so that when you have initially scrolled down on the website and then go to move your cursor towards the top of the page (towards the navigation for example) then the popup window will appear.
Javascript
// Initialize Variables
var closePopup = document.getElementById("popupclose");
var overlay = document.getElementById("overlay");
var popup = document.getElementById("popup");
var button = document.getElementById("button");
// Close Popup Event
closePopup.onclick = function() {
overlay.style.display = 'none';
popup.style.display = 'none';
};
// Show Overlay and Popup
button.onclick = function() {
overlay.style.display = 'block';
popup.style.display = 'block';
}
I have created a JSFiddle with all my current code.
https://jsfiddle.net/1ud9crou/
With jQuery, you could do:
var isOnTop = false;
$(window).on('mousemove', function(e) {
mouseIsOnTop = e.pageY < 20;
if (mouseIsOnTop) {
button.onclick();
}
});
Otherwise, with bare Javascript (if you need IE support):
(function() {
document.onmousemove = handleMouseMove;
function handleMouseMove(event) {
var dot, eventDoc, doc, body, pageX, pageY;
event = event || window.event;
// if pageX/Y aren't available and clientX/Y are, calculate pageX/Y
if (event.pageX == null && event.clientX != null) {
eventDoc = (event.target && event.target.ownerDocument) || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0 );
}
mouseIsOnTop = event.pageY < 20;
if (mouseIsOnTop) {
button.onclick();
}
}
})();
UPDATE: to detect if user scrolled from top:
var userDidScrollABit = false;
window.onscroll = function() {
var body = document.body;
var document = document.documentElement;
document = (document.clientHeight) ? document : body;
if (document.scrollTop > 20) {
userDidScrollABit = true;
}
};

Parallax Background Positioning Scrolling

I have just developed a new parallax scrolling script. I have it working just the way I want however there is just 1 issue with it currently.
I want the script to start scrolling the background image at the y coord that is specified in the css stylesheet by default. Instead my script seems to be resetting the CSS y coord to 0 before scrolling the image. This is obviously undesired behavior.
// Parallax scripting starts here
$.prototype.jpayParallax = function(userOptions){
var _api = {};
_api.utils = {};
_api.utils.isElementInViewport = function(el){
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
_api.utils.debounceScrollWheel = (function(){
$(function(){
var $window = $(window); //Window object
var scrollTime = 0.3; //Scroll time
var scrollDistance = 50; //Distance. Use smaller value for shorter scroll and greater value for longer scroll
$window.on("mousewheel DOMMouseScroll", function(event){
event.preventDefault();
var delta = event.originalEvent.wheelDelta/120 || -event.originalEvent.detail/3;
var scrollTop = $window.scrollTop();
var finalScroll = scrollTop - parseInt(delta*scrollDistance);
TweenMax.to($window, scrollTime, {
scrollTo : { y: finalScroll, autoKill:true },
ease: Power1.easeOut, //For more easing functions see http://api.greensock.com/js/com/greensock/easing/package-detail.html
autoKill: true,
overwrite: 5
});
});
});
})();
_api.selector = 'data-jpay-parallax';
_api.methods = {};
_api.methods.checkForVisibleParallaxEls = function(){
$('['+_api.selector+']').each(function(){
var instanceObject = $(this);
var origBgPos = $(this).css('backgroundPosition').split(' ');
var options = $(this).data('jpay-parallax');
console.log(origBgPos)
if (_api.utils.isElementInViewport(instanceObject)){
_api.methods.doParallax(instanceObject, options);
}
});
}
_api.methods.doParallax = function(instanceToManip, userOptions){
var direction = userOptions.settings.direction;
var orientation = userOptions.settings.orientation;
var speed = userOptions.settings.speed;
var type = userOptions.settings.type;
var speedInt;
var getSpeed = (function(){
if (speed){
switch(speed){
case 'slow':
speedInt = 10;
break;
case 'fast':
speedInt = 5;
break;
case 'faster':
speedInt = 1;
break;
default:
throw new TypeError('Unknown speed parameter added to module instructions');
}
}
})();
var distToTopInt = function(){
if (typeof speedInt === 'number'){
return $(window).scrollTop()/speedInt;
}
else {
return $(window).scrollTop();
}
}
var origPos = instanceToManip.css('backgroundPosition').split(' ');
var origPosX = parseInt(origPos[0]);
var origPosY = parseInt(origPos[1]);
var newPosY = origPosY += distToTopInt();
var newPosX = origPosX += distToTopInt();
if (orientation === 'vertical' && direction !== 'reverse'){
instanceToManip.css('backgroundPositionY', newPosX+'px');
}
else if (orientation === 'vertical' && direction === 'reverse'){
instanceToManip.css('backgroundPositionY', -newPosX+'px');
}
else if (orientation == 'horizontal' && direction !== 'reverse'){
instanceToManip.css('backgroundPositionX', newPosX+'px');
}
else if (orientation == 'horizontal' && direction === 'reverse'){
instanceToManip.css('backgroundPositionX', -newPosY+'px');
}
}
$(window).on('scroll', _api.methods.checkForVisibleParallaxEls)
};
$.fn.jpayParallax();
Here is the pen:
http://codepen.io/nicholasabrams/pen/OPxKXm/?editors=001
BONUS: Why does this script also mess with the css set backgroundSize property when the script never accesses it?
I am looking for advice in where in the script to cache the original CSS background image y coord value so that it becomes incremented from there instead of starting at 0px /0 for each instance. Thanks again for the help!

I want to add Mouseover effect on my Canvas using JavaScript

Mouseover effect should be created only on specific canvas location.
In addition I've created the MousePosition function(See below).
commands for Mouseover effect should be on the MouseOverButton function.
But still It can't seems to work.
My code:
function init() {
var can=document.getElementById("SnakeCanvas");
var ctx=can.getContext("2d");
can.addEventListener('mouseover',MouseOverButton, false);
}
function getPosition(event) {
var x = new Number();
var y = new Number();
var can = document.getElementById("SnakeCanvas");
if (event.x != undefined && event.y != undefined) {
x = event.x;
y = event.y;
} else {//Firefox Compatability//
x = event.clientX + document.body.scrollLeft +
document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop +
document.documentElement.scrollTop;
}
x -= can.offsetLeft;
y -= can.offsetTop;
return {mx:x, my:y};
}
function MouseOverButton(e) {
var can=document.getElementById("SnakeCanvas");
var ctx=can.getContext("2d");
var cell=getPosition(event);
if ((cell.mx > 854 && cell.mx < 985) && (cell.my > 256 && cell.my < 315)) {
ReplaceImage(ctx,'Images/New_Game_Hover.png',570,100,140,70);
}
}
Your event parameter in function MouseOverButton(e) is called e but you use event when passing it to getPosition:
var cell=getPosition(event); should be var cell=getPosition(e);
Try this:
function MouseOverButton(e) {
e = e || window.event; // Compatibility
var can = document.getElementById("SnakeCanvas");
var ctx = can.getContext("2d");
var cell = getPosition(e);
// ^ That was `event`, breaking your code.
if ((cell.mx > 854 && cell.mx < 985) && (cell.my > 256 && cell.my < 315)) {
ReplaceImage(ctx,'Images/New_Game_Hover.png',570,100,140,70);
}
}

Categories

Resources