Browser relative positioning with jQuery and CutyCapt - javascript

I've been using CutyCapt to take screen shots of several web pages with great success. My challenge now is to paint a few dots on those screen shots that represent where a user clicked.
CutyCapt goes through a process of resizing the web page to the scroll width before taking a screen shot. That's extremely useful because you only get content and not much (if any) of the page's background.
My challenge is trying to map a user's mouse X coordinates to the screen shot. Obviously users have different screen resolutions and have their browser window open to different sizes. The image below shows 3 examples with the same logo. Assume, for example, that the logo is 10 pixels to the left edge of the "content" area (in red).
In each of these cases, and for any resolution, I need a JavaScript routine that will calculate that the logo's X coordinate is 10. Again, the challenge (I think) is differing resolutions. In the center-aligned examples, the logo's position, as measured from the left edge of the browser (in black), differs with changing browser size. The left-aligned example should be simple as the logo never moves as the screen resizes.
Can anyone think of a way to calculate the scrollable width of a page? In other words, I'm looking for a JavaScript solution to calculate the minimum width of the browser window before a horizontal scroll bar shows up. And I need to do this without first knowing any element IDs or class names.
Thanks for your help!

You can get the total space an element needs:
function getWidth(x){
var totalWidth = x.width();
totalWidth += parseInt(x.css("padding-left"), 10) + parseInt(x.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(x.css("margin-left"), 10) + parseInt(x.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(x.css("borderLeftWidth"), 10) + parseInt(x.css("borderRightWidth"), 10); //Total Border Width
return totalWidth;
}
You have to add that to the position of the element:
$('#yourlogo').offset().left;
So:
var window-width = $('#yourlogo').offset().left + getWidth($('#yourlogo'));
Hope this helps :-??

If I understand you correctly, then this is what should work for you!
var browserWidth=$(window).width(); // returns width of browser viewport
It should return the width of the persons browser window.
Hope this helps!

Related

Calculate what portion of div is off the screen

I have a div that is position: absolute. Sometimes on smaller screen resolutions it goes off the screen. Is it possible to calculate in px how much of it is off the screen?
As has been already mentioned, this really isn't the way for solving this problem, however the code you need is:
const offsetRight = document.querySelector('.your-element').getBoundingClientRect().right - window.innerWidth
This code gets the px value of the right edge of your element and calculates the difference between that and the edge of the window.
For the left side:
const offsetLeft = 0 - document.querySelector('.your-element').getBoundingClientRect().left;

Change text size on scroll

I would like to achieve the following:
On a mobile device, when someone starts scrolling from the top, a text starts to shrink down, and after a given amount, it takes its final size and stays like so for the rest of the page. The idea is that I have a Company name in the middle of the screen, and on scroll, it shrinks to the top left corner of the screen, and a menu bar appears behind it, and the Company name becomes the logo on the menu bar. The menu bar's background is the Hero image of the page. Here is my code:
window.onscroll = scrolled
function scrolled(){
let fromTop = window.scrollY
if (fromTop < 300) {
heroText.style.fontSize = `${2 - fromTop/160}em`
hero.classList.remove('hero-fixed')
heroNav.classList.remove('hero-nav-fixed')
heroText.classList.remove('h1-fixed')
heroImg.classList.remove('hero-img-fixed')
} else {
hero.classList.add('hero-fixed')
heroNav.classList.add('hero-nav-fixed')
heroText.classList.add('h1-fixed')
heroImg.classList.add('hero-img-fixed')
}
if (fromTop > 360) {
heroNav.classList.add('nav-mobile', 'hidden')
intro.classList.add('intro-fixed')
hamburger.classList.remove('hidden')
} else {
hamburger.classList.add('hidden')
heroNav.classList.remove('nav-mobile','hidden')
intro.classList.remove('intro-fixed')
}
}
}
It works, but I have to adjust for every screen size I want to support, and it is extremely laggy! It is probably a very wrong way to do it, so could someone help me make it more efficient and less laggy on mobile devices?
My guess is that the constant resizing of the text is one of the problems, as well as the height change of the hero image. I play with position fixed, and padding-top changes in the CSS to compensate the disappearing (becoming fixed positioned) elements.
Could some library, like RxJS help, or is there a VanillaJS elegant solution as well?
To make this more efficient in the Javascript side, you could use something like lodash's debounce.
Changing layout can be a very resource intensive operation so you might want to try leaving the element fixed position all the time and only adjusting its size (and/or the size of its parents) with the CSS transform property. scale() would work quite nicely here.

Get the max-viewport size of user browser window

I am working on a project including several draggable divs using jQuery-UI with the constrain functionality to help the user avoid stray divs hiding in the outskirts.
Now I am getting the full screen dimensions for the constrains:
var width = window.screen.availWidth;
var height = window.screen.availHeight;
And that is pretty close to what I desire. However, as all browser have the tabs and search input line on the top and often some other stuff at the bottom I am getting a bigger constrain than the actual view port. Then you say get the view port dimensions:
$(window).height();
$(window).width();
Well, that is close to but it is not 100%, because if the user has a minimized window when entering the site that view port size is going to be the constrain size. This means that if the user then uses full screen the constraint is just as big as the view port were from the start.
Then you might say: "Why not change the constrain dynamically along the way?"
Well, that could have been a possibility but this whole page idea is to fine tune the GUI and by changing the constrain size could potentially mess upp the positioning of the draggable objects. So, what am I asking for?
I am asking for a way to get the maximum browser view port size on the current users screen? No matter if the user has a smaller than max browser window ATM when entering the page.
PS. I suppose I could check which browser the user is using and by hard code remove the amount of pixels that specific browsers head-bar is using. That however is a bad solution in my book, for several reasons.
with some good suggestions pointing me in the right direction I have now understood my problem.. I think.
These two bad boys are actually doing the trick:
var width = window.screen.availWidth;
var height = window.screen.availHeight;
BUT!! I am on a desktop running windows and the taskbar at the bottom is actually overlaying the chrome browser window! This was what made me confused to start with. So... yeah. I guess that is it. I just have to live with my users beeing able to put the divs under the win taskbar. Well ok! Bye
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
Although pretty hacky, you could take advantage of the viewport units of css.
$('body').css({
'height': '100vh',
'width': '100vw'
});
var height = $('body').height(); // or innerHeight or OuterHeight
var width = $('body').width();
vw : Relative to 1% of the width of the viewport
vh : Relative to 1% of the height of the viewport
vmin : Relative to 1% of viewport's smaller dimension
vmax : Relative to 1% of viewport's larger dimension
https://www.w3schools.com/cssref/css_units.asp
You can use $(window).outerWidth() and $(window).outerHeight()
You may refer these links.
https://developer.mozilla.org/en-US/docs/Web/API/Window/outerHeight
https://developer.mozilla.org/en-US/docs/Web/API/Window/outerWidth

Using javascript to find the page number of the current view page in an iboooks epub

I am building a lightbox style div element for an ibooks epub. I want the div to be displayed on the current page being viewed at the time. If the image is on page two of the ebook, I want the lightbox to showup on page two. I have the div width and height set to fill the screen.
document.getElementById("LightBoxDiv").style.width=window.innerWidth+"px";
document.getElementById("LightBoxDiv").style.height=window.innerHeight+"px";
I can manualy set a fixed top value of the div if I know which page number an image is on. My device has a 460px height on the window. So for an image on page two, the top should then be 460 which is the beginning of the 2nd page.
document.getElementById("LightBoxDiv").style.top="460px";
However, as ebooks are dynamic in that the user can change the size of the text larger or smaller, the page upon which something might fall changes. I need a way to set the top dynamically based upon the current page. If I know the current page number being viewed, I can set the div top to
var lighboxHeight = (pagenumber-1)*window.innerHeight;
I tried using the window.pageYOffset to calculate the current page, but this always gives a 0 value as the page does not scroll in an ebook. Unfortunately, I can find no documentation or any reference describing how to use javascript to access the page numbers. Does anyone have any idea how to access or find the current page number in an ibooks epub using javascript?
Thanks,--christopher
I believe I found the solution. This question/answer helped a lot.
//window height
var winHeight = window.innerHeight;
//top of object to be placed in the lightbox
//can be any object
var curOjbTop = document.getElementById(svgId).getBoundingClientRect().top;
//body y value
var bodyTop = document.body.getBoundingClientRect().top;
//amount the object is shifted vertically downward from the top of the body element
var offset = curObjTop - bodyTop;
//page number of the object
//this is actually 1 less than the true page number
//it basically starts the page count at 0, but for actual page number add 1
var curPage = Math.floor(offset/winHeight);
//this sets the top edge of the lightbox at y=0 on the page the item is on
var lightboxTop = curPage*winHeight;
document.getElementById("LightBoxDiv").style.top=lightboxTop;
My lightbox div covers the entire viewing area, but if you wanted a smaller one that was centered, you would need to add an additional half of the window height and then set the top margin to be half the negative amount of the height you wanted.
For example if the light box was 200 x 200, then your lightboxtop would be
var lightboxTop = (curpage*winHeight)+(winHeight*.5);
var topMargin = "-100px";
It may need to be tweeked some, but overall it should work to determine a page number.

How do I move the background image of a DIV based on the scrollbar movement?

I have been looking into parallax effects for vertical scrolling on my web page, and after some research, I'm not sure that what I want to do is technically a parallax effect.
From what I've seen, most parallax effects assume you want to be able to scroll indefinitely with many background images rolling by, or with huge images that repeat.
What I want to do is have the background of two DIVs be filled with a background image as the scroll bar reaches the bottom of the page. Note that I do not want the background images to stretch. I'm assuming to get the effect I want that these images would have a vertical height bigger than most people's viewport, and then their vertical position would change. When the user's scrollbar is at the top, a certain amount of the background is visible, and then it moves vertically to fill the background space as the user scrolls down.
Please see the image below for a visual explanation of the effect I hope to acheive:
The height of the veiwport will vary depending on the length of content inside the inner DIV.
My trouble is that if what I am trying to do is not exactly a parallax effect, then I don't know what else to call it, and my attempts to search by describing it keep landing me back at pages offering tutorials on parallax effects. So I've been stumped by a lack of terminology.
If someone could direct me to how I can control the vertical position of the background depending on the scrollbar position, that would be much appreciated. If this can be done with just CSS that would be great, but I'm assuming some Javascript would be required. A jQuery solution would also work for me.
Update:
After searching using the terms provided in comments, I've got the background image in the outer DIV to almost do what I want with the following code:
$(window).scroll(function () {
var yPos = $("#outerDiv").height() - ($("#outerDIV").height() * ($(window).scrollTop() / $(window).height()));
document.getElementById('outerDIV').style.backgroundPosition="0px " + yPos + "px";
});
It moves the background image in the right direction relative to the scrolling, but what it lacks is constraining that motion to within the viewport. Getting the right proportions based on the viewport and DIV sizes is proving to be just a little beyond my mathematical abilities.
For your requirement, you have to use a jquery parallax plugin to guide this activity, my best suggest it to use a Superscollorama and play with the elements as your wish...
As far as your question, Try this example,
controller.addTween(
'#examples-background',
(new TimelineLite())
.append([
TweenMax.fromTo($('#parallax-it-left'), 1,
{css:{backgroundPosition:"(0 -54px)"}, immediateRender:true},
{css:{backgroundPosition:"(0 -54px)"}}),
TweenMax.fromTo($('#parallax-it-right'), 1,
{css:{backgroundPosition:"(0 -54px)"}, immediateRender:true},
{css:{backgroundPosition:"(0 54px)"}})
]),
1000 // scroll duration of tween
);
You serial vice change as far as your wish...
Try practice this plugin, hope that works for you...
http://johnpolacek.github.io/superscrollorama/
Thanks...
Turns out what I want to acheive is possible with no special plugins, just some carefully thought out math. I did use a little jQuery syntax, but I don't think it's strictly necessary.
The code below has copious notes, so hopefully it's largely explanatory. In summary, you just need to find the position of the background image when the scroll would be at the top, and the position it would be if the scroll bar was at the bottom, and then you can use the percentage of the scrollbar's movement to work out where you are between those two points. It's a little tricker than just that, of course, in that you have to account for the difference between the total height of the scroll bar and where your DIV appears on the page and a few other adjustments, but the details of what I did are below.
What I've done here is just for the "outer DIV" that I described in my question. To get a background to move like the "inner DIV" I described, you'd have to modify the code, presumeably by reversing a few parameters. I haven't done that yet, but it seems like a straightforward task.
Hope others find this code useful. If anyone has suggestions on how it can be made more efficient or better, please let me know.
function moveBG(){
// imageHeight is not the total height of the image,
// it's the vertical amount you want to ensure remains visible no matter what.
var imageHeight = 300;
// Get the maximum amount within the DIV that the BG can move vertically.
var maxYPos = $("#outerDIV").height() - imageHeight;
// Get the amount of vertical distance from the top of the document to
// to the top of the DIV.
var headerHeight = document.getElementById("outerDIV").offsetTop;
// Calculate the BG Y position for when the scrollbar is at the very top.
var bgTopPos = $(window).height() - headerHeight - imageHeight;
// I don't want the image to wander outside of the DIV, so ensure it never
// goes below zero.
if (bgTopPos < 0)
{
bgTopPos = 0;
}
// Calculate the BG Y position when the scrollbar is at the very top.
var bgBottomPos = $(document).height() - $(window).height() - headerHeight;
// To prevent the BG image from getting cut off at the top, make sure
// its position never exceeds the maximum distance from the top of the DIV.
if (bgBottomPos > maxYPos)
{
bgBottomPos = maxYPos;
}
// Subtract the top position from the bottom, and you have the spread
// the BG will travel.
var totalYSpan = bgBottomPos - bgTopPos;
// Get the scrollbar position as a "percentage". Note I simply left it as a
// value between 0 and 1 instead of converting to a "true" percentage between
// 0 and 100, 'cause we don't need that in this situation.
var scrollPercent = ($(window).scrollTop() / ( $(document).height() - $(window).height()));
// The percentage of spread is added to the top position, and voila!
// You have your Y position for the BG image.
var bgYPos = bgTopPos + (Math.round(totalYSpan * scrollPercent));
// Apply it to the DIV.
document.getElementById('outerDIV').style.backgroundPosition="0px " + bgYPos + "px";
}
// Place the BG image correctly when opening the page.
$(document).ready(function() {
moveBG();
});
// Make it update when the scrollbar moves.
$(window).scroll(function () {
moveBG();
});

Categories