I need to receive the elements left and top property in the middle of the CSS transition. Currently I use jQuery position method and it seem to be working to some point.
I have made 2 examples to show my problem more clearly:
1) Here is NON-working example where position of element is printed to console. The correct position is received till the elements transition is changed to its original position. After the first change in transform value, the position is not updated anymore. jsFiddle link: http://jsfiddle.net/PCWDa/8/
2) Here is WORKING example with only difference in the way position of the element is reported to us: position is outed to input (type=text) elements value. jsFiddle link: http://jsfiddle.net/PCWDa/9/
Conclusion: the jQuerys position() method appears not to receive the correct position when dom elements properties does not receive any updates (like updating value of text element etc).
Bug? This could be bug in jQuery, css or browser itself? Are there any workarounds to get first example working - to get correct position in the middle of transition at any time without making changes to dom element properties like in second example.
jsFiddle code:
To get example 1 code, change variable working to false and to get example 2 , to true.
css
.box{
width: 100px;
height: 100px;
background-color: red;
position: relative;
-webkit-transition: all 5000ms ease;
}
.box_moved{
-webkit-transform: translateX(300px);
}
html
<div class="box"></div>
<input type="text" class="val">
javascript
var direction = false;
var working = false;
window.forward = function(){$('.box').addClass('box_moved')}
window.backward = function(){$('.box').removeClass('box_moved')}
window.swap = function(){
if( direction = !direction )
forward()
else
backward();
}
window.getlocation = function(){
if(working)
$('.val').val( $('.box').position().left );
else
console.log($('.box').position().left);
}
window.setInterval("swap()",3000);
window.setInterval("getlocation()",200);
Related
So I have been reading up on dozens upon dozens of Javascript zoom components, but none of them do what I am looking for, so I'm curious where to find such a component (if one exists) or how to code it myself.
The goal is to download a single large (1000x1000) image to the browser. Then within the browser, the image would have three presentation states within the same element container that the user can toggle between by clicking on some page element.
State 1 (default): See the entire image, but scaled down to fit within a 500x500 container (i.e. shrunk, but not cropped). For example (not to scale, but for comparison with other states):
State 2: See the middle 50%, centered, in the same container (i.e. actual size, and cropped). For example:
State 3: See the middle 25%, centered, in the same container (i.e. enlarged, and cropped quite a bit). For example:
And I would put the script that toggles between these three states in the click of some page element, such as a button.
Can any one offer a link to a component that does this, or suggestions on how the method that might accomplish it?
Thanks for any help!
I will go down on leveraging some CSS here.
For first case:
1) create a DIV which is 500x500, and set the background image to the file. Make sure you set background-size:contain property as well on the div.
2) For the second case I will remove the background-size:contain
3) The third case I will set the `background-size:200%;'
JSFiddle
If what you've described is really all you want to do it can be easily achieved with some CSS and a few lines of javascript:
var container = document.querySelector('.image-zoom'),
zoomBtn = document.getElementById('zoom-it'),
i = 0;
function clickHandler() {
if (i === 0) {
container.classList.add('zoom-2x');
i++;
} else if (i === 1) {
container.classList.add('zoom-4x');
i++;
} else {
container.classList.remove('zoom-2x');
container.classList.remove('zoom-4x');
i = 0;
}
}
zoomBtn.addEventListener('click', clickHandler);
.image-container, .image-zoom {
width: 250px;
height: 250px;
}
.image-container {
overflow: hidden;
}
.image-zoom.zoom-2x {
transform: scale(2);
}
.image-zoom.zoom-4x {
transform: scale(4);
}
<div class="image-container">
<div class="image-zoom" style="background-image:url(http://lorempixel.com/250/250)">
</div>
</div>
<button id="zoom-it">zoom image</button>
This assumes you know the dimensions of the image, which if you're using a CMS you can likely easily get and insert them inline on the .image-zoom and .image-containerelements.
jsFiddle
EDIT
jsFiddle 2
Modified the jsfiddle to be closer to what your question asked (initial state of the image is contained within the square and not cropped any amount.)
I need to get the height of a textarea. Seemingly so simple but it's driving me mad.
I have been researching for ages on stackoverflow with no luck: textarea-value-height and jquery-js-get-the-scrollbar-height-of-an-textarea and javascript-how-to-get-the-height-of-text-inside-of-a-textarea, among many others.
This is how it looks currently:
This is how I want it to look, open a full height:
.
Here is my html:
<textarea id="history" class="input-xxlarge" placeholder="Enter the content ..." rows="13"></textarea>
CSS:
.input-xxlarge {
display: inline-block;
height: auto;
font-size: 12px;
width: 530px;
resize: none;
overflow: auto;
}
jQuery:
var textarea = $('#history');
I've tried (inter alia):
1. textarea.height() --> always returns 0
2. textarea.ready(function() { // wait for DOM to load
textarea.height();
}
3. getting scrollheight from textarea as an HTMLTextareaElement (i.e. DOM Element) --> returns 0
4. var contentSpan = textarea.wrapInner('<span>');
var height = contentSpan.height(); --> always returns 0
Please help, I'm at my wit's end!
Ok, I've found a solution. Whether it's the best solution, I don't know, but it works and that, frankly, is all I care about, having spent almost a day on this issue.
Here it is for anyone who faces the same problem:
Select the textarea:
var textarea = $('#history');
Get the textarea's text:
var text = textarea.text();
Create a temporary div:
var div = $('<div id="temp"></div>');
Set the temp div's width to be the same as the textarea. Very important else the text will be all on one line in the new temp div!:
div.css({
"width":"530px"
});
Insert the text into the new temp div:
div.text(text);
Append it to the DOM:
$('body').append(div);
Get the height of the div:
var divHeight = $('#temp').height();
Remove the temp div from the DOM:
div.remove();
Had a similar issue, in my case I wanted to have an expand button, that would toggle between two states (expanded/collapsed). After searching also for hours I finally came up with this solution:
Use the .prop to get the content height - works with dynamically filled textareas and then on a load command set it to your textarea.
Get the inner height:
var innerHeight = $('#MyTextarea').prop('scrollHeight');
Set it to your element
$('#MyTextarea').height(innerHeight);
Complete code with my expand button(I had min-height set on my textarea):
$(document).on("click", '.expand-textarea', function () {
$(this).toggleClass('Expanded');
if($(this).hasClass('Expanded'))
$($(this).data('target')).height(1);
else
$($(this).data('target')).height($($(this).data('target')).prop('scrollHeight'));
});
Modern answer: textarea sizing is a few lines of ES6 implementable two primary ways. It does not require (or benefit from) jQuery, nor does it require duplication of the content being sized.
As this is most often required to implement the functionality of auto-sizing, the code given below implements this feature. If your modal dialog containing the text area is not artificially constrained, but can adapt to the inner content size, this can be a perfect solution. E.g. don't specify the modal body's height and remove overflow-y directives. (Then no JS will be required to adjust the modal height at all.)
See the final section for additional details if you really, truly only actually need to fetch the height, not adapt the height of the textarea itself.
Line–Based
Pro: almost trivial. Pro: exploits existing user-agent behavior which does the heavy lifting (font metric calculations) for you. Con: impossible to animate. Con: extended to support constraints as per my codepen used to explore this problem, constraints are encoded into the HTML, not part of the CSS, as data attributes.
/* Lines must not wrap using this technique. */
textarea { overflow-x: auto; white-space: nowrap; resize: none }
for ( let elem of document.getElementsByTagName('textarea') ) {
// Prevent "jagged flashes" as lines are added.
elem.addEventListener('keydown', e => if ( e.which === 13 ) e.target.rows = e.target.rows + 1)
// React to the finalization of keyboard entry.
elem.addEventListener('keyup', e => e.target.rows = (elem.value.match(/\n/g) || "").length + 1)
}
Scrollable Region–Based
Pro: still almost trivial. Pro: animatable in CSS (i.e. using transition), though with some mild difficulty relating to collapsing back down. Pro: constraints defined in CSS through min-height and max-height. Con: unless carefully calculated, constraints may crop lines.
for ( let elem of document.getElementsByTagName('textarea') )
elem.addEventListener('keyup', e => {
e.target.style.height = 0 // SEE NOTE
e.target.style.height = e.target.scrollHeight + 'px'
})
A shocking percentage of the search results utilizing scrollHeight never consider the case of reducing size; for details, see below. Or they utilize events "in the wrong order" resulting in an apparent delay between entry and update, e.g. pressing enter… then any other key in order to update. Example.
Solution to Initial Question
The initial question specifically related to fetching the height of a textarea. The second approach to auto-sizing, there, demonstrates the solution to that specific question in relation to the actual content. scrollHeight contains the height of the element regardless of constraint, e.g. its inner content size.
Note: scrollHeight is technically the Math.max() of the element's outer height or the inner height, whichever is larger. Thus the initial assignment of zero height. Without this, the textarea would expand, but never collapse. Initial assignment of zero ensures you retrieve the actual inner content height. For sampling without alteration, remove the height override (assign '') or preserve (prior to) then restore after retrieval of scrolllHeight.
To calculate just the height of the element as-is, utilize getComputedStyle and parse the result:
parseInt(getComputedStyle(elem).height, 10)
But really, please consider just adjusting the CSS to permit the modal to expand naturally rather than involving JavaScript at all.
Place this BEFORE any HTML elements.
<script src="/path/to/jquery.js"></script>
<script>
$(document).ready(function(){
var textarea = $('#history');
alert(textarea.height()); //returns correct height
});
</script>
You obviously do not have to alert it. I was just using an easily visible example.
Given a textarea with an id of "history", this jQuery will return it's height:
$('#history').height()
Please see a working example at http://jsfiddle.net/jhfrench/JcGGR/
You can also retrieve the height in pixels by using $('#history').css('height'); if you're not planning on doing any calculations.
for current height in px:
height = window.getComputedStyle(document.querySelector('textarea')).getPropertyValue('height')
for current width in px:
width = window.getComputedStyle(document.querySelector('textarea')).getPropertyValue('width')
change 'textarea' to '#history' or like a css selector. or textarea, since a variable is declared to select element.
Is there any way to check, if DIV with name for example "character" is overlaping DIV with name "ground" ?
I want to do this with clean Javascript, I know that jQuery is better, but that's what I don't want.
I saw this post: check collision between certain divs? , but it does not return anything.
Thanks for help.
First, I'd suggest you check out the HTML5 canvas element, as by the sounds of it, you want to make a game, and the canvas is great for that ;)
But, to answer your question, you could create or get div elements with document.createElement() or getElementById() respectively, and get their style properties either by getting their JS-set values (element.style) or use getComputedStyle if you'd prefer to set initial values in CSS.
Make sure that, however you get these CSS properties, they'll need to be parsed into something that JS can digest. For integer-based positions, parseInt() usually does the trick.
Next, you do the math. In this case, you'd want to see if the character div's top, plus its height, is greater than the top position of the ground. If it is, it has collided.
To set the style back to the div, you can just set the style property.
Here's an example (copied from this fiddle):
var character = document.getElementById("character");
var ground = document.getElementById("ground");
//We could use getComputedStyle to get the style props,
//but I'm lazy
character.style.top = "10px";
character.style.height = "40px";
ground.style.top = "250px";
//For every 33ms (about 30fps)
setInterval(function(){
//Get the height and position of the player
var charTop = parseInt(character.style.top),
charHeight = parseInt(character.style.height);
//and the top of the ground
var groundTop = parseInt(ground.style.top);
//linear gravity? Why now?
charTop += 5;
//If the character's bottom is hitting the ground,
//Stop moving
if(charTop + charHeight > groundTop) {
charTop = groundTop - charHeight;
}
//Set the character's final position
character.style.top = charTop + "px";
},33);
#character {
position: absolute;
width: 40px;
height: 40px;
left: 50px;
background-color: #F00;
}
#ground {
position: absolute;
width: 300px;
height: 60px;
left: 0px;
background-color: #A66;
}
<div id="character"></div>
<div id="ground"></div>
One more thing: While there are convoluted ways to get element positions when elements use different positioning properties (ex: the player uses top/left coordinates, where the ground uses bottom), it's a lot harder to manage.
The only jQuery that was being used in that linked answer was to get with width,height, and position of the divs, which are somewhat trivial to retrieve using pure JS:
CSS / JavaScript - How do you get the rendered height of an element?
jquery position() in plain javascript
How do I retrieve an HTML element's actual width and height?
It's not returning anything because the .top .left and height variables in the return statement were relying on jQuery functions that retrieve the information mentioned above.
I want to change the background color of in-viewport elements (using overflow: scroll)
So here was my first attempt:
http://jsfiddle.net/2YeZG/
As you see, there is a brief flicker of the previous color before the new color is painted. Others have had similar problems.
Following the HTML5 rocks instructions, I tried to introduce requestAnimationFrame to fix this problem to no avail:
http://jsfiddle.net/RETbF/
What am I doing wrong here?
Here is a simpler example showing the same problem: http://jsfiddle.net/HJ9ng/
Filed bug with Chromium here: http://code.google.com/p/chromium/issues/detail?id=151880
if it is only the background color, well why don't you just change the parent background color to red and once it scroll just change it to pink?
I change your CSS to that
#dad
{
overflow-y: scroll;
overflow-x: hidden;
width: 100px;
height: 600px;
background-color:red;
}
I remove some of you Jquery and change it to this
dad.bind('scroll', function() {
dad.css('background-color', 'pink');
});
And I remove this line
iChild.css('backgroundColor', 'red');
But is the Red color it is important that won't work for sure http://jsfiddle.net/2YeZG/5/
I like Manuel's Solution.
But even though I don't get what you're exactly trying to do, I want to point out a few things.
In your fiddle code, I saw that you included Paul Irish's Shim for requestAnimationFrame.
But you never use it.
(It's basically a reliable setTimeOut, nothing else) it's from frame based animations.)
So since you just want to change some CSS properties, I don't see why you would need it. Even if you want transitions, you should rely on CSS transitions.
Other than that your code could look something like
dad.bind('scroll', function() {
dad.css('background-color', 'pink');
eachElemNameHere.css('background-color','randomColor');
});
Also you should ideally not use something like that if you can help it. You should just add and remove class names and add all these properties in your CSS. Makes it work faster.
Also, again I don't quite get it, but you could use the jQuery function to find out each elements' position from the top to have better control.
Your problem seems to be that you only change the background color of the elements which have already been scrolled into view. Your code expects that the browser waits for your code to handle the scroll event before the browser redraws its view. This is most probably not a guarantee given by the HTML spec. That's why it flickers.
What you should do instead is to change the elements which are going to be scrolled into view. This is related to off screen rendering or double buffering as it is called in computer games programming. You build your scene off screen and copy the finished scene to the visible frame buffer.
I modified your first JSFiddle to include a multiplier for the height of the scroll area: http://jsfiddle.net/2YeZG/13/.
dad.bind('scroll', function() {
// new: query multiplier from input field (for demonstration only) and print message
var multiplier = +($("#multiplier")[0].value);
$("#message")[0].innerHTML=(multiplier*100)-100 + "% of screen rendering";
// your original code
var newScrollY = newScrollY = dad.scrollTop();
var isForward = newScrollY > oldScrollY;
var minVal = bSearch(bots, newScrollY, true);
// new: expand covered height by the given multiplier
// multiplier = 1 is similar to your code
// multiplier = 2 would be complete off screen rendering
var newScrollYHt = newScrollY + multiplier * dadHeight;
// your original code (continued)
var maxVal;
for (maxVal = minVal; maxVal < botsLen; maxVal++) {
var nxtTopSide = tops[maxVal];
if (nxtTopSide >= newScrollYHt) {
break;
}
}
maxVal = Math.min(maxVal, botsLen);
$(dadKids.slice(minVal, maxVal)).css('background', 'pink');
});
Your code had a multiplier of 1, meaning that you update the elements which are currently visible (100% of scroll area height). If you set the multiplier to 2, you get complete off screen updates for all your elements. The browser updates enough elements to the new background color so that even a 100% scroll would show updated elements. Since the browser seldom scrolls 100% of the area in one step (depends of the operating system and the scroll method!), it may be sufficient to reduce the multiplier to e.g. 1.5 (meaning 50% off screen rendering). On my machine (Google Chrome, Mac OS X with touch pad) I cannot produce any flicker if the multiplier is 1.7 or above.
BTW: If you do something more complicated than just changing the background color, you should not do it again and again. Instead you should check whether the element has already been updated and perform the change only afterwards.
I was able to implement the solution posted here ("position: fixed and absolute at the same time. HOW?") to get a div element to move with the rest of the page horizontally, but stay fixed vertically. However, this solution causes the selected element to move ALL the way to the left of the page (with what appears to be a 20px margin). I'm still new to javascript and jQuery, but as I understand it, the following:
$(window).scroll(function(){
var $this = $(this);
$('#homeheader').css('left', 20 - $this.scrollLeft());});
takes the selected element and, upon scrolling by the user, affects the CSS of the element so that its position from the left becomes some function of the current scrollbar position adjusted by the 20px margin. If this is correct? And if so, can anyone think of a way that I could change it so that instead of moving the selected element all the way to the left side of the window, we only move it as far left as my default CSS position for the body elements of the HTML document (shown below)?
body {font-size:100%;
width: 800px;
margin-top: 0px;
margin-bottom: 20px;
margin-left: auto;
margin-right: auto;
padding-left: 20px;
padding-right: 20px;}
EDIT: Here is a jsfiddle (code here) that I made to illustrate the issue. My page is designed so that when it is displayed in full-screen or near full-screen mode, the #homeheader element appears centered horizontally due to its width and the left and right margins being set to auto. As the page gets smaller and smaller the margins do as well, until they disappear altogether and are replaced by the padding-left and padding-right settings of 20px. So at this point (when the window is small enough that the margins disappear altogether), which is what the jsfiddle shows, the code appears to work as intended, but when the window is full-sized the JS overrides the CSS and pushes the div element all the way to the left (getting rid of the margin) upon any scrolling action.
There are two events you need to handle to get this to work correctly. First is the scroll event which you are pretty close on. The only thing you might want to do is to use offset to get the current left position value based on the document.
The other event which is not yet handled is the resize event. If you don't handle this then once a left position is defined your element (header) will be there always regardless of whether or not the user resizes the window.
Basically something like this should work:
var headeroffset;
var header = $('#homeheader');
// handle scroll
$(window).scroll(function() {
// auto when not defined
if (headeroffset === undefined) {
// capture offset for current screen size
headeroffset = header.offset();
}
// calculate offset
var leftOffset = headeroffset.left - $(this).scrollLeft();
// set left offset
header.css('left', leftOffset);
});
// handle resize
$(window).resize(function() {
// remove left setting
// (this stops the element from being stuck after a resize event
if (header.css('left') !== 'auto') {
header.css('left', '');
headeroffset = undefined;
}
});
JSFiddle example: http://jsfiddle.net/infiniteloops/ELCq7/6/
http://jsfiddle.net/infiniteloops/ELCq7/6/show
This type of effect can be done purely in css however, i would suggest taking a look at the full page app series Steve Sanderson did recently.
http://blog.stevensanderson.com/2011/10/05/full-height-app-layouts-a-css-trick-to-make-it-easier/
As an example you could do something like this:
http://jsfiddle.net/infiniteloops/ELCq7/18/
Try this
$('#homeheader').css('left', parseInt($('body').css('margin-left')) - $this.scrollLeft());});
What I did here is just replace 20 with body's left-margin value.