Image follow the mouse, using mousemove event (using Jquery/Javascript) - javascript

I want the image to follow along with the mouse when the mouse is move but when the mouse has clicked once anywhere the image stops following; it begins following when the mouse has clicked again
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Mousemove">
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
$(document).click(function(e) {
$(".image").mousemove({ top: e.pageY, left: e.pageX });
});
});
</script>
</head>
<body>
<img class="image" src="../images/food%20photgraphy2.jpg" height="50px" width="55px" alt="food">
</body>
</html>
As you can see, when the mouse moves the image doesn't follow along with the mouse and I'm not able to click anywhere. Why is my code not working?

Simply as you can see in this snippet, I add a class once the document clicked and and based on that we change the element position, bind/unbind mousemove event and also remove the added class or not based on alternated click, I think this is what you want:
$(document).ready(function () {
$(this).click(function (e) {
if ($('body').hasClass("clicked")) {
$('body').removeClass("clicked");
$("img").css({ top: 0, left: 0 });
$(this).unbind('mousemove');
} else {
$('body').addClass("clicked");
$(this).mousemove(function (e) {
$("img").css({ top: e.pageY, left: e.pageX });
});
}
});
});
img {
position:absolute
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="http://via.placeholder.com/30x30">
Updated snippet:
$(document).ready(function () {
$(this).mousemove(function (e) {
if (!$('body').hasClass("clicked")) {
$("img").css({ top: e.pageY, left: e.pageX });
}
});
$(this).click(function (e) {
if ($('body').hasClass("clicked")) {
$('body').removeClass("clicked");
//$("img").css({ top: 0, left: 0 });
//$(this).unbind('mousemove');
} else {
$('body').addClass("clicked");
//$(this).mousemove(function (e) {
//$("img").css({ top: e.pageY, left: e.pageX });
//});
}
});
});
img {
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="http://via.placeholder.com/30x30">

Click toggle between events, nest the mousemove in one instance along with addClass('image') and then removeClass('image') in the other.
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
$('#move').clickToggle(function() {
$(this).mousemove(function(e) {
$('.image').css({
'top': e.clientY - 20,
'left': e.clientX - 20
});
});
$('#img').addClass('image');
}, function() {
$('.image').removeClass("image");
});
#img {
position: relative;
z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="move">
<img class="image" src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQXNfNpnfElPqK1QE2BSbDlBd49DQZE-xlNxRlLKQxIscKgIKpP&usqp=CAU" height="50px" width="55px" alt="food" id="img">
<div id="log"></div>
</body>

Related

how to hide loading image after load chart in d3?

$(document).on('click', '.tbtn', function(e) {
$('#loading-image').show();
if(error){
$('loading-image').hide();
else{
val = $('.barbtn input:checked').val();
draw_summary($.parseJSON(data['summary']),val);
draw_barchart($.parseJSON(data['barchart']),val);
draw_scatter($.parseJSON(data['table']),val);
$('#loading-image').show();
}
});
Here i have drawing charts using d3...charts are coming correctly but i need to set loading image when i onclick the button...this code is not working
how to set loading image when onclick the button?
You just need to set CSS for it. Otherwise you are following right path. Please check below snippet.
$(document).on('click', '.tbtn-hide', function(e) {
$('#loading-image').hide(); //hide loader
});
$(document).on('click', '.tbtn-show', function(e) {
$('#loading-image').show(); //show loader
});
#loading-image
{
background: white url("http://smallenvelop.com/demo/simple-pre-loader/images/loader-64x/Preloader_1.gif") no-repeat scroll center center;;
height: 80%;
left: 0;
position: fixed;
top: 10;
width: 100%;
z-index: 9999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="tbtn-hide">Hide</button>
<button class="tbtn-show">show</button>
<div id="loading-image" style="display:none">
</div>
$(document).on('click', '.tbtn', function(e) {
$('#loading-image').show();
$.ajax({
success:function(result){
val = $('.barbtn input:checked').val();
draw_summary($.parseJSON(data['summary']),val);
draw_barchart($.parseJSON(data['barchart']),val);
draw_scatter($.parseJSON(data['table']),val);
$('#loading-image').hide();
}
});
});

How can one append a div exactly in the position where the mouse is over? jQuery

I want to leave a colored div trail without generating divs when the page loads. I want them to be appended when the mouse is over the parent div and position them where the mouse is within it.
EDIT: I think I need to be more precise so I posted the code that I want to rewrite. I want it to do the same thing without generating the divs that become colored on mouseover when the page loads but to create a colored div when the mouse is over $(".container") at the current position of the mouse.
THANKS!
Mention: the script generates lots of divs - it might take a while for the page to load.
$(document).ready( function() {
var csize = $(".container").width() * $(".container").height();
var space = $(window).width() * $(window).height();
while ( csize * $(".container").length < space) {
$("#space").append("<div class='container'></div>");
};
$(document).on("mousemove", function() {
window.color = Math.floor(Math.random()*16777215).toString(16);
});
$(".container").on("mouseover", function() {
$(this).css("background-color", "#" + window.color);
});
});
#space{
width: auto;
height: auto;
}
.container {
width: 15px;
height: 15px;
display: inline-block;
float: left;
border: none;
}
<!DOCTYPE html>
<html>
<head>
<title> JqPractice</title>
<link rel="stylesheet" type="text/css" href="reset.css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="jq.js" type="text/javascript"></script>
<script src="sv2.js" type="text/javascript"></script>
</head>
<body>
<div id="space">
<div class="container">
</div>
</div>
</body>
<footer>
</footer>
</html>
$("#parent").on({
mousemove: function (e) {
var wrapper = $(this);
var parentOffset = wrapper.offset();
var relX = e.pageX - parentOffset.left + wrapper.scrollLeft();
var relY = e.pageY - parentOffset.top + wrapper.scrollTop();
wrapper.find('.randomTrail:visible').remove();
wrapper.append($('<div class="randomTrail"/>').css({
left: relX,
top: relY
}));
},
mouseleave: function () {
$('.randomTrail:visible').remove();
}
});
DEMO
Ref:
.offset()
.scrollLeft()
.scrollTop()
.remove()
e.pageX and e.pageY
.on()
mousemove
mouseleave
Events
find()
You will need to use mousemoves() to get the event data and coordinate like below
$( "#target" ).mousemove(function( event ) {
var msg = "Handler for .mousemove() called at ";
msg += event.pageX + ", " + event.pageY;
console.log(msg);
});
and you will need a div with css {position:absolute; width:10px; height:10px; background-color:yellow; left: event.pageX; top:event.pageY} something like this will do
For more info checkout official doc from jQuery

How to allow text selection in an element that has a canvas overlay (issue with IE9 non-support of pointer-events=none)

I have been looking for a solution for the lack of support for the pointer-events property in IE9/10. There are a couple of other related posts here:
css 'pointer-events' property alternative for IE
How to make Internet Explorer emulate pointer-events:none?.
And I can forward mouse events such as mousedown, up & move. But my real problem is how to get text selection to work - how to be able to select text that are in elements beneath the canvas.
In the example I have below, I use document.elementFromPoint with the coordinates from the event in order to find the element beneath the canvas to forward the event to. But that doesn't work for events such as selectstart because there is no coordinate information in the event. It also doesn't work for mousein/out because those events only fire on the canvas edge. As I said, mousemove works, but working with that event doesn't allow me to select text.
Has anyone found a solution for this, or have suggestions?
<!DOCTYPE html>
<head>
</head>
<body>
<div id="div" style="background-color: pink; width: 500px; height: 500px; position: absolute;">
<span style="background-color: yellow; position: absolute; left: 0px">Test 1</span>
<span style="background-color: red; position: absolute; left: 50px">Test 2</span>
<span style="background-color: blue; position: absolute; left: 100px">Test 3</span>
<span style="background-color: green; position: absolute; left: 150px">Test 4</span>
<span style="background-color: purple; position: absolute; left: 200px">Test 5</span>
<canvas id="canvas" style="background-color: gray; position: absolute; width: 100%; height: 100%; opacity: .5;">The canvas</canvas>
</div>
<script type="text/javascript">
var main = document.getElementById("div");
var canvas = document.getElementById("canvas");
var forwardAnEvent = function(event){
var display = canvas.style.display;
canvas.style.display = "none";
var bottomElement = document.elementFromPoint(event.clientX, event.clientY);
canvas.style.display = display;
var eventCopy = document.createEvent("MouseEvents");
eventCopy.initMouseEvent(event.type, event.bubbles, event.cancelable, event.view, event.detail,
event.pageX || event.layerX, event.pageY || event.layerY, event.clientX, event.clientY, event.ctrlKey, event.altKey,
event.shiftKey, event.metaKey, event.button, event.relatedTarget);
if (bottomElement)
bottomElement.dispatchEvent(eventCopy );
event.stopPropagation();
}
// Set event handlers on the canvas and forward to elements beneath.
// mouseover won't work because when the event happens on the canvas, there
// is nothing else under the mouse except the main div.
// Non-mouse events, such as selectstart, won't work because there is no
// coordinate information in the event to send to document.elementFromPoint.
// How can text selection work for the <span> elements beneath the canvas??
canvas.addEventListener("mouseover", function(event)
{
console.log("mouseover: " + event.target.innerHTML);
forwardAnEvent(event);
event.stopPropagation();
}
, false);
canvas.addEventListener("mousedown", function(event)
{
console.log("mousedown: " + event.target.innerHTML);
forwardAnEvent(event);
event.stopPropagation();
}
, false);
canvas.addEventListener("mouseup", function(event)
{
console.log("mouseup: " + event.target.innerHTML);
forwardAnEvent(event);
event.stopPropagation();
}
, false);
// Set event handlers on all of the <span> elements...
for (var i = 0 ; i < main.children.length; i++)
{
if (main.children[i].tagName == "CANVAS")
{
continue;
}
main.children[i].addEventListener("mouseover", function(event)
{
console.log("mouseover: " + event.target.innerHTML);
event.stopPropagation();
}
, false);
main.children[i].addEventListener("mousedown", function(event)
{
console.log("mousedown: " + event.target.innerHTML);
event.stopPropagation();
}
, false);
main.children[i].addEventListener("mouseup", function(event)
{
console.log("mouseup: " + event.target.innerHTML);
event.stopPropagation();
}
, false);
}
main.addEventListener("mouseover", function(event){
console.log("moving over div.");
event.stopPropagation();
}
, false);
main.addEventListener("mousedown", function(event){
console.log("mousedown div.");
event.stopPropagation();
}
, false);
main.addEventListener("mouseup", function(event){
console.log("mouseup div.");
event.stopPropagation();
}
, false);
</script>
</body>
</html>

Scroll the page vertically and scroll big image inside div horizontally on mouse drag with jQuery

I have page that I want to scroll vertically on event mouse down, and I already have found the answer on this question link. In my case i have a div that contain image that user put on it and sometimes it have bigger size than my div size, with overflow:auto; i get horizontal scroll inside that div. So i need to apply drag scroll horizontally on that div.
HTML
<html>
<body>
<div id="container">
<div class="detail-title"> TITLE </div>
<div class="detail-content">
<img src="...." />
!-- long content --!
</div>
</div>
</body>
</html>
CSS
.detail-main-content-box {
background: none;
display: block;
left: 0;
min-height: 350px;
overflow: auto;
padding: 5px 5px 5px 5px;
width: auto;
}
jQuery from answer link
$(document).on({
'mousemove': function (e) {
clicked && updateScrollPos(e);
},
'mousedown': function (e) {
clicked = true;
clickY = e.pageY;
$('html').addClass('block-selection').css({ 'cursor': 'url(../img/closedhand.cur), default' });
},
'mouseup': function () {
clicked = false;
$('html').removeClass('block-selection').css('cursor', 'auto');
}
});
var updateScrollPos = function(e) {
$(window).scrollTop($(window).scrollTop() + (clickY - e.pageY));
};
how can i apply this on div? i have try to change $(document) to $('.detail-content') also change function scrollTop to scrollLeft but nothing happen. Here is the fiddle for current condition.
this has been left here unanswered for two long years, not even a useful comment. OK, here is my try. hope it can help ( le roi est mort vive le roi)
<script type="text/javascript">
var clicked = true;
var clickY = e.pageY;
$('.detail-content').on({
'mousemove': function (e) {
clicked && updateScrollPos(this,e);
},
'mousedown': function (e) {
clicked = true;
clickY = e.pageY;
$('html').addClass('block-selection').css({ 'cursor': 'grabbing' });
},
'mouseup': function () {
clicked = false;
$('html').removeClass('block-selection').css('cursor', 'auto');
}
});
var updateScrollPos = function(obj,e) {
$(obj).scrollTop($(obj).scrollTop() + (clickY - e.pageY));
clickY = e.pageY;
};
</script>

Sliding a div across to left and the next div appears

I have this form Im creating and when you click on the "Next" button I want to slide the next form() across to the left this is my function
jQuery('input[name^=Next]').click(function () {
current.animate({ marginLeft: -current.width() }, 750);
current = current.next();
});
That function isn't working the way I want to. it slides the text in the container across not the whole container it could be a css problem for all I know.
And my form which has a class name .wikiform doesn't center horizontally. here is my full code. I'm not that experience in javascript so you would be appreciated. cut and paste and try it out
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" />
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" language="javascript" src="Scripts/jquery-1.4.4.js"></script>
<script type="text/javascript" language="javascript" src="Scripts/jquery-easing.1.2.pack.js"></script> <script type="text/javascript" language="javascript">
(function ($) {
$.fn.WikiForm = function (options) {
this.Mode = options.mode || 'CancelOk' || 'Ok' || 'Wizard';
var current = jQuery('.wikiform .view :first');
function positionForm() {
//jQuery('.wikiform').css( {'top':
jQuery('body')
.css('overflow-y', 'hidden');
jQuery('<div id="overlay"></div>')
.insertBefore('.wikiform')
.css('top', jQuery(document).scrollTop())
.animate({ 'opacity': '0.8' }, 'slow');
jQuery('.wikiform')
.css('height', jQuery('.wikiform .wizard .view:first').height() + jQuery('.wikiform .navigation').height())
.css('top', window.screen.availHeight / 2 - jQuery('.wikiform').height() / 2)
.css('width', jQuery('.wikiform .wizard .view:first').width())
.css('left', -jQuery('.wikiform').width())
.animate({ marginLeft: jQuery(document).width() / 2 + jQuery('.wikiform').width() / 2 }, 750);
jQuery('.wikiform .wizard')
.css('overflow', 'hidden')
.css('height', jQuery('.wikiform .wizard .view:first').height() );
}
if (this.Mode == "Wizard") {
return this.each(function () {
var current = jQuery('.wizard .view :first');
var form = jQuery(this);
positionForm();
jQuery('input[name^=Next]').click(function () {
current.animate({ marginLeft: -current.width() }, 750);
current = current.next();
});
jQuery('input[name^=Back]').click(function () {
alert("Back");
});
});
} else if (this.Mode == "CancelOk") {
return this.each(function () {
});
} else {
return this.each(function () {
});
}
};
})(jQuery);
$(document).ready(function () {
jQuery(window).bind("load", function () {
jQuery(".wikiform").WikiForm({ mode: 'Wizard', speed:750, ease:"expoinout" });
});
});
</script>
<style type="text/css">
body
{
margin:0px;
}
#overlay
{
background-color:Black; position:absolute; top:0; left:0; height:100%; width:100%;
}
.wikiform
{
background-color:Green; position:absolute;
}
.wikiform .wizard
{
clear: both;
}
.wizard
{
position: relative;
left: 0; top: 0;
width: 100%;
list-style-type: none;
}
.wizard .view
{
float:left;
}
.view .form
{
}
.navigation
{
float:right; clear:left
}
#view1
{
background-color:Aqua;
width:300px;
height:300px;
}
#view2
{
background-color:Fuchsia;
width:300px;
height:300px;
}
</style>
<title></title>
</head>
<body><form action="" method=""><div id="layout">
<div id="header">
Header
</div>
<div id="content" style="height:2000px">
Content
</div>
<div id="footer">
Footer
</div>
</div>
<div id="formView1" class="wikiform">
<div class="wizard">
<div id="view1" class="view">
<div class="form">
Content 1
</div>
</div>
<div id="view2" class="view">
<div class="form">
Content 2
</div>
</div>
</div>
<div class="navigation">
<input type="button" name="Back" value=" Back " />
<input type="button" name="Next " class="Next" value=" Next " />
<input type="button" name="Cancel" value="Cancel" />
</div>
</div></form></body></html>
Try changing this line:
var current = jQuery('.wizard .view :first');
(which was selecting the form element directly under 'view')
to this:
var current = jQuery('.wizard .view:first');
// The first element with a class of 'view' under an element with a class of
// 'wizard'
Update, due to comments below:
To make a simple scrolling widget, you need the following:
An outer <div> with a fixed width and height
An inner <div> with a fixed height and a very long width.
Code to change the left offset of the inner <div>.
You can see a simple example of a widget like this here: http://jsfiddle.net/andrewwhitaker/feJxu/
For the OP's specific problem, I've modified the code that assigns CSS properties to look like this:
$('.wikiform')
.css('height', $('.wikiform .wizard .view:first').height() + $('.wikiform .navigation').height())
.css('top', window.screen.availHeight / 2 - $('.wikiform').height() / 2)
.css('width', $('.wikiform .wizard .view:first').width())
.css('left', -$('.wikiform').width())
.css('overflow', 'hidden') // ADDED
.animate({marginLeft: $(document).width() / 2 + $('.wikiform').width() / 2
}, 750);
$('.wikiform .wizard')
.css('width', '10000px') // ADDED. May need to be longer depending on content.
.css('height', $('.wikiform .wizard .view:first').height());
I've also changed the animation that 'next' does:
$('input[name^=Next]').click(function() {
$(".wizard").animate({
left: "-=" + current.width() + "px"
}, 750);
}); // Similar logic for 'back'
What this is doing is basically altering the left offset of the view with a huge width (.wizard) and scrolling a new form into the view with a fixed width and height (.wikiform). See a working sample here: http://jsfiddle.net/andrewwhitaker/J9L8s/

Categories