Image change mouse move - javascript

I'm still very new to jquery and javascript.
I'm trying to make a image change whenever the mouse move to the left. For example, every 50px the mouse move to the left, the image will change.
I don't know where to start. But I found this in JSFiddle .
Not too sure how to advance from there though.
$( "div" ).mousemove(function( event ) {
var pageCoords = "( " + event.pageX + ", " + event.pageY + " )";
var clientCoords = "( " + event.clientX + ", " + event.clientY + " )";
$( "span:first" ).text( "( event.pageX, event.pageY ) : " + pageCoords );
$( "span:last" ).text( "( event.clientX, event.clientY ) : " + clientCoords );
if(event.pageX){
}
});
I appreciate all helps. Thank you so much.

found an interesting jsfiddle that detects mouse movement, taken from this question.
i was able to get it to work with four images. just create more classes, oldMath variables, and else if statements for more.
var oldMath = 0;
var oldMath2 = 50;
var oldMath3 = 100;
$('#image').mousemove(function(event) {
var startingTop = 10,
startingLeft = 22,
math = Math.round(Math.sqrt(Math.pow(startingTop - event.clientY, 2) +Math.pow(startingLeft - event.clientX, 2))) + 'px';
$('#currentPos').text('you are at :' + math); // remove this line if you don't want the span
if(Math.abs(parseInt(math) - oldMath) > 50){
//you have moved 5 pixles, put your stuff in here
$('.example').removeClass('example').addClass('example2').text('it\'s fall!');
oldMath = parseInt(math);
} else if(Math.abs(parseInt(math) - oldMath2) > 50){
//you have moved 5 pixles, put your stuff in here
$('.example2').removeClass('example2').addClass('example3').text('it\'s winter!');
oldMath2 = parseInt(math);
} else if(Math.abs(parseInt(math) - oldMath3) > 50){
//you have moved 5 pixles, put your stuff in here
$('.example3').removeClass('example3').addClass('example4').text('it\'s spring!');
oldMath3 = parseInt(math);
}
});
#image {
width: 500px;
height: 500px;
color: white;
font-size: 25px;
}
.example {
background: url('http://writers.uclaextension.edu/wp-content/uploads/2013/03/summer.jpg');
}
.example2 {
background: url('http://pcafalcons.com/wp-content/uploads/2014/10/Fall_image.jpg');
}
.example3 {
background: url('http://cdn1.theodysseyonline.com/files/2015/12/04/635848557150633136-120303261_winter.jpg');
}
.example4 {
background: url('http://sites.psu.edu/showerthoughts/wp-content/uploads/sites/21601/2015/03/spring-flowers-background-3.jpg');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="currentPos"></span>
<div class="example" id="image">hover to change the season</div>

Related

Shifting a div to the left on click in angularjs

So I am trying to allow the user to shift a div to the left or right in angularjs. Right now I have the function below. It works on the first click but all it does is toggle every click and is saying left is NaN. What am I doing wrong here? Also if someone has a better solution for this please let me know.
vm.scrollSelector = function(e, direction) {
var target = document.getElementById('item-selector');
var left = target.style.left;
if(direction === 'left') {
left += 600;
target.setAttribute('style', 'left: ' + left + 'px');
} else {
left -= 600;
target.setAttribute('style', 'left: ' + left + 'px');
}
}
So I quickly found the answer just by looking at the docs. Left is returned as a string so all I had to to was do parseInt(left) + 600 and it worked.
vm.scrollSelector = function(e, direction) {
var target = document.getElementById('item-selector');
var left = target.style.left.match(/\d+/);
left = parseInt(left[0], 10)
if(direction === 'left') {
left += 600;
target.setAttribute('style', 'left: ' + left + 'px');
} else {
left -= 600;
target.setAttribute('style', 'left: ' + left + 'px');
}
}
First try to see what value target.style.left is returning. It might be returning value like '10px'. You need to convert this into a number first then perform the addition or subtraction.

Moving highlight works on one page but not the other

I am using this moving highlight as reference on my website: https://css-tricks.com/examples/MovingHighlight/
<script>
var originalBG = '',
lightColor = 'fff',
gradientSize = 500;
$('.navigation .flex, .navigation a, .black')
.mousemove(function(e) {
originalBG = $(".navigation .flex, .black").css("background-color");
x = e.pageX - this.offsetLeft;
y = e.pageY - this.offsetTop;
xy = x + " " + y;
bgWebKit = "-webkit-gradient(radial, " + xy + ", 0, " + xy + ", 400, from(rgba(255,255,255,0.2)), to(rgba(255,255,255,0.0))), " + originalBG;
bgMoz = "-moz-radial-gradient(" + x + "px " + y + "px 45deg, circle, " + lightColor + " 0%, " + originalBG + " " + gradientSize + "px)";
$(this)
.css({ background: bgWebKit })
.css({ background: bgMoz });
}).mouseleave(function() {
$(this).css({ background: originalBG });
});
</script>
I've tried removing various scripts etc but nothing seems to be working. Any ideas why I'm not seeing the gradient on the home page?
removing the parent elements position:relative; solved the problem.

drag a div into existence

I have a selection on a canvas, that I can drag and resize when it´s there.
I also can make it visible when I drag on the empty canvas.
But how do I make it visible and instantly have the bottom-right corner "in my hand" (for resizing); i.e. can I pass the drag event from the canvas to a resize event on the selection?
Is there a way with jQuery or do I have to make my own?
<div id="canvas" style="position:relative;width:500px;height:500px"
draggable="true" onDragStart="initSelection(event)">
<div id="selection" style="border:1px dashed gray;position:absolute;display:none"></div>
</div>
$('#selection').draggable({containment:'parent'}).resizable({containment:'parent'});
function initSelection(e){
if ('none'==$('#selection').css('display'))
{
var q=$('#canvas').offset();
$('#selection')
.css('left', e.clientX-q.left)
.css('top', e.clientY-q.top)
.css('width',10).css('height',10)
.css('display','block')
;
}
}
I think I see what you're trying to do.
Testing here: jsfiddle.net/Twisty/vkLjn0gL
I think you need to take one route or the other, not both at once.
resize the div with CSS based on the mousedown / mouseup events and
mouse x and y.
make it resizable up front and enable/start the resize
event tied to the mousemove until done and then make it draggable
I got this far when you posted that you found an answer: https://jsfiddle.net/Twisty/vkLjn0gL/5/
$(function() {
$("#canvas").on("dragstart", initSelection);
$("#canvas").on("mousemove", resize);
$("#canvas").on("mouseup", function() {
allowResize = false;
});
var allowResize = false;
/*
$('#selection').draggable({
containment: 'parent'
}).resizable({
containment: 'parent'
});
*/
function initSelection(e) {
if ('none' == $('#selection').css('display')) {
var q = $('#canvas').offset();
$('#selection')
.css('left', e.clientX - q.left)
.css('top', e.clientY - q.top)
.css('width', '10px').css('height', '10px')
.css('display', 'block');
allowResize = true;
}
}
function resize(e) {
if (allowResize) {
//console.log("MouseMove: ", e);
var w = $("#selection").width(),
h = $("#selection").height(),
q = $("#canvas").offset(),
px = 0,
py = 0;
px = e.clientX - q.left;
py = e.clientY - q.top;
console.log("Width: ", (w + px), " Height: ", (h + py));
$("#selection").css({
width: (w + px) + "px",
height: (h + py) + "px"
});
}
}
});
Update 1
Few fixes to mouse tracking:
https://jsfiddle.net/Twisty/vkLjn0gL/6/
function resize(e) {
if (allowResize) {
//console.log("MouseMove: ", e);
$("#canRes").html(allowResize);
$("#cx").html(e.clientX - $("#canvas").offset().left);
$("#cy").html(e.clientY - $("#canvas").offset().top);
$("#ox").html($("#selection").width());
$("#oy").html($("#selection").height());
var w = $("#selection").width(),
h = $("#selection").height(),
q = $("#canvas").offset(),
o = $("#selection").position();
px = 0,
py = 0;
if (w > $("#canvas").width() + q.left) {
return false;
}
if (h > $("#canvas").height() + q.top) {
return false;
}
px = e.clientX - q.left - o.left;
py = e.clientY - q.top - o.top;
$("#selection").css({
width: px + "px",
height: py + "px"
});
}
}
Update 2
I think this will do all that you wanted if you're still looking: https://jsfiddle.net/Twisty/vkLjn0gL/7/
Updated to selection after mouseup
$("#canvas").on("mouseup", function() {
allowResize = false;
$("#canRes").html(allowResize);
$("#selection").draggable({
containment: 'parent'
})
.resizable({
containment: 'parent'
});
});
Update 3
Added the drag handle on initial sizing: https://jsfiddle.net/Twisty/vkLjn0gL/10/

How do I position a div relative to the mouse pointer exactly when scroll page?

I found this example on my search.
But it is useless, because when the webpage has long height, and my <div> block isn't on the top, when I scroll the page, there are different distances with different PageY or clientY, so the movable <div> can not exactly go after the mouse cursor.
Here's what I've tried so far:
jQuery("#requestStatusChart").mouseover(function (event) {
var maskVal = '<span id="floatTip" style="position:absolute"><span id="hintdivlogistics" class="RMAHintdivlogistics">' +
+'</span><div class="clear"></div></span>';
jQuery(this).find(".DashboardMask").append(maskVal)
ShowHintInfoLogistics("abc");
//when onmouse out ,remove the elements I appended before.
jQuery(this).find(".DashboardMask").mouseout(function () {
if (typeof jQuery("#hintdivlogistics") != undefined) {
jQuery("#floatTip").fadeOut("slow").remove();
}
});
//move current row
jQuery(this).find(".DashboardMask").mousemove(function (event) {
_xx = event.clientX;
_yy = event.clientY;
_yyPage = event.pageY;
var pos = jQuery(this).position();
console.log((pos.left + " " + pos.top));
jQuery("#floatTip").css({ "top": _yy + "px", "left": _xx - 180 + "px",
"border": "2px solid red"
}).fadeIn("slow");
console.log("x:" + _xx + ",y:" + _yy / _yyPage * _yy);
return false;
});
return false;
});
I don't know of any way to do that reliably, given that you don't know the position of the mouse without a mouse event. You could keep track of the mouse position on mousemove, but as this snippet demonstrates it's far from ideal.
function mousemoved(event) {
var f = document.querySelector('#floater');
console.log(event);
f.style.top = event.pageY + f.scrollTop + 'px';
f.style.left = event.pageX + 'px';
}
document.querySelector('#container').addEventListener('mousemove', mousemoved);
#container {
overflow: scroll;
position: relative;
}
#content {
height: 4000px;
background: lightblue;
}
#floater {
position: absolute;
border: 1px solid black;
padding: 1em 2em;
}
<div id="container">
<div id="floater">Hi</div>
<div id="content">content just to make the container taller</div>
</div>
I have solved this problem use another way.
in X axis we can do like this.
content means your main program width,codes adapted all resolution.
var widthContent = jQuery("#content").width();
jQuery("#floatTip").css("left", _xx - (window.screen.width - widthContent)/2 + "px");

