How to make an image stop/start following cursor on click - javascript

I am still very new to jquery and was wondering if anyone could help me with this. I have a small script that detects the position of the cursor and has an image follow it. I am stuck as to how I can get the image to stop/start following if the mouse button is clicked. Could anyone help point me in the write direction?
<!doctype html>
<head>
<title>Follow</title>
<link href="stylesheets/standard.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$("html").mousemove(function (e) {
var xPos = e.pageX;
var yPos = e.pageY;
$("#foxlocation").html("The fox is at: " + xPos + ", " + yPos);
$("#imgFollow").offset({left:e.pageX,top:e.pageY});
});
});
</script>
</head>
<body>
<h1>Test</h1>
<h2 id="foxlocation"></h2>
<img id="imgFollow" width="75px" height="75px" src="images/fox.jpg"></img>
<footer>Test2</footer>
</body>
</html>

$(document).ready(function () {
var init = true;
$(document).on('click', function () {
$(this)[init ? 'on' : 'off']('mousemove', follow);
init = !init;
});
function follow(e) {
var xPos = e.pageX;
var yPos = e.pageY;
$("#foxlocation").html("The fox is at: " + xPos + ", " + yPos);
$("#imgFollow").offset({
left: e.pageX,
top: e.pageY
});
}
});
FIDDLE
EDIT:
To start of with the function initialized, the easiest would be to just trigger a click:
$(document).on('click', function () {
$(this)[init ? 'on' : 'off']('mousemove', follow);
init = !init;
}).trigger('click');
FIDDLE

Here is an example : LIVE EXAMPLE
With my solution, the image is following the mouse directly after the page loading without user interaction
I am using the CSS property
#imgFollow{
position:absolute;
}
And your code except .css() instead of .offset()
$(document).ready(function () {
$(window).mousemove(function (e) {
var xPos = e.pageX;
var yPos = e.pageY;
$("#foxlocation").html("The fox is at: " + xPos + ", " + yPos);
$("#imgFollow").css({
left: e.pageX,
top: e.pageY
});
});
});

Try this!
$(document).ready(function() {
$("html").mousemove(function (e) {
follow(e);
})
.click( function () {
var foo = $.data( this, 'events' ).mousemove;
if(typeof foo = 'function') {
$(this).off('mousemove');
} else {
$(this).mousemove( function (e) {
follow(e);
});
}
});
});
function follow(e){
var xPos = e.pageX;
var yPos = e.pageY;
$("#foxlocation").html("The fox is at: " + xPos + ", " + yPos);
$("#imgFollow").offset({left:e.pageX,top:e.pageY});
}

Related

How to read coordinates of a DIV while it is being dragged ? (Javascript)

