Hello I am trying to set the position of the div on the scroll. This is fiddle . Actually i want to scroll the div on which point i placed my mouse and scroll. On click it is working fine. But on Scroll it is not working.
This is my jquery code
$( '#target' ).on( 'wheel', function( e ) {
var x = e.pageX - this.offsetLeft;
$( "#target1" ).scrollLeft(x);
$( this ).html(x);
});
You cannot get mouse current position on scroll, so I created a global variable to store it xMousePos
, check this fiddle:
var xMousePos = 0; var yMousePos = 0; $("#target1").scroll(function(e) { var tg1 = $(this); var tg = tg1.children(0); var x = xMousePos; //console.log("Scroll:"+xMousePos); $(this).scrollLeft(x); $("#target1").children(0).html(x); }); $("#target1").mousemove(function(event) { xMousePos = event.pageX - this.offsetLeft; yMousePos = event.pageY - this.offsetLeft; })
body { padding: 50px; } #target { background-color: gray; width: 500px; height: 240px; padding-top: 50px; font-size: larger; font-weight: bold; color: white; } #target1 { overflow-x: scroll; width: 300px; height: 300px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="target1"> <div id="target"></div> </div>
On mousewheel, which you are looking for I guess, you have to use event.originalEvent
. Mousewheel and DOMMouseScroll need event.originalEvent
too, since there is no support for wheel event.
use event.originalEvent.pageX
$( '#target' ).on( 'mousewheel', function( e ) { e.preventDefault(); var x = e.originalEvent.pageX - e.target.offsetLeft; $( "#target1" ).scrollLeft(x); console.log(e.originalEvent.pageX, e.target.offsetLeft); $( this ).html(x); }); $( '#target' ).on( 'click', function( e ) { var x = e.pageX - this.offsetLeft; $( "#target1" ).scrollLeft(x); console.log(e.pageX, this.offsetLeft); $( this ).html(x); });
body { padding:50px; } #target { background-color:gray; width:500px; height:240px; padding-top:50px; font-size:larger; font-weight:bold; color:white; } #target1{ overflow-x: scroll; width:300px; height:300px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="target1"> <div id="target"></div> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.