DOM element position based on view - javascript

How can I get position of an element based on view? So as viewer scroll I get different values.
jQuery is prefered.

Do you mean relative to the viewable window?
If so, you can use something like this:
$("#element").offset().top - $(window).scrollTop()
That will return a positive number until it is scrolled off the window, at which point it will return a negative number.

$(function() {
$(window).scroll(function() {
var pos = $('#button_id').offset(),
top = pos.top - $(window).scrollTop(),
lft = pos.left - $(window).scrollLeft();
$("#where").html("Top: " + top + "\nLeft: " + lft);
});
});
Try it out with this jsFiddle
HTML something like the following:
<div id="button_id">Button ID</div>
<div id="where"></div>

Maybe something like this?
(jQuery)
var pos = $('#button_id').position();
alert("POSITION: \nLeft: "+pos.left + "\nTop: " + pos.top);
Source:
http://blog.ekini.net/2009/01/30/jquery-find-position-the-exact-position-of-an-element-in-the-browser-window/
Good luck, if you edit your question maybe I´ll be able to helo you better

Related

Is there a way to access whether a portion of a webpage is being rendered on screen or not via Javascript?

Currently our logic runs within an iframe on clients pages. We have the request to now detect whether that iFrame is currently in the viewing window or not (scrolled off-screen).
I just had an idea that this might be something that the GPU might already have which would allow for it to provide better performance on the page with regards to what it is rendering and I wanted to know if anyone was aware of whether this data was accessible via an API/lib such as OpenGL.
I am aware that providing actual pixel info, could be a large security issue, however just having access to whether or not a specific iFrame was being rendered would be helpful for viewability detection.
Is anyone aware of whether there is a way to do this? Current reading so far is not showing this as being possible, but I am continuing my search and thought I would post here as well.
Any info or direction would be helpful. Thanks!
You can calculate if the object is inside your viewport or not.
http://plnkr.co/edit/91gybbZ7sYVELEYvy1IK?p=preview
$(document).ready(function() {
myElement = $('.someObject');
window.onscroll = function() {
var screenTop = $(window).scrollTop();
var screenBottom = screenTop + $(window).height();
var elTop = $(myElement).offset().top;
var elBottom = elTop + $(myElement).height();
var info = 'screenTop:' + screenTop + ' screenBottom:' + screenBottom + ' elTop:' + elTop + ' elBottom:' + elBottom;
if((elBottom <= screenBottom) && (elTop >= screenTop)) {
$('.info').html('Element is in view + <small>' + info + '</small>');
} else {
$('.info').html('Element is out of view + <small>' + info + '</small>');
}
}
})

How do you get this result, using Jquery Scroll Event & offset/position, css or javascript?