how to get the top left x and y coordinate using javascript

I know that we can get width and height using clientWidth and clientHeight, however how do I figure out the top left x and top left y position of an element?
function findPosX(obj)
{
var curleft = 0;
if(obj.offsetParent)
while(1)
{
curleft += obj.offsetLeft;
if(!obj.offsetParent)
break;
obj = obj.offsetParent;
}
else if(obj.x)
curleft += obj.x;
return curleft;
}
function findPosY(obj)
{
var curtop = 0;
if(obj.offsetParent)
while(1)
{
curtop += obj.offsetTop;
if(!obj.offsetParent)
break;
obj = obj.offsetParent;
}
else if(obj.y)
curtop += obj.y;
return curtop;
}
Retrieve the position (X,Y) of an HTML element
Find X/Y of an HTML element with JavaScript
These two links should be helpful.
Using jQuery you can do this by calling .position() function. Like:
$('#mydiv').position().left;
$('#mydiv').position().top;
This is the most reliable way, since it already calculates the position checking the CSS of elements and its parents.
You can see the full implementation here:
http://code.jquery.com/jquery-1.7.1.js at line 9077
To get the top you need to add the offsetTop of the element and the element's offsetParent's offsetTop. Do this all the way up the DOM to the document. That accounts for absolute, relative and fixed positioning. To get the left, do the same thing with offsetLeft.
These two functions add two properties to Element, documentOffsetTop and documentOffsetLeft, that will get top/left of any element:
window.Object.defineProperty( Element.prototype, 'documentOffsetTop', {
get: function () {
return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
}
} );
window.Object.defineProperty( Element.prototype, 'documentOffsetLeft', {
get: function () {
return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 );
}
} );
This demo shows several combinations of element layout, comparing documentOffsetTop with jQuery's offset().top.
Demo: http://jsfiddle.net/ThinkingStiff/3G7EZ/
Script:
window.Object.defineProperty( Element.prototype, 'documentOffsetTop', {
get: function () {
return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
}
} );
var line = document.getElementsByClassName( 'grid-line' )[0],
grid = document.getElementById( 'grid' );
for( var index = 2; index < 100; index++ ) {
var copy = line.cloneNode();
copy.textContent = ( index * 10 );
grid.appendChild( copy );
};
var offset = document.getElementById( 'absolute' );
offset.textContent = 'absolute: '
+ offset.documentOffsetTop + ', $'
+ $( offset ).offset().top;
offset = document.getElementById( 'static' );
offset.textContent = 'static: '
+ offset.documentOffsetTop + ', $'
+ $( offset ).offset().top;
offset = document.getElementById( 'static2' );
offset.textContent = 'static: '
+ offset.documentOffsetTop + ', $'
+ $( offset ).offset().top;
offset = document.getElementById( 'relative' );
offset.textContent = 'relative: '
+ offset.documentOffsetTop + ', $'
+ $( offset ).offset().top;
offset = document.getElementById( 'fixed-side' );
offset.textContent = 'fixed/absolute (side): '
+ offset.documentOffsetTop + ', $'
+ $( offset ).offset().top;
offset = document.getElementById( 'fixed-top' );
offset.textContent = 'fixed/absolute (top): '
+ offset.documentOffsetTop + ', $'
+ $( offset ).offset().top;
offset = document.getElementById( 'fixed-bottom' );
offset.textContent = 'fixed/absolute (bottom): '
+ offset.documentOffsetTop + ', $'
+ $( offset ).offset().top;
offset = document.querySelectorAll( '#relative-wrapped-absolute div' )[0];
offset.textContent = 'absolute/relative/static (absolute/relative wrapped): '
+ offset.documentOffsetTop + ', $'
+ $( offset ).offset().top;
offset = document.querySelectorAll( '#static-wrapped-static div' )[0];
offset.textContent = 'static (static wrapped): '
+ offset.documentOffsetTop + ', $'
+ $( offset ).offset().top;
HTML:
<div id="static" class="offset">0</div>
<div id="static2" class="offset">0</div>
<div id="static-wrapped-static"><br /><div class="offset">0</div></div>
<div id="absolute" class="offset">0</div>
<div id="relative" class="offset">0</div>
<div id="fixed-side" class="offset">0</div>
<div id="fixed-top" class="offset">0</div>
<div id="fixed-bottom" class="offset">0</div>
<div style="position: relative;"><div id="relative-wrapped-absolute"><div class="offset">0</div></div></div>
<div id="grid"><div class="grid-line">10</div></div>
CSS:
body {padding-left: 12px;}
#absolute {
top: 100px;
position: absolute;
}
#relative {
top: 150px;
position: relative;
}
#fixed-side {
right: 0;
position: fixed;
}
#fixed-top {
left: 50%;
position: fixed;
top: 0;
}
#fixed-bottom {
left: 50%;
position: fixed;
bottom: 0;
}
#relative-wrapped-absolute {
top: 8px;
position: relative;
}
#relative-wrapped-absolute div {
position: absolute;
top: 20px;
}
.offset {
border: 1px solid black;
}
#grid {
height: 100%;
left: 0;
position: absolute;
top: 1px;
width: 100%;
z-index: -1;
}
.grid-line {
border-bottom: 1px solid lightgray;
font-size: 8px;
height: 9px;
line-height: 20px;
}
Output:
Do you need the x and y for a specific element.
$("#bnElement").offset().left;
$("#bnElement").offset().top;
Just have a look at the following post jQuery x y document coordinates of DOM object
regards
Maybe this can help you. ?!
HTML
<div>
<p>Hello</p>
</div>
<p></p>
CSS
div { padding: 50px;}
p { margin-left:10px; }
JS
var p = $("p:first");
var position = p.position();
$("p:last").text( "left: " + position.left + ", top: " + position.top );
Demo: http://jsfiddle.net/bZezzz/TvMMv/
Using querySelectorAll() method
var domTree = [];
var allelems = document.querySelectorAll(tagsCheck ); // for all tags use --> '*'
for(var i = 0; i < allTags.length; i++){
console.log(i+' '+'Tag : '+ allTags[i].nodeName+'#'+allTags[i].id); // getPath(allTags[i]);
getPosition(allTags[i]);
console.log('Coordinates : {top : '+allTags[i].getBoundingClientRect().top+', left : '+allTags[i].getBoundingClientRect().left+' } ');
console.log('Dimensions offset : {width : '+allTags[i].offsetWidth+', height : '+allTags[i].offsetHeight+' } ');
console.log('Dimensions style Q : {width : '+allTags[i].style.width+', height : '+allTags[i].style.height+' } ');
var singleTag = [];
var jsonData = getTagInfo(allelems[i]); //singleTag.push(getFullXPath(allelems[i]));
singleTag.push(jsonData);
domTree.push(singleTag);
console.log(singleTag);
}
function getTagInfo(element){
return '{ \"Xpath\": \"'+ getFullXPath(element) + '\", \"left\": '+element.getBoundingClientRect().left+',\"top\": '+element.getBoundingClientRect().top+
',\"width\": '+element.offsetWidth+',\"height\" : '+element.offsetHeight+'}';
}
Using getElementsByTagName() and getComputedStyle()
function getElementDimensions(tagsCheck){
var allElem = document.getElementsByTagName('*');
for(i = 0, j = 0; i < allElem.length; i++) {
var elemstyle= window.getComputedStyle(allElem[i], null);
if( tagsCheck.indexOf( allElem[i].tagName ) > -1 ){
console.log(i+' '+'Tag : '+allElem[i].tagName+'[#id : '+allElem[i].id);
console.log('Dimensions style E : {width : '+elemstyle.width+', height : '+elemstyle.height+' } ');
}
}
}
position and XPath of an HTML element
function getPosition(element){
var xPosition = 0;
var yPosition = 0;
while(element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
console.log('GetPosition : {top : '+yPosition+', left : '+xPosition+' } ');
}
I really liked jquery.simulate implementation
function findCorner(elem) {
var offset,
document = $(elem.ownerDocument);
elem = $(elem);
offset = elem.offset();
return {
x: offset.left - document.scrollLeft(),
y: offset.top - document.scrollTop()
};
}
seems to capture a lot of scenarios.
it brings you the position relative to screen.. so if I scrolled, some items may be in negative position. which is useful for automated tests that use drag & drop.
You can easily wrap it with jquery for cool syntax like so
$.fn.findCorner = function(){
if ( this.length > 1 ) {
return this.map(function(){ return findCorner(this); })
} else {
return findCorner(this[0]);
}
};
and so do $('div').findCorner()..

Categories