I have written a function that positions a tooltip just above a textbox.
The function takes two arguments:
textBoxId - The ID of the textbox above which the tooltip will appear.
Example: "#textBoxA"
toolTipId - The ID of the tooltip which will appear above the textbox.
Example: "#toolTipA"
function positionTooltip(textBoxId, toolTipId){
var hoverElementOffsetLeft = $(textBoxId).offset().left;
var hoverElementOffsetWidth = $(textBoxId)[0].offsetWidth;
var toolTipElementOffsetLeft = $(toolTipId).offset().left;
var toolTipElementOffsetWidth = $(toolTipId)[0].offsetWidth;
// calcluate the x coordinate of the center of the hover element.
var hoverElementCenterX =
hoverElementOffsetLeft + (hoverElementOffsetWidth / 2);
// calculate half the width of the toolTipElement
var toolTipElementHalfWidth = toolTipElementOffsetWidth / 2;
var toolTipElementLeft = hoverElementCenterX - toolTipElementHalfWidth;
$(toolTipId)[0].style.left = toolTipElementLeft + "px";
var toolTipElementHeight = $(toolTipId)[0].offsetHeight;
var hoverElementOffsetTop = $(textBoxId).offset().top;
var toolTipYCoord = hoverElementOffsetTop - toolTipElementHeight;
toolTipYCoord = toolTipYCoord - 10;
$(toolTipId)[0].style.top = toolTipYCoord + "px";
$(toolTipId).hide();
$(textBoxId).hover(
function(){ $(toolTipId + ':hidden').fadeIn(); },
function(){ $(toolTipId + ':visible').fadeOut(); }
);
$(textBoxId).focus (
function(){ $(toolTipId + ':hidden').fadeIn(); }
);
$(textBoxId).blur (
function(){ $(toolTipId+ ':visible').fadeOut(); }
);
}
The function works fine upon initial page load:
However, after the user resizes the window the tooltips move to locations that no longer display above their associated textbox.
I've tried writing some code to fix the problem by calling the positionTooltip() function when the window is resized but for some reason the tooltips do not get repositioned as they did when the page loaded:
var _resize_timer = null;
$(window).resize(function() {
if (_resize_timer) {clearTimeout(_resize_timer);}
_resize_timer = setTimeout(function(){
positionTooltip('#textBoxA', ('#toolTipA'));
}, 1000);
});
I'm really at a loss here as to why it doesn't reposition the tooltip correctly as it did when the page was initially loaded after a resize.
Your logic for calculating the position of the tooltip only fires initially when you call positionTooltip. You want to call it to recalculate position before the fadeIn call.
i don't understand why you use a setTimeout() to launch your function. Try
$(function(){
// all your code onDocumentReady
...
...
$(window).resize(function() {
positionTooltip('#textBoxA', ('#toolTipA'));
});
});
That worked like a charm for me, the only drawback is that sometimes it dosen't get the proper X,Y position, apparently not it's compensating with object's padding/margin values, i did a dirty fix by adding those values manually before they are set like:
toolTipElementLeft = toolTipElementLeft + 40;
$(toolTipId)[0].style.left = toolTipElementLeft + "px";
and
toolTipYCoord = toolTipYCoord + 25;
$(toolTipId)[0].style.top = toolTipYCoord + "px";
Related
I want to call a function only once every time the div #blinds reach their max-height at 430px, how can I do this?
My Codepen: https://codepen.io/cocotx/pen/YzGBpVJ
window.addEventListener('mousemove', function(event) {
var blinds = document.getElementById("blinds");
blinds.style.height = event.clientY + 'px';
});
One polling way is adding the code below in your js if there are other behaviours changing the size of the element. Simply change 400 to the value you want.
var blinds = document.getElementById("blinds");
setInterval(() => {
let rect = blinds.getBoundingClientRect();
if (rect.height > 400)
console.log(" reach 400");
}, 100);
window.addEventListener('mousemove', function(event) {
var blinds = document.getElementById("blinds");
blinds.style.height = event.clientY + 'px';
// i added here the condition
if(blinds.offsetHeight > 430 /*the value you want*/){
//call your function
}
});
Notice that this doesn't work if you use blinds.style.height instead of blinds.offsetHeight, there's a difference between using these but i im still trying to figure it out.
I would suggest to clean your code:
window.addEventListener('mousemove',handler);
function handler(event){
...
if(blinds.offsetHeight >430){
//call your function
...
//and maybe remove the listener
window.removeEventListener('mousemove',handler);
}
};
EDIT: try this code
function hasReachedMax(){
var styles = getComputedStyle(blinds);
var borderBottom = styles.borderBottom.split("px")[0]; //this is to get the number of pixels
var borderTop = styles.borderTop.split("px")[0];
var maxH = styles.maxHeight.split("px")[0];
var currentDivSize = blinds.offsetHeight-borderBottom-borderTop;
return maxH == currentDivSize;
};
function resetTrigger(){
//the condition to reset your trigger, for example making the div element at least 5 px smaller than maxHeight
var styles = getComputedStyle(blinds);
var borderBottom = styles.borderBottom.split("px")[0];
var borderTop = styles.borderTop.split("px")[0];
var maxH = styles.maxHeight.split("px")[0];
var currentDivSize = blinds.offsetHeight-borderBottom-borderTop;
return maxH-currentDivSize>5;
};
//this should be part of your main code
var trigger = true;
window.addEventListener('mousemove', function(event) {
var blinds = document.getElementById("blinds");
blinds.style.height = event.clientY + 'px';
if(hasReachedMax()&&trigger){
//call your function
console.log("Im called now");
trigger=false;
}
if(resetTrigger()) trigger=true;
});
As a self-improvement exercise I am building a piece of plain js that takes a set of various sized squares (all of the same aspect ratio) and lays them out in a fluid grid so that there are no gaps.
After spending the evening I have a very basic model that works for the test data I have given it.
The last problem I need to solve before I can justify sinking more time in it is this:
When resizing the browser window the width of the parent element (#container) is not being re calculated.
This width is being used with the aspect ratio of the grid items to calculate the row height so when you resize the window everything shifts correctly except the vertical position.
The function being called by window.onresize is as follows
function() {
var parentElem = this.element;
console.log(parentElem.offsetWidth);
var elems = parentElem.getElementsByTagName('*'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + 'tile' + ' ') > -1) {
var ele = elems[i];
var tile_size = ele.getAttribute('data-grid-size');
var tile_col = ele.getAttribute('data-grid-col');
var tile_row = ele.getAttribute('data-grid-row');
var col_width = (100 / this.options.cols); // column width in %
var row_height = (parentElem.getElementWidth() / this.options.cols) / this.options.tile_ratio;
var left_offset = col_width * tile_col;
var top_offset = row_height * tile_row;
// Position tiles
var currentStyle = ele.getAttribute('style');
ele.setAttribute('style', currentStyle + ' left: ' + left_offset + '%; top: ' + top_offset + 'px;');
}
}
}
See the full fiddle here.
So any ideas as to why the width of the element is not being recalculated?
This line from your fiddle:
window.onresize = gridfill.layoutGrid();
...doesn't assign your function as a resize handler, it calls your function immediately and tries to assign the return value as a resize handler. You need to remove the parentheses:
window.onresize = gridfill.layoutGrid;
Except to keep the correct context within the function you will need to use:
window.onresize = gridfill.layoutGrid.bind(gridfill);
Note that the .bind() function is not supported by IE<=8, but you can use a polyfill, or just wrap the function call:
window.onresize = function() { gridfill.layoutGrid(); };
Demo: http://jsfiddle.net/WzaXF/1/
I want to have a custom scrollbar on my main div which has buttons to go to certain parts of the div, however anchor points don't seem to work when using the flexcroll plugin (I know i'm doing anchor points correctly because when I disable flexcroll on that div they work fine)
Is their any method I could use to set up the anchor points?
EDIT FOUND SOLUTION: On the buttons I want to click to go to the specific place in the document I can put onclick="Wrapper.fleXcroll.setScrollPos(false,0);"
I've used this function in the past. FYI, I don't know anything about flexcroll, so this is not tested with that:
var isInt = function(val) {
return (parseInt(val, 10) == val);
};
var scrollTo = function(node) {
var pNode = node.parentNode;
var offset = node.offsetTop - pNode.offsetTop;
var pHeight = pNode.clientHeight;
var height = node.clientHeight;
var scrollOffset = pNode.scrollTop;
var buffer = 10;
var scroll = null;
if (scrollOffset > offset) {
scroll = offset - buffer;
} else if (pHeight + scrollOffset < offset + height + buffer) {
scroll = offset + height + buffer - pHeight;
}
if (isInt(scroll)) {
pNode.scrollTop = scroll;
}
};
This is the pure JS version. (example)
Here is an example of a jQuery version, which animates the scroll event: jQuery version
I have to move an image using jQuery / Javascript exactly like this url
I have done similar to this using my own logic. But it gets cut for smaller / bigger image either at the top or at the bottom. Or It moves completely at the bottom and doesn't move completely at the top or vice-versa.
http://jsfiddle.net/N2k6M/
(Please move the horizontal scrollbar to view full image.)
Can anyone please suggest me / Fix my code here, so that my mousemove functionality works perfectly fine and upper / lower part of image moves properly.
I need a seamless movement of image just like in the original url.
HTML PART
<div id="oheight" style="z-index:1000;position:absolute;">123</div> , <div id="yheight" style="z-index:1000;position:absolute;">123</div>
<img id="avatar" src="http://chaikenclothing.com/wp-content/uploads/2012/05/11.jpg![enter image description here][2]" style="position:absolute;overflow:hidden;" />
JAVASCRIPT PART
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script lang="javascript">
var doc_height = $(document).height();
function updateAvatarPosition( e )
{
var avatar = document.getElementById("avatar");
var yheight = parseInt(e.y);
var ywidth = e.x;
//avatar.style.left = e.x + "px";
if((yheight)<(doc_height)){
yheight*=2;
avatar.style.top = '-'+(yheight) + "px";
}
console.log(yheight);
$("#oheight").html(doc_height);
$("#yheight").html(yheight);
/*if((ywidth)<(doc_height/6)){
avatar.style.top = '-'+e.x + "px";
}*/
}
document.getElementById("avatar").onmousemove = updateAvatarPosition;
</script>
see http://jsfiddle.net/N2k6M/7/
function updateAvatarPosition( e )
{
var img_height = $('#avatar').height();
var window_height = $(window).height();
var factor = (img_height - window_height) / window_height;
if(factor > 1) {
var avatar = document.getElementById("avatar");
var yheight = parseInt(e.clientY);
avatar.style.top = '-'+(yheight * factor) + "px";
}
}
#Felix's answer is great and works well, however it's doing more work than necessary. There are a few constants that do not need to be reassigned with every call. By setting these outside of the updateAvatarPosition function you can improve performance some.
var avatar = $('#avatar');
img_height = avatar.height(),
window_height = $(window).height();
function updateAvatarPosition( e )
{
var factor = (img_height - window_height) / window_height,
yheight = parseInt(e.clientY);
if (factor < 1) {
factor = 1;
}
avatar.css('top', -(yheight * factor));
}
avatar.on('mousemove', updateAvatarPosition);
Updated Fiddle
Avatar is referenced more than once so no need to traverse the DOM multiple times, especially multiple times within a constantly cycling event like mousemove. Make a variable reference to avatar outside of the function. The image_height and window_height are also constants and do not change, so there is no need to recalculate them every time as well. If there is the chance that they would change, reassignment should be handled by a resize event.
Would have replied/commented directly under #Felix's answer but apparently don't have enough influence yet. :-/
i think this is something you want
http://jsfiddle.net/N2k6M/6/
var doc_height = $(document).height();
function updateAvatarPosition( e )
{
var avatar = document.getElementById("avatar");
var yheight = parseInt(e.clientY);
var ywidth = e.clientX;
if((yheight)<(doc_height)){
yheight*=2;
avatar.style.top = '-'+(yheight) + "px";
}
/*if((ywidth)<(doc_height/6)){
avatar.style.top = '-'+e.x + "px";
}*/
}
document.getElementById("avatar").onmousemove = updateAvatarPosition;
Is it possible to know whether or not an HTML element like image is viewable in current viewport or it will be visible on scroll?
If it is viewable completely or partially then how can I get the amount of portions is visible?
I am trying to explain it from the following image:
The two images at the bottom is partially visible within the viewport and these will be completely visible if one scroll down a little bit.
Now I want to get the the aforesaid information.
In the actual scenario I am trying to get the popup-zoom effect on hover of image in my album like google image search. Everything is fine, except if the images are placed in the described manner then the zoomed div also displaying in half.
Normal condition where image is completely in viewport:
And partially in viewport:
I really appreciate your help.
The code:
var albumDetailOnReady = function() {
$('.image').each(function(){
var photo = $(this);
var wrap = $(findParentByClassName(document.getElementById(photo.attr('id')), 'wrap'));
var row = $(findParentByClassName(document.getElementById(wrap.attr('id')), 'albumDetailRow'));
var visibleZone = $(wrap).find('.alDtlColumn');
var pictureBlock = $(visibleZone).find('.pictuteBlock');
var hiddenZone = $(wrap).find('.hiddenZone');
$(photo).load(function(){
if(177 > $(photo).width()){
var imgleft = ($(pictureBlock).width() - $(photo).width())/2 + 'px';
$(photo).css({'left': imgleft});
}
});
$(photo).hover(function(){
var y;
if($(photo).height() > $(photo).width()) {
y = ($(visibleZone).offset().top - 50) + 'px';
} else {
y = ($(visibleZone).offset().top + 50) + 'px';
}
var x;
if($(row).find('.wrap:first').attr('id') === $(wrap).attr('id')) {
x = ($(visibleZone).offset().left - 10) + 'px';
} else if($(row).find('.wrap:last').attr('id') === $(wrap).attr('id')) {
x = ($(visibleZone).offset().left - 50) + 'px';
} else {
x = ($(visibleZone).offset().left - 20) + 'px';
}
$(hiddenZone).css({
'top': y,
'left': x,
'position': 'absolute',
'z-index': '10'
});
$(hiddenZone).fadeIn('fast');
}, function(){
});
$(hiddenZone).hover(function(){},function(){
$(hiddenZone).hide().stop(true, true);
});
});
}
var findParentByClassName = function(element, clazz) {
while (element.parentNode) {
element = element.parentNode;
if (hasClass(element, clazz)) {
return element;
}
}
return null;
}
function hasClass(element, cls) {
var regex = new RegExp('\\b' + cls + '\\b');
return regex.test(element.className);
}
I am unable to show any HTML as I haven't have any, I am working in ADF framework.
But for an explanation:
I have two zone for each image: visible and hidden. Both of them are in a wrap. Now on hover an image I am showing the hidden div. The top and left of the hidden div is measured by the top and left of the visible div with some condition.
jQuery.Viewport
Very helpfull and lightweight jQuery plugin that makes an element as a handy viewport for displaying elements with absolute position. The plugin is hosted on GitHub. You can see it in action right there:
https://github.com/borbit/jquery.viewport