I want to read the coordinates of a <div> while it is being dragged and compare it to a static <div> and if at all their positions intersect each other while dragging, it should show some message. I want to accomplish this on web using jquery or javascript. Thanks in advance.
code might be something like this (just a random code)
function onDivDragged(e){
var elemOffset=$("#"+e.target.id).offset();
var elem2Offset=$("#elem2Id").offset();
if(parseInt(elem2Offset.top.replace("px",""))==parseInt(elemOffset.top.replace("px","") && parseInt(elem2Offset.left.replace("px",""))==parseInt(elemOffset.left.replace("px","")))
{
alert("intersection occurred");
}
}
If using jQuery UI is an option then you can use jQuery UI Draggable to achieve this.
Further details are available here http://jqueryui.com/draggable/#events
During drag event get cordinates of div getting dragged and compare it to the static div and compute intersection.
use below javascript code to get the coordinate position of the element
var elemant = document.getElementById('elementID'),
left = element.offsetLeft, // returns X coords
top = element.offsetTop; // returns Y coords
You can use "ondragover" event instead of manually checking coordinates.
http://www.w3schools.com/html/html5_draganddrop.asp
You can get offset of any element using jquery.
var offset = $("#some-element").offset();
// log the values
console.log("top: " + offset.top+ "left: " + offset.left);
try this code.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="http://jqueryui.com/jquery-wp-content/themes/jquery/css/base.css?v=1">
<style>
#myDiv
{
width: 20px;
height: 20px;
background-color: Red;
}
</style>
<script>
$(document).ready(function () {
$("#myDiv").draggable({
start: function (e, ui) {
var parentOffset = $(this).parent().offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
$("#start").html(" x: " + relX + ", y: " + relY);
},
stop: function (e, ui) {
var parentOffset = $(this).parent().offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
$("#end").html(" x: " + relX + ", y: " + relY);
},
drag: function (e, ui) {
var parentOffset = $(this).parent().offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
$("#current").html(" x: " + relX + ", y: " + relY);
}
});
});
</script>
</head>
<body>
start Position:<span id="start"></span>
<br />
End Position:<span id="end"></span>
<br />
Dragging Position<span id="current"></span>
<div id="myDiv">
</div>
</body>
</html>

Having issues with mousemove and images in Jquery

How can I make the other images also follow the mouse? Not all at the same time, but when I click on the selected image.
How can I calculate the distance where the mouse moved when I click on the image?
See link below.
HTML:
<div id="squarelocation"></div>
<div class="square 1">1</div>
<div class="square 2">2</div>
<div class="square 3">3</div>
Jquery:
$(document).ready(function () {
var i = true;
$(document).on('click', function () {
$(this)[i ? 'on' : 'off']('mousemove', follow);
i = !i;
});
function follow(e) {
var xPos = e.pageX;
var yPos = e.pageY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$(".2").offset({
left: e.pageX,
top: e.pageY
});
}
});
I suggest you to bind a click event to the square class like this:
var clickedImage;
$('.square').click(function (e){
initialX = e.pageX;
initialY = e.pageY;
clickedImage = this;
});
and assign the context to a variable, so that you can refer to it whenever you needed. And then in your code, refer to that context instead of the hardcoded '.2':
$(clickedImage).offset({
left: e.pageX,
top: e.pageY
});
This way, the image clicked will be referred to, instead of just '2' following the mouse all the time.
Same for calculating the distance between the clicked origin and the current position, you can save the original spot on clicking the image:
var initialX;
var initialY;
$('.square').click(function (e){
initialX = e.pageX;
initialY = e.pageY;
clickedImage = this;
});
and do the calculation in the 'follow' function, of course how the calculation should be is up to you, but here is an example:
var distanceX = xPos - initialX;
var distanceY = yPos - initialY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$('#squaredistance').html("Distance from origin: " + distanceX + ", " + distanceY);
Hope this help. jsfiddle: http://jsfiddle.net/FW9jV/1/
You could add an 'active' class for the active square. I added an example.
The active square will always be moving until you click to deactivate it.
http://jsfiddle.net/fG6kr/1/
$(document).ready(function () {
var i = true;
$('.square').on('click', function () {
if( $(this).hasClass("active"))
{
$(this).removeClass("active");
$(document).off('mousemove');
}
else
{
$(this).addClass("active");
$(document).on('mousemove', follow);
}
});
function follow(e) {
var xPos = e.pageX;
var yPos = e.pageY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$('.active').offset({
left: e.pageX,
top: e.pageY
});
}
});
demo
$(function() {
$('.square').click(function(){
$(this).toggleClass('sel');
});
$(document).on('mousemove', function(e){
$(".sel").offset({left: e.pageX+10, top: e.pageY+10});
});
});

Unable to drop an element on mouseup event

Here is the jQuery code that I have written to drag multiple items at a time. It is draggable now but not droppable.
here is the code
$(document).on('click', function (e) {
var target = e.target;
if (!$(target).hasClass('a')) $('.selected').removeClass('selected');
});
$(document).delegate('.a', 'dblclick', function (e) {
$(this).addClass('selected');
});
$(document).delegate('.selected', 'mousedown', function (e) {
var div = $('<div></div>');
$('.selected').each(function () {
div.append($(this).clone());
});
div.prop('id', 'currentDrag');
$('#currentDrag').css({
left: e.pageX + "px",
top: e.pageY + "px"
});
$('body').append(div);
});
$(document).on('mouseup', function (e) {
var tgt = e.target;
var mPos = {
x: e.pageX,
y: e.pageY
};
$('.drop').each(function () {
var pos = $(this).offset(),
twt = $(this).width(),
tht = $(this).height();
});
if((mPos.x > pos.left) && (mPos.x < (pos.left + twt)) && (mPos.y > targPos.top) && (mPos.y < (pos.top + tht))) {
$(this).append($('#currentDrag').html());
}
$('.drop .selected').removeClass('selected');
$('#currentDrag').remove();
});
$('.drop').on('mouseup', function (e) {
$(tgt).append($('#currentDrag').html());
$('.drop .selected').removeClass('selected');
$('#currentDrag').remove();
});
$(document).on('mousemove', function (e) {
$('#currentDrag').css({
left: e.pageX + "px",
top: e.pageY + "px"
});
});
What is the pronblem with my code and how can I achieve this. here is the fiddle http://jsfiddle.net/mDewr/27/
I would really recommend trying to find a way to make the jQuery UI draggable and droppable libraries work for you. Then the question becomes,
similar to this one: How do I drag multiple elements with JavaScript or jQuery?.
Here's how we can apply one of the answers from that question to your problem. I'm using the jQuery UI multiple draggable plugin, the entire script of which can be found here: jquery.ui.multidraggable-1.8.8.js.
First let's simplify your HTML. By putting our draggable and dropable divs inside of elements, we don't have to apply redundant stylings to each one. Instead we can use the containing element to style
HTML
<div id="parent">
<div id="dragTargets">
<div>123</div>
<div>456</div>
<div>789</div>
</div>
<div id='dropTargets'>
<div></div>
<div></div>
</div>
</div>
Using the plugin we can call multidraggable on each of the drag divs. And droppable anywhere they can be dropped
JavaScript
$("#dragTargets div").multidraggable();
$("#dropTargets div").droppable();
Customize
We can control the appearance with styling. As an example, we'll make anything that can receive drops yellow, anything you're about to drop as red, and anything that has received an element green.
Here's some styling as an example in CSS
.ui-state-highlight { background: green; }
.ui-state-active { background: yellow; }
.ui-state-hover { background: red; }
And we'll control when these classes are applied with JavaScript:
$("#dropTargets div").droppable({
activeClass: "ui-state-active",
hoverClass: "ui-state-hover",
drop: function () {
$(this).addClass("ui-state-highlight")
}
});
Multi-Draggable
You should style the elements that are currently selected. The script will apply the class ui-multidraggable to all the currently selected elements. The following CSS will make it apparent to the user that their choice is selected.
.ui-multidraggable {
background: tan;
}
Check out this demo. Just hold down ctrl to select more than one of the divs and then drag all of them at once.
jsFiddle
There are few errors in you code. You can check errors on browser console.
To check elements over droppable area, you should check the drop area in the each loop, rather than after each loop. When moving mouse, you should better turn off selection to avoid selected text flashing
$(document).on('click', '.a', function (e) {
$(this).removeClass('selected');
});
$(document).on('dblclick', '.a', function (e) {
$(this).toggleClass('selected');
});
$(document).on('mousedown', '.selected', function (e) {
var dragMode = true;
var div = $('<div></div>');
$('.selected').each(function () {
div.append($(this).clone());
});
div.prop('id', 'currentDrag');
$('#currentDrag').css({
left: e.pageX + "px",
top: e.pageY + "px"
});
$('body').append(div);
//disable selection on dropping start
disableSelection();
$(document).on('mousemove.drop', function(e){
onDragging(e, dragMode);
});
$(document).on('mouseup.drop', function(e){
onDragEnd(e, dragMode);
});
});
function onDragEnd(e, dragMode){
if(!dragMode)
return;
var tgt = e.target;
var mPos = {
x: e.pageX,
y: e.pageY
};
$('.drop').each(function () {
var pos = $(this).position(),
twt = $(this).width(),
tht = $(this).height();
if((mPos.x > pos.left) &&
(mPos.x < (pos.left + twt)) &&
(mPos.y > pos.top) &&
(mPos.y < (pos.top + tht))) {
$(this).append($('#currentDrag').html());
}
});
$('.drop .selected').removeClass('selected');
$('#currentDrag').remove();
$('.onDrop').removeClass('onDrop');
//remove listener on docuemnt when drop end
$(document).off('mousemove.drop');
$(document).off('mouseup.drop');
//enable selection
enableSelection();
}
function onDragging(e, dragMode){
if(!dragMode)
return;
var p = $('body').offset();
var mPos = {
x: e.pageX,
y: e.pageY
};
$('#currentDrag').css({
left: mPos.x,
top: mPos.y
});
$('.drop').each(function () {
var pos = $(this).position(),
twt = $(this).width(),
tht = $(this).height();
$(this).toggleClass("onDrop",
(mPos.x > pos.left)
&& (mPos.x < (pos.left + twt))
&& (mPos.y > pos.top)
&& (mPos.y < (pos.top + tht))
);
});
}
function disableSelection(){
$(document).on("selectstart", function(){ return false; });
//firefox
$("body").css("-moz-user-select", "none");
}
function enableSelection(){
$(document).off("selectstart");
//firefox
$("body").css("-moz-user-select", "");
}
I updated your code: http://jsfiddle.net/mDewr/46/, may can help you.
There were several errors, which I'll not list now, but you can compare the old version with the new one.
$(document).on('dblclick', '.a', function (e) {
$(this).toggleClass('selected');
});
$(document).on('mousedown', '.selected', function (e) {
var div = $('<div id="currentDrag"></div>');
$('.selected').each(function () {
div.append($(this).clone(true));
});
var p = $('body').offset();
var l = e.pageX - p.left;
var t = e.pageY - p.top;
console.log(l, ', ', t);
$('body').append(div);
$('#currentDrag').css({
left: l,
top: t
});
});
$(document).on('mouseup', '.selected', function (e) {
$('.d').each(function(index, item){
var $i = $(item);
if (e.pageX >= $i.offset().left &&
e.pageX <= $i.offset().left + $i.width() &&
e.pageY >= $i.offset().top &&
e.pageY <= $i.offset().top + $i.height()) {
console.log('Dropped');
var $cl = $('#currentDrag').find('>*').clone(true);
$i.append($cl);
}
});
$('.selected').removeClass('selected');
$('#currentDrag').remove();
});
$(document).on('mousemove', function (e) {
var p = $('body').offset();
$('#currentDrag').css({
left: e.pageX - p.left,
top: e.pageY - p.top
});
});
http://jsfiddle.net/mDewr/43/
Everything should work perfectly in this version (this is an update).
PS: I've changed to 1.7+ jQuery, but you can easily change it back to <1.7. Also you don't need custom attributes, use css classes instead.

Disabling default tooltip

Here's a tooltip script, http://www.alessioatzeni.com/blog/simple-tooltip-with-jquery-only-text/. It works great in all the browsers but the default tooltip isn't disabled in IE.
How can i update the following script to disable the default tooltip?
<script type="text/javascript">
$(document).ready(function() {
// Tooltip only Text
$('.masterTooltip').hover(function(){
// Hover over code
var title = $(this).attr('title');
$(this).data('tipText', title).removeAttr('title');
$('<p class="tooltip"></p>').text(title).appendTo('body').fadeIn('slow');
}, function() {
// Hover out code
$(this).attr('title', $(this).data('tipText'));
$('.tooltip').remove();
}).mousemove(function(e) {
var mousex = e.pageX + 20; //Get X coordinates
var mousey = e.pageY + 10; //Get Y coordinates
$('.tooltip').css({ top: mousey, left: mousex })
});
});
</script>
I don't see any reason to add the title attribute back in to the element on blur. You have it stored in the jQuery metadata. My guess is that is why IE is still showing it. Remove the line
$(this).attr('title', $(this).data('tipText'));
and see if that fixes it.
EDIT: That missed some requirements. This is untested, but might work:
$(document).ready(function() {
$('.masterTooltip').each(function() {
var title = $(this).attr('title');
$(this).data('tipText', title).removeAttr('title');
}).hover(function(){
$('<p class="tooltip"></p>')
.text($(this).data('tipText'))
.appendTo('body')
.fadeIn('slow');
}, function() {
$('.tooltip').remove();
}).mousemove(function(e) {
var mousex = e.pageX + 20;
var mousey = e.pageY + 10;
$('.tooltip')
.css({ top: mousey, left: mousex })
});
});
Note that this is sub-optimal, as it calls $(this) twice in the each block, but that should be easy enough to fix.
I have simple solution to disable the default tooltip which is shown in left/right bottom side of the IE or other browser. [If your default tooltip is same as I mentioned]
Just write a simple javascript function
function GoToLink()
{
location.href = "mypage.htm";
}
call this function in tag like
<a id="204" name="wow" class="SettPage" href="" onclick="GoToLink()">

Using jQuery how to get click coordinates on the target element

I have the following event handler for my html element
jQuery("#seek-bar").click(function(e){
var x = e.pageX - e.target.offsetLeft;
alert(x);
});
I need to find the position of the mouse on the #seek-bar at the time of clicking. I would have thought the above code should work, but it gives incorrect result
Are you trying to get the position of mouse pointer relative to element ( or ) simply the mouse pointer location
Try this Demo : http://jsfiddle.net/AMsK9/
Edit :
1) event.pageX, event.pageY gives you the mouse position relative document !
Ref : http://api.jquery.com/event.pageX/
http://api.jquery.com/event.pageY/
2) offset() : It gives the offset position of an element
Ref : http://api.jquery.com/offset/
3) position() : It gives you the relative Position of an element i.e.,
consider an element is embedded inside another element
example :
<div id="imParent">
<div id="imchild" />
</div>
Ref : http://api.jquery.com/position/
HTML
<body>
<div id="A" style="left:100px;"> Default <br /> mouse<br/>position </div>
<div id="B" style="left:300px;"> offset() <br /> mouse<br/>position </div>
<div id="C" style="left:500px;"> position() <br /> mouse<br/>position </div>
</body>
JavaScript
$(document).ready(function (e) {
$('#A').click(function (e) { //Default mouse Position
alert(e.pageX + ' , ' + e.pageY);
});
$('#B').click(function (e) { //Offset mouse Position
var posX = $(this).offset().left,
posY = $(this).offset().top;
alert((e.pageX - posX) + ' , ' + (e.pageY - posY));
});
$('#C').click(function (e) { //Relative ( to its parent) mouse position
var posX = $(this).position().left,
posY = $(this).position().top;
alert((e.pageX - posX) + ' , ' + (e.pageY - posY));
});
});
$('#something').click(function (e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
console.log(xPos, yPos);
});
Try this:
jQuery(document).ready(function(){
$("#special").click(function(e){
$('#status2').html(e.pageX +', '+ e.pageY);
});
})
Here you can find more info with DEMO
In percentage :
$('.your-class').click(function (e){
var $this = $(this); // or use $(e.target) in some cases;
var offset = $this.offset();
var width = $this.width();
var height = $this.height();
var posX = offset.left;
var posY = offset.top;
var x = e.pageX-posX;
x = parseInt(x/width*100,10);
x = x<0?0:x;
x = x>100?100:x;
var y = e.pageY-posY;
y = parseInt(y/height*100,10);
y = y<0?0:y;
y = y>100?100:y;
console.log(x+'% '+y+'%');
});
If MouseEvent.offsetX is supported by your browser (all major browsers actually support it), The jQuery Event object will contain this property.
The MouseEvent.offsetX read-only property provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.
$("#seek-bar").click(function(event) {
var x = event.offsetX
alert(x);
});
see here enter link description here
html
<body>
<p>This is a paragraph.</p>
<div id="myPosition">
</div>
</body>
css
#myPosition{
background-color:red;
height:200px;
width:200px;
}
jquery
$(document).ready(function(){
$("#myPosition").click(function(e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
alert("X position: " + xPos + ", Y position: " + yPos);
});
});

Categories