Is there a simple way to locate all DOM elements that "cover" (that is, have within its boundaries) a pixel with X/Y coordinate pair?
You can have a look at document.elementFromPoint though I don't know which browsers support it.
Firefox and Chrome do. It is also in the MSDN, but I am not so familiar with this documentation so I don't know in which IE version it is included.
Update:
To find all elements that are somehow at this position, you could make the assumption that also all elements of the parent are at this position. Of course this does not work with absolute positioned elements.
elementFromPoint will only give you the most front element. To really find the others you would have to set the display of the front most element to none and then run the function again. But the user would probably notice this. You'd have to try.
I couldn't stop myself to jump on Felix Kling's answer:
var $info = $('<div>', {
css: {
position: 'fixed',
top: '0px',
left: '0px',
opacity: 0.77,
width: '200px',
height: '200px',
backgroundColor: '#B4DA55',
border: '2px solid black'
}
}).prependTo(document.body);
$(window).bind('mousemove', function(e) {
var ele = document.elementFromPoint(e.pageX, e.pageY);
ele && $info.html('NodeType: ' + ele.nodeType + '<br>nodeName: ' + ele.nodeName + '<br>Content: ' + ele.textContent.slice(0,20));
});
updated: background-color !
This does the job (fiddle):
$(document).click(function(e) {
var hitElements = getHitElements(e);
});
var getHitElements = function(e) {
var x = e.pageX;
var y = e.pageY;
var hitElements = [];
$(':visible').each(function() {
var offset = $(this).offset();
if (offset.left < x && (offset.left + $(this).outerWidth() > x) && (offset.top < y && (offset.top + $(this).outerHeight() > y))) {
hitElements.push($(this));
}
});
return hitElements;
}
When using :visible, you should be aware of this:
Elements with visibility: hidden or opacity: 0 are considered visible,
since they still consume space in the layout. During animations that
hide an element, the element is considered to be visible until the end
of the animation. During animations to show an element, the element is
considered to be visible at the start at the animation.
So, based on your need, you would want to exclude the visibility:hidden and opacity:0 elements.
Related
I have the following div floating but I want as the green element inside left panel to have a delay about half second.
Does anyone any idea how can I do this?
https://jsfiddle.net/eoopvgmc/22/
This is the code which is floating the elements on scroll
$(document).ready(function() {
var offset = $('.ads').offset().top, top;
$(document).on('scroll', function() {
top = $(window).scrollTop() < offset ? '0' : $(window).scrollTop() - offset + 'px';
$('.ads').css({
'top': top
});
})
});
To make the .element independent transition, you need to move it out of the .left-zone element.
$(document).ready(function () {
var offset = $('.ads').offset().top,
top;
$(document).on('scroll', function () {
top = $(window).scrollTop() < offset ? '0' : $(window).scrollTop() - offset;
console.log(top);
$('.ads').css({
'top': top
});
$('.element').css({
'top': +top + 50
});
})
});
Working Fiddle
I managed to get something like what you describe working by adding some transition effects to the element and using a little delay, you should be able to tweak the timeout, margin-top and transition values to get exactly what you want:
$(document).ready(function() {
var offset = $('.ads').offset().top, top;
$(document).on('scroll', function() {
top = $(window).scrollTop() < offset ? '0' : $(window).scrollTop() - offset + 'px';
$('.ads .element').css({
'transition': 'none',
'margin-top': '-60px'
});
$('.ads').css({
'top': top
});
setTimeout(function() {
$('.ads .element').css({
'transition': 'margin-top 3s',
'margin-top': '0'
});
});
})
});
Fiddle: https://jsfiddle.net/yckszc16/
Since the element is absolute positioned, I took it that it does not need to be nested within the div. Therefore I changed the HTML from this:
<div class="left-zone ads">
<div class="element"></div>
</div>
to this:
<div class="left-zone ads"></div>
<div class="element"></div>
I then adjusted the css to position the element in the same place as it was, like so:
.element{
position: absolute;
top: 60px;
left: -71px;
width: 20px;
height: 30px;
background: green;
}
This allows the object to be manipulated completely seperately to the parent, which also makes it much more flexible in what you can do with it.
To get the animation going on it, I had to change a few bits of code.
Where you were setting the top variable, I removed the + 'px' at the end to allow for the setting of different values in each animation. This is required because the element must have it's top value (60px in this case) added to the animation to keep it in the correct position. I then copied the code that sets the animation going and repeated it for the 'element' div, and added the 60px to it. if that doesn't make sense then check out the code below.
$(document).on('scroll', function() {
top = $(window).scrollTop() < offset ? '0' : $(window).scrollTop() - offset;
$('.ads').css({
'top': top + 'px'
});
$('.element').css({
'top': top + 60 + 'px'
});
})
Next is to get the delay. I first tried the jquery .delay function but it didn't seem to work so I made an even simpler change, add the transition line from your 'ads' div to the 'element' div's css and change the duration to half a second longer. This achieves the required effect of it coming in afterwards! Here is the code:
.element{
position: absolute;
top: 60px;
left: -71px;
width: 20px;
height: 30px;
background: green;
transition: top 1.3s;
}
Here is a jsfiddle if you want to see it in action: https://jsfiddle.net/hdn1oyjd/
Let me know if you have any questions!
I have this event:
$(window).scroll(function(e){
console.log(e);
})
I want to know, how much I have scroll value in pixels, because I think, scroll value depends from window size and screen resolution.
Function parameter e does not contains this information.
I can store $(window).scrollTop() after every scroll and calculate difference, but can I do it differently?
The "scroll value" does not depend on the window size or screen resolution. The "scroll value" is simply the number of pixels scrolled.
However, whether you are able to scroll at all, and the amount you can scroll is based on available real estate for the container and the dimensions of the content within the container (in this case the container is document.documentElement, or document.body for older browsers).
You are correct that the scroll event does not contain this information. It does not provide a delta property to indicate the number of pixels scrolled. This is true for the native scroll event and the jQuery scroll event. This seems like it would be a useful feature to have, similar to how mousewheel events provide properties for X and Y delta.
I do not know, and will not speculate upon, why the powers-that-be did not provide a delta property for scroll, but that is out of scope for this question (feel free to post a separate question about this).
The method you are using of storing scrollTop in a variable and comparing it to the current scrollTop is the best (and only) method I have found. However, you can simplify this a bit by extending jQuery to provide a new custom event, per this article: http://learn.jquery.com/events/event-extensions/
Here is an example extension I created that works with window / document scrolling. It is a custom event called scrolldelta that automatically tracks the X and Y delta (as scrollLeftDelta and scrollTopDelta, respectively). I have not tried it with other elements; leaving this as exercise for the reader. This works in currrent versions of Chrome and Firefox. It uses the trick for getting the sum of document.documentElement.scrollTop and document.body.scrollTop to handle the bug where Chrome updates body.scrollTop instead of documentElement.scrollTop (IE and FF update documentElement.scrollTop; see https://code.google.com/p/chromium/issues/detail?id=2891).
JSFiddle demo: http://jsfiddle.net/tew9zxc1/
Runnable Snippet (scroll down and click Run code snippet):
// custom 'scrolldelta' event extends 'scroll' event
jQuery.event.special.scrolldelta = {
delegateType: "scroll",
bindType: "scroll",
handle: function (event) {
var handleObj = event.handleObj;
var targetData = jQuery.data(event.target);
var ret = null;
var elem = event.target;
var isDoc = elem === document;
var oldTop = targetData.top || 0;
var oldLeft = targetData.left || 0;
targetData.top = isDoc ? elem.documentElement.scrollTop + elem.body.scrollTop : elem.scrollTop;
targetData.left = isDoc ? elem.documentElement.scrollLeft + elem.body.scrollLeft : elem.scrollLeft;
event.scrollTopDelta = targetData.top - oldTop;
event.scrollTop = targetData.top;
event.scrollLeftDelta = targetData.left - oldLeft;
event.scrollLeft = targetData.left;
event.type = handleObj.origType;
ret = handleObj.handler.apply(this, arguments);
event.type = handleObj.type;
return ret;
}
};
// bind to custom 'scrolldelta' event
$(window).on('scrolldelta', function (e) {
var top = e.scrollTop;
var topDelta = e.scrollTopDelta;
var left = e.scrollLeft;
var leftDelta = e.scrollLeftDelta;
// do stuff with the above info; for now just display it to user
var feedbackText = 'scrollTop: ' + top.toString() + 'px (' + (topDelta >= 0 ? '+' : '') + topDelta.toString() + 'px), scrollLeft: ' + left.toString() + 'px (' + (leftDelta >= 0 ? '+' : '') + leftDelta.toString() + 'px)';
document.getElementById('feedback').innerHTML = feedbackText;
});
#content {
/* make window tall enough for vertical scroll */
height: 2000px;
/* make window wide enough for horizontal scroll */
width: 2000px;
/* visualization of scrollable content */
background-color: blue;
}
#feedback {
border:2px solid red;
padding: 4px;
color: black;
position: fixed;
top: 0;
height: 20px;
background-color: #fff;
font-family:'Segoe UI', 'Arial';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='feedback'>scrollTop: 0px, scrollLeft: 0px</div>
<div id='content'></div>
Note that you may want debounce the event depending on what you are doing. You didn't provide very much context in your question, but if you give a better example of what you are actually using this info for we can provide a better answer. (Please show more of your code, and how you are using the "scroll value").
To detemine how many pixels were scrolled you have to keep in mind that the scroll event gets fired almost every pixel that you move. The way to accomplish it is to save the previous scrolled value and compare that in a timeout. Like this:
var scrollValue = 0;
var scrollTimeout = false
$(window).scroll(function(event){
/* Clear it so the function only triggers when scroll events have stopped firing*/
clearTimeout(scrollTimeout);
/* Set it so it fires after a second, but gets cleared after a new triggered event*/
scrollTimeout = setTimeout(function(){
var scrolled = $(document).scrollTop() - scrollValue;
scrollValue = $(document).scrollTop();
alert("The value scrolled was " + scrolled);
}, 1000);
});
This way you will get the amount of scrolled a second after scrolling (this is adjustable but you have to keep in mind that the smooth scrolling that is so prevalent today has some run-out time and you dont want to trigger before a full stop).
The other way to do this? Yes, possible, with jQuery Mobile
I do not appreciate this solution, because it is necessary to include heavy jQuery mobile. Solution:
var diff, top = 0;
$(document).on("scrollstart",function () {
// event fired when scrolling is started
top = $(window).scrollTop();
});
$(document).on("scrollstop",function () {
// event fired when scrolling is stopped
diff = Math.abs($(window).scrollTop() - top);
});
To reduce the used processing power by adding a timer to a Jquery scroll method is probably not a great idea. The visual effect is indeed quite bad.
The whole web browsing experience could be made much better by hiding the scrolling element just when the scroll begins and making it slide in (at the right position) some time after. The scrolling even can be checked with a delay too.
This solution works great.
$(document).ready(function() {
var element = $('.movable_div'),
originalY = element.offset().top;
element.css('position', 'relative');
$(window).on('scroll', function(event) {
var scrollTop = $(window).scrollTop();
element.hide();
element.stop(false, false).animate({
top: scrollTop < originalY
? 0
: scrollTop - originalY + 35
}, 2000,function(){element.slideDown(500,"swing");});
});
});
Live demo here
I am trying to incrementally reposition an element by setting the -webkit-transform property to +=200px
But it doesn't work. I'm missing something, but don't know what.
http://jsfiddle.net/yVSDC/
Clicking the div is supposed to move it further down by 200px everytime.
CSS doesn't work like that, and jQuery doesn't pull that data out so you can do it like that.
You'd need to read the value, add 200 and then reset it.
var getTranslatedY = function (element) {
var transform = element.css("transform") || element.css("-webkit-transform") || element.css("-moz-transform");
if (transform == "none") {
return 0;
}
return parseInt((transform.match(/^matrix\(.*?(-?[\d.]+)\)$/) || [])[1]) || 0;
};
$('#m').on(
'click',
function () {
var element = $(this);
element
.css('-webkit-transform',
"translateY(" + (getTranslatedY(element) + 200) + "px)");
});
jsFiddle.
var step = 200;
$('body').on('click', "#m", function(){
$(this).css('-webkit-transform','translateY('+ step +'px)');
step = step+200;
});
And instead -webkit-transform:translateY(100px); in CSS you can set margin-top: 100px;
http://jsfiddle.net/yVSDC/28/
You have to get the Current webkit-transform value and increment it. Alternative Solution is ustin the top CSS Property
You can try this (it's free): http://ricostacruz.com/jquery.transit/
Sample Code:
$('.box').transition({ x: '200px' });
$('.box').transition({ y: '200px' });
$('.box').transition({ x: '200px', y: '200px' });
Usually I prefer to write my own solutions for trivial problems because generally plugins add a lot of unneeded functionality and increase your project in size. Size makes a page slower and a 30k difference (compared to jquery draggable) in a 100k pageviews / day website makes a big difference in the bill. I already use jquery and I think that's all I need for now, so please, don't tell me to use another plugin or framework to drag things around.
Whit that in mind I wrote the following code, to allow a box to be draggable around. The code works just fine (any tip about the code itself will be great appreciate), but I got a small little glitch.
When I drag the box to the browser right edge limit, a horizontal scroll bar appears, the window width gets bigger because of the box. The desirable behavior is to see no horizontal scroll bar, but allow to put part of the box outside the window area, like a windows window do.
Any tips?
CSS:
.draggable {
position: absolute;
cursor: move;
border: 1px solid black;
}
Javascript:
$(document).ready(function() {
var x = 0;
var y = 0;
$("#d").live("mousedown", function() {
var element = $(this);
$(document).mousemove(function(e) {
var x_movement = 0;
var y_movement = 0;
if (x == e.pageX || x == 0) {
x = e.pageX;
} else {
x_movement = e.pageX - x;
x = e.pageX;
}
if (y == e.pageY || y == 0) {
y = e.pageY;
} else {
y_movement = e.pageY - y;
y = e.pageY;
}
var left = parseFloat(element.css("left")) + x_movement;
element.css("left", left);
var top = parseFloat(element.css("top")) + y_movement;
element.css("top", top);
return false;
});
});
$(document).mouseup(function() {
x = 0;
y = 0;
$(document).unbind("mousemove");
});
});
HTML:
<div id="d" style="width: 100px; left: 0px; height: 100px; top: 0px;" class="draggable">a</div>
For a simple solution, you could just add some CSS to the draggable object's container to prevent the scrollbars.
body { overflow: hidden; }
jsFiddle: http://jsfiddle.net/F894P/
Instead of this :
$("#d").live("mousedown", function () {
// your code here
}); // live
try this :
$("body").on("mousedown","#d", function(){
// your code here
$("#parent_container").css({"overflow-x":"hidden"});
// or $("body").css({"overflow-x":"hidden"});
}); // on
Where #parent_container is where your draggable object is.
You should be using jQuery 1.7+
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
I have an HTML document with images in a grid format using <ul><li><img.... The browser window has both vertical & horizontal scrolling.
Question:
When I click on an image <img>, how then do I get the whole document to scroll to a position where the image I just clicked on is top:20px; left:20px ?
I've had a browse on here for similar posts...although I'm quite new to JavaScript, and want to understand how this is achieved for myself.
There's a DOM method called scrollIntoView, which is supported by all major browsers, that will align an element with the top/left of the viewport (or as close as possible).
$("#myImage")[0].scrollIntoView();
On supported browsers, you can provide options:
$("#myImage")[0].scrollIntoView({
behavior: "smooth", // or "auto" or "instant"
block: "start" // or "end"
});
Alternatively, if all the elements have unique IDs, you can just change the hash property of the location object for back/forward button support:
$(document).delegate("img", function (e) {
if (e.target.id)
window.location.hash = e.target.id;
});
After that, just adjust the scrollTop/scrollLeft properties by -20:
document.body.scrollLeft -= 20;
document.body.scrollTop -= 20;
Since you want to know how it works, I'll explain it step-by-step.
First you want to bind a function as the image's click handler:
$('#someImage').click(function () {
// Code to do scrolling happens here
});
That will apply the click handler to an image with id="someImage". If you want to do this to all images, replace '#someImage' with 'img'.
Now for the actual scrolling code:
Get the image offsets (relative to the document):
var offset = $(this).offset(); // Contains .top and .left
Subtract 20 from top and left:
offset.left -= 20;
offset.top -= 20;
Now animate the scroll-top and scroll-left CSS properties of <body> and <html>:
$('html, body').animate({
scrollTop: offset.top,
scrollLeft: offset.left
});
Simplest solution I have seen
var offset = $("#target-element").offset();
$('html, body').animate({
scrollTop: offset.top,
scrollLeft: offset.left
}, 1000);
Tutorial Here
There are methods to scroll element directly into the view, but if you want to scroll to a point relative from an element, you have to do it manually:
Inside the click handler, get the position of the element relative to the document, subtract 20 and use window.scrollTo:
var pos = $(this).offset();
var top = pos.top - 20;
var left = pos.left - 20;
window.scrollTo((left < 0 ? 0 : left), (top < 0 ? 0 : top));
Have a look at the jQuery.scrollTo plugin. Here's a demo.
This plugin has a lot of options that go beyond what native scrollIntoView offers you. For instance, you can set the scrolling to be smooth, and then set a callback for when the scrolling finishes.
You can also have a look at all the JQuery plugins tagged with "scroll".
Here's a quick jQuery plugin to map the built in browser functionality nicely:
$.fn.ensureVisible = function () { $(this).each(function () { $(this)[0].scrollIntoView(); }); };
...
$('.my-elements').ensureVisible();
After trial and error I came up with this function, works with iframe too.
function bringElIntoView(el) {
var elOffset = el.offset();
var $window = $(window);
var windowScrollBottom = $window.scrollTop() + $window.height();
var scrollToPos = -1;
if (elOffset.top < $window.scrollTop()) // element is hidden in the top
scrollToPos = elOffset.top;
else if (elOffset.top + el.height() > windowScrollBottom) // element is hidden in the bottom
scrollToPos = $window.scrollTop() + (elOffset.top + el.height() - windowScrollBottom);
if (scrollToPos !== -1)
$('html, body').animate({ scrollTop: scrollToPos });
}
My UI has a vertical scrolling list of thumbs within a thumbbar
The goal was to make the current thumb right in the center of the thumbbar.
I started from the approved answer, but found that there were a few tweaks to truly center the current thumb. hope this helps someone else.
markup:
<ul id='thumbbar'>
<li id='thumbbar-123'></li>
<li id='thumbbar-124'></li>
<li id='thumbbar-125'></li>
</ul>
jquery:
// scroll the current thumb bar thumb into view
heightbar = $('#thumbbar').height();
heightthumb = $('#thumbbar-' + pageid).height();
offsetbar = $('#thumbbar').scrollTop();
$('#thumbbar').animate({
scrollTop: offsetthumb.top - heightbar / 2 - offsetbar - 20
});
Just a tip. Works on firefox only
Element.scrollIntoView();
Simple 2 steps for scrolling down to end or bottom.
Step1: get the full height of scrollable(conversation) div.
Step2: apply scrollTop on that scrollable(conversation) div using the value
obtained in step1.
var fullHeight = $('#conversation')[0].scrollHeight;
$('#conversation').scrollTop(fullHeight);
Above steps must be applied for every append on the conversation div.
After trying to find a solution that handled every circumstance (options for animating the scroll, padding around the object once it scrolls into view, works even in obscure circumstances such as in an iframe), I finally ended up writing my own solution to this. Since it seems to work when many other solutions failed, I thought I'd share it:
function scrollIntoViewIfNeeded($target, options) {
var options = options ? options : {},
$win = $($target[0].ownerDocument.defaultView), //get the window object of the $target, don't use "window" because the element could possibly be in a different iframe than the one calling the function
$container = options.$container ? options.$container : $win,
padding = options.padding ? options.padding : 20,
elemTop = $target.offset().top,
elemHeight = $target.outerHeight(),
containerTop = $container.scrollTop(),
//Everything past this point is used only to get the container's visible height, which is needed to do this accurately
containerHeight = $container.outerHeight(),
winTop = $win.scrollTop(),
winBot = winTop + $win.height(),
containerVisibleTop = containerTop < winTop ? winTop : containerTop,
containerVisibleBottom = containerTop + containerHeight > winBot ? winBot : containerTop + containerHeight,
containerVisibleHeight = containerVisibleBottom - containerVisibleTop;
if (elemTop < containerTop) {
//scroll up
if (options.instant) {
$container.scrollTop(elemTop - padding);
} else {
$container.animate({scrollTop: elemTop - padding}, options.animationOptions);
}
} else if (elemTop + elemHeight > containerTop + containerVisibleHeight) {
//scroll down
if (options.instant) {
$container.scrollTop(elemTop + elemHeight - containerVisibleHeight + padding);
} else {
$container.animate({scrollTop: elemTop + elemHeight - containerVisibleHeight + padding}, options.animationOptions);
}
}
}
$target is a jQuery object containing the object you wish to scroll into view if needed.
options (optional) can contain the following options passed in an object:
options.$container - a jQuery object pointing to the containing element of $target (in other words, the element in the dom with the scrollbars). Defaults to the window that contains the $target element and is smart enough to select an iframe window. Remember to include the $ in the property name.
options.padding - the padding in pixels to add above or below the object when it is scrolled into view. This way it is not right against the edge of the window. Defaults to 20.
options.instant - if set to true, jQuery animate will not be used and the scroll will instantly pop to the correct location. Defaults to false.
options.animationOptions - any jQuery options you wish to pass to the jQuery animate function (see http://api.jquery.com/animate/). With this, you can change the duration of the animation or have a callback function executed when the scrolling is complete. This only works if options.instant is set to false. If you need to have an instant animation but with a callback, set options.animationOptions.duration = 0 instead of using options.instant = true.