How do you get this result in css, javascript or jquery, or a combination of all:
I asked and posted a similar question before, but no one answered it.
Someone said:
"Maybe you can use javascript (or bether JQuery) for this.
If you use JQuery, you can use the scroll event. If you are scrolling, do a
check if it hits the other div. https://api.jquery.com/scroll/
Checking the positions of the divs is possible with offset/position.
http://api.jquery.com/offset/ https://api.jquery.com/position/
If you want to change the background, you give the div a background color
that is pink. If it hits then you can add an additional background-image
that has a specific background-position
(http://www.w3schools.com/cssref/pr_background-position.asp xpos ypos).
I don't have tried it yet, but I guess it is possible that way."
So my question is, how would you go about doing it to get this result or regardless of what way?
I came up with this after a couple of hours trying to make it work. It was pretty fun doing it, so I'm sharing it.
$(document).ready(function() {
var initScrollTop = $(window).scrollTop();
$('.div1').css('top', (initScrollTop+100)+"px");
$(window).scroll(function () {
var top = parseInt($('.div1').css('top').split("px")[0]);
// I GIVE A FIXED TOP TO .DIV1
var scrollTop = $(this).scrollTop() + 100;
$('.div1').css('top', scrollTop+"px");
// GETTING SOME VALUES
// DIV1
var div2Top = parseInt($('.div2').css('top').split('px')[0]);
var div2Height = parseInt($('.div2').css('height').split('px')[0]);
var div2Bottom = parseInt($('.div2').css('bottom').split('px')[0]);
// DIV2
var div1Width = parseInt($('.div1').css('width').split('px')[0]);
var div1Height = parseInt($('.div1').css('height').split('px')[0]);
var div1Top = parseInt($('.div1').css('top').split('px')[0]);
var div1Bottom = parseInt($('.div1').css('bottom').split('px')[0]);
var div1Left = parseInt($('.div1').css('left').split('px')[0]);
// WE ARE GOING THROUGH THE GREEN BOX
if(scrollTop + div1Height > div2Top) {
// OUTSIDE OF THE GREEN BOX (.div2)
if(scrollTop + div1Height > div2Height + div2Top) {
var div3Height = div2Top + div2Height - scrollTop;
$('.div3').css('top', scrollTop+ "px")
// .css('bottom', div2Bottom + "px")
.css('width', div1Width + "px")
.css('height', div3Height + "px")
.css('visibility','visible');
console.log("I'm out");
}
// INSIDE OF THE GREEN BOX (.div2)
else {
var div3Height = (div1Top > div2Top) ? div1Height : scrollTop + div1Height - div2Top;
var div3Top = (div1Top > div2Top) ? div1Top : div2Top;
$('.div3').css({
'top' : div3Top + "px",
'left': div1Left + "px",
'width': div1Width + "px",
'height': div3Height + "px",
'visibility':'visible'
});
}
} else {
$('.div3').css('visibility','hidden');
}
// WE ARE ABSOLUTELY OUT OF THE GREEN BOX (FROM THE BOTTOM GOING DOWN)
if(scrollTop > div2Top + div2Height) {
$('.div3').css('visibility','hidden');
}
});
});
Here's there a fiddle so you can test it http://jsfiddle.net/5076h670/2/
So basically what it does is create three divs, two of them will be visible and 'collide' between each other, the other one starts hidden and it shows only when the position of the div1 is in the range of the div2. This div3 (the third div) will be shown over the div1 (see the z-index). When it's absolutely out of the box div3 will be hidden.
I don't know what else to explain about the code, I don't know if (and I don't think, it took me a while to make it work) it's understandable what it does. If you have something to ask I'll be reading ;)
Hope it helps

scripting in css with some creativity

I found the following creative accepted answer
jQuery('.get-close-to').hover(function() {
var offset = jQuery(this).css('offset');
alert( 'Left: ' + offset.left + '\nTop: ' + offset.top );
});
I wanted to know how .css('offset') is working so I made a jsfiddle but it's alerting "undefined".
Can anyone describes about this, working and is correct way?
Comment:
I know to use .offset() but I don't mean to use this, but my question regards how the accepted answer's code is working ....... with .css('offset')? That's all.
There's no offset property in CSS. with jQuery.css(propertyName) you can only access properties that exist. Everything else will return null.
for example:
jQuery.css('myImaginativePropertyname'); // returns null
jQuery.css('border'); // would return '0px none rgb(0, 0, 0)'
However
You can access the event.target (DOM element) like this:
jQuery('.get-close-to').hover(function(e) {
var elem = e.target;
alert( 'Left: ' + elem.offsetLeft + '\nTop: ' + elem.offsetTop );
}, function(e){});
I added the second function so that the code won't be executed twice. If you have only single function as input on jQuery.hover(), it will execute both in hover and blur. If you add a second function as a parameter, the first one will be executed on hover, while the second will be executed on blur of the element.
Here's the fiddle: http://jsfiddle.net/JLAK4/2/
Some people may argue to use jQuery(this).offset() instead, but why waste cpu cycles for yet another method call while you already have your DOM element populated and at your disposal? jQuery is a nice compatibility layer, I give you that. But abusing and overusing it makes no sense at all.
Do you want to be using .offset() instead?
jQuery('.get-close-to').hover(function() {
var offset = jQuery(this).offset();
alert( 'Left: ' + offset.left + '\nTop: ' + offset.top );
});
Try this:
jQuery('.get-close-to').hover(function() {
var offset = jQuery(this).offset();
alert( 'Left: ' + offset.left + '\nTop: ' + offset.top );
});
I think he wanted to say like this: working fiddle
jQuery('.get-close-to').hover(function() {
var offset = jQuery(this).offset();
alert( 'Left: ' + offset.left + '\nTop: ' + offset.top );
});
But mistakenly he has typed .css('offset') may be.

Binding events to a jquery object not working

I've been trying to bind events to jquery objects (code below) but its really not working at all. Could somebody offer me a suggestion? Thanks!
var img = thumbnail[0].appendChild(document.createElement('img'));
img.className = 'smallboard';
img.src = 'res/smallboard' + i + '.jpg';
img.onload = function() {console.log('small board loaded.');}
img.style.top = (8-i)*height+5 + 'px';
img.style.left = 4 + 'px';
var jqimg = $(img);
jqimg.bind('click', function(){
console.log(i + '');
show_board(i-1, true);
});
Here, thumbnail is a jquery element and i is a small whole number. I had problems with binding it in another way as well. (code below)
highlight = $('<div id="level_highlight"></div>');
highlight.css('height', height + 'px');
highlight.css('width', width + 'px');
highlight.css('display', 'inline');
highlight.css('left', posx + 'px');
highlight.css('top', posy + 'px');
highlight.bind('mouseover', function() {console.log('mousing over highlight');});
Its not working here either. I feel I am making a silly error somewhere. I'm using Chrome.
Thank you!
seems to work for me...
see my jsFiddle example. Am I missing something?
Is it just an error in your retranscription here or did you froget
the var before highlight ?
var highlight = $('');
Did you append it somewhere in the DOM ($('body').append(highlight);) or something, if it already exists, you should do var highlight = $('#level_highlight'); instead
Thanks guys. The answer was that since this code is an over-simplification of the code-base, I'd missed out a part where the z-index for the container element for this section was set to -10. Set that part correct and it worked like a charm.
Thanks.

Different background position every click

Im trying to build sort of slide where when click on link ".animate" will change it position ( every time 100px more)
This:
$(function(){
$('#m-main').click(function(){
$('slide').animate({top : "100px"}, {duration:500})
})
});
will work only once.
How can I make this working?
Many thanks for your help.
$(function() {
$('#m-main').click(function(){
$(this).data($(this).data('pos') + 100);
$('slide').animate({top : $(this).data('pos') + 'px'}, {duration:500})
})
});
When it runs it sets the top padding to 100px, so after the first time it's just setting it to the same value it already has. You need to increment the value each time.
$(function(){
$('#m-main').click(function(){
var current = $('slide').css('top');
current = current + 100;
$('slide').animate({top : current+"px"}, {duration:500})
})
});
code above untested
Try using a counter instead of just top : "100px". It is just doing it once because essentially your setting top to 100px and then setting top to 100px again which is just keeping it where it is. You want it to move to 200px and then to 300px, etc.
Try this:
var fromTop = 100;
$(function() {
fromTop = fromTop + 100;
$('#m-main').click(function() {
$('slide').animate({top : '"' + fromTop + 'px"'}, {duration:500})
})
});
It looks like you've got some error in the query string in the click handler. $('slide') will select all <slide> elements, which I assume you have none, perhaps $('.slide') or $('#slide') is what you're after?
If you just keep a reference of the position you'd like the element to move to and increase that by 100 each time (see chaos's answer) then you should be right.
$(function(){
var pos=100;
$('#m-main').click(function(){
$('slide').animate({top : pos+'px'}, {duration:500});
pos=pos+100;
});
});
Try this:
$('#m-main').click(function(){
var slide = $('.slide', this),
posY = parseInt(slide.css("background-position").split(" ")[1]);
slide.stop().animate({backgroundPosition: "0 "+(Math.ceil(posY/100)*100 + 100)+"px"}, {duration:500});
});

Categories