I'm using meteor for a quick site and I'm trying to make this div '#box' fit the viewport and then have the top cut off '#wrapping'. But all of these methods error or they fill the entire page instead of just the page size... So it'd be as tall as the viewport height is but you can scroll to the next page, (I'm doing a single page design) :)
var viewPortHeight = $(window).height();
$ '#box'.height() = $(Math.viewPortHeight - '#wrapping'.offset.top);
Firstly, as I pointed out in my comment. There are some syntax errors in your code here:
$ '#box'.height() = $(Math.viewPortHeight - '#wrapping'.offset.top);
We need parentheses around '#box' and '#wrapping', and you will want to user viewPortHeight other than Math.viewPortHeight (since there is no such property in the Math object):
$('#box').height() = $(viewPortHeight - $('#wrapping').offset.top);
There are still a few problems here. In jQuery when you assign a property like height you do it like so .height(newValue) and to get the height you do this .height():
$(...).height(newValue); // Sets the height to 'newValue'
$(...).height(); // Returns the height
What your doing in the code is this: $(...).height() = ... ; is not assignment, which is why you have your error. So you want to do it like in the example above:
var viewPortHeight = $(window).height();
$('#box').height( viewPortHeight - $('#wrapping').offset().top );
Here is an example with multiple pages
Related
How do I get the offset of an element from the right side, relative to the window?
I can only find jQuery solutions but I need a solution using vanilla JavaScript.
This is the solution using jQuery
var rt = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));
How do I translate this to vanilla JavaScript?
You could try using element.getBoundingClientRect() to achieve that behavior. If you wrote your code to use this instead of jQuery, it would look something like:
var rt = window.innerWidth - element.getBoundingClientRect().right;
You can get the width of an element using .innerWidth
You can get the offset values of a element using getBoundingClientRect()
You can get the outerWidth using offsetWidth
Porting your solution would be something like this:
window.innerWidth - (element.getBoundingClientRect().left + element.offsetWidth)
For more info you can check this link
You can get the offset left position using the .offsetLeft attribute on an element.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetLeft
For outer width see this answer:
outerWidth without jquery
So it would be written something like:
var rt = function() {
var someElement = document.getElementById('someID');
return window.innerWidth - (someElement.offsetLeft + someElement.offsetWidth);
}
Just grab the window size and subtract the x offset plus the width of the element you want to get the offset for.
function windowOffsetRight (ele) {
let rect = ele.getBoundingClientRect ();
let width = document.documentElement.getBoundingClientRect().width;
return width - ( rect.x + rect.width)
}
You just need to translate the jQuery functions in vanilla JS.
$window() // jQuery
window // Vanilla JS
$whatever // jQuery (probably a variable of $('.whatever'))
document.querySelectorAll('.whatever') // Vanilla JS
offset().left // jQuery
offsetLeft // Vanilla JS
outerWidth() // jQuery
offsetWidth // Vanilla JS
const el = document.getElementById('test');
console.log(window.innerWidth - (el.offsetLeft + el.offsetWidth));
<div id="test"></div>
Of course there are many other ways how to do it.
None of the above answers returned the correct value in my case, if there was scrolling involved. Here's what did the trick in my case:
var clientRect = document.querySelector("#element").getBoundingClientRect();
var offset = {
top: clientRect.top + window.scrollY,
left: clientRect.left + window.scrollX,
};
console.log(offset);
I'm trying to code a scroll indicator progress bar in React. I have it working with Jquery but would like to know how to do it with pure Javascript.
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
handleScroll() {
var winHeight = $(window).height(),
docHeight = $(document).height(),
value = $(window).scrollTop(),
max, percent;
max = docHeight - winHeight;
percent = (value / max) * 100;
this.props.updatePercent(percent);
}
Also, should I bother doing this in pure Javascript? I've been told that Jquery should not be used used in React.
Is this the only place you used JQuery? If so, I'd recommend ditching it for pure javascript. Everything you can do with JQuery you can also do with React and pure JavaScript, and it's not worth the overhead here.
Here's a pure JavaScript version of your handleScroll function. Note that document height is notoriously annoying to compute, but I've taken the approach of this question (which just reproduces JQuery's implementation).
handleScroll() {
var winHeight = window.innerHeight;
// Annoying to compute doc height due to browser inconsistency
var body = document.body;
var html = document.documentElement;
var docHeight = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
var value = document.body.scrollTop;
...
}
Update
If you want to get the scroll position within an element, you'll need something like
var el = document.getElementById('story_body');
var minPixel = el.offsetTop;
var maxPixel = minPixel + el.scrollHeight;
var value = document.body.scrollTop;
// respect bounds of element
var percent = (value - minPixel)/(maxPixel - minPixel);
percent = Math.min(1,Math.max(percent, 0))*100;
To answer your second question: In this particular case, you could just stick to jQuery (although I prefer the vanilla javascript version).
With react, it is perfectly OK to use jQuery for:
reading info from the real DOM, which are unknown to react (such as component height in the DOM, or scroll position in your case)
ajax stuff
With React, you should NOT use jQuery for:
Manipulating the DOM directly: only manipulate the DOM through react. (manipulating DOM with jQuery in react is a guarantee for big trouble)
Reading DOM info that can and should be known to react, such as value of an input field. (things do not really break, but it makes your react code harder to debug if you use jQuery to circumvent react's strict design guidelines)
I'm working on a jQuery function to set the height of a div based on the height of the window and some other elements, and I noticed something strange. The outerHeight() function seems to accept an integer parameter, even though the documentation doesn't specify that one is allowed.
So this seems to work in both Chrome and Firefox:
var o_height = $("#content").outerHeight();
var n_height = $(window).outerHeight() - $("#nav").outerHeight();
if (n_height > o_height) {
$("#content").outerHeight(n_height);
}
The alternative is to calculate the padding and then subtract it, which is a few lines longer:
var o_height = $("#content").outerHeight();
var n_height = $(window).outerHeight() - $("#nav").outerHeight();
if (n_height > o_height) {
var padding = $("#content").outerHeight() - $("#content").height();
$("#content").height(n_height - padding);
}
What I'm wondering is whether it's safe to use the shorter version. I'll be doing stuff like this several times, so I'd rather cut down on the length of the script, but not at the cost of stability. Is this a stable, but undocumented feature, or do I just need to accept the extra weight in the function?
In case anybody else stumbles upon this, it appears that this functionality was actually added all the way back in 1.8.0 for both outerHeight and outerWidth, but that despite frequent reports, the documentation still hasn't been updated.
I have several fixed position divs with the same class at varying distances from the left edge of the window, and I'd like to increase/decrease that distance by an equal amount on each div when a certain action happens (in this case, the window being resized). I've tried positioning them with CSS and percentages rather than pixels, but it doesn't quite do the job.
Is there a way to store the position of each of those divs in an array and then add/subtract a given amount of pixels?
Here's what I've tried so far - I'm still getting my head around JS so this could be really bad for all I know, but here goes:
roomObjects = $('.object-pos');
var objectCount = 0;
for ( var objectCount = 0; objectCount < 10; objectCount++;) {
roomObjects = rooomObjects[objectCount];
console.log(roomObjects.css("background-position").split(" "));
}
Do you mind sharing why percentages wouldn't work? Usually that's what I would recommend if you're wanting the page to scale correctly on window resizes. I guess if you really wanted to you could do something like:
$(window).resize(function() {
$('#whateverdiv').style.whateverproperty = $('#whateverdiv').style.whateverproperty.toString() + (newPosition - oldPosition);
oldPosition = newPosition;
}
this is obviously not the complete code, but you should be able to fill in the blanks. You'll have to set the oldPosition variable on page load with the original position so that the function works the first time.
edit: you'll also have to strip off the units from the x.style.property string, so that you'll be able to add the value to it
A problem you might well be facing is that when retrieving the current left or top properties, they are returned as a string, with px of % on the end. Try running a parseInt() on the returned values to get a number, then you might well be able to add to the values. Just be sure, when reassigning, that you concatenate "px" or "%" on the end as appropriate.
You could use a bit of jQuery :
var el = $("#id");
var top = el.css("top");
el.css("top", top * 1.2); // increase top by 20%
saves mucking around in the DOM
This might be useful if you want to position things relatively: http://docs.jquery.com/UI/Position
I'm trying to get the value of an inherited CSS property using Javascript. I haven't been able to find a comprehensive answer.
Example CSS:
div {
width: 80%;
}
Example Markup:
<div id="mydiv"> Some text </div>
Using javascript (jQuery, or native), I need to get the width of the element-- not in pixels, but the string "80%".
$('#mydiv').css('width'); // returns in px
$('#mydiv')[0].style.width // empty string
getComputedStyle($('#mydiv')[0]).width // returns in px
The reason I need the value as a string is because I need to copy the style to another element. If it's declared as a percent, the other value needs to be a percent. If it's declared in px, the other value needs to be in px.
The real trick is that this property could be inherited, not declared explicitly on the element (as in my example).
Does anyone have any ideas?
What you are searching for is this quirksmode.org article. It proposes the function
function getStyle(el, styleProp) {
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
Still, you should read that article carefully. They names of the styleProps are not really cross-browser, and you will see how different browsers handle this. Opera seems to have the best support for reporting the correct values.
There's no way to get the percentage value I'm afraid. You can try something like this:
var widthpx = getComputedStyle($('#mydiv')[0]).width;
var parentWidth = $('#mydiv').parent().css('width')
var width = ( 100 * parseFloat(widthpx) / parseFloat(parentWidth) ) + '%';
get the offSetWidth of the element, and the offsetWidth of its offsetParent, and calculate the percentage from the two integers.
This binds an event handler to an element for the click event and alerts the element's relative width compared to it's parent element.
$('#mydiv').on('click', function () {
//element width divided by parent width times 100 to make a percentage
alert(Math.round($(this).width() / $(this).parent().width() * 100) + '%');
});
Here is a demo: http://jsfiddle.net/X67p5/