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;
});
Related
I have the following JS code I am using to move something around on the screen and then when i click a button I want to move everything back to where the original element loaded. Why does my following logic not work? I have also tried subtracting the gMouseDownOffsetX and gMouseDownOffsetY still the button does not transform the image back to the orgin of where it started.
I know the button works because it does in fact change other properties I set, but not the position.
$('#clickMe').click(function(){
$(#element).css({' transform : 'translate('+ -gMouseDownX + ')' });
$(#element).css({' transform : 'translate(' + -gMouseDownY + ')' });
});
let gMouseDownX = 0;
let gMouseDownY = 0;
let gMouseDownOffsetX = 0;
let gMouseDownOffsetY = 0;
function addListeners() {
document.getElementById('cursorImage').addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}
function mouseUp() {
window.removeEventListener('mousemove', divMove, true);
}
function mouseDown(e) {
gMouseDownX = e.clientX;
gMouseDownY = e.clientY;
var div = document.getElementById('cursorImage');
//The following block gets the X offset (the difference between where it starts and where it was clicked)
let leftPart = "";
if(!div.style.left)
leftPart+="0px"; //In case this was not defined as 0px explicitly.
else
leftPart = div.style.left;
let leftPos = leftPart.indexOf("px");
let leftNumString = leftPart.slice(0, leftPos); // Get the X value of the object.
gMouseDownOffsetX = gMouseDownX - parseInt(leftNumString,10);
//The following block gets the Y offset (the difference between where it starts and where it was clicked)
let topPart = "";
if(!div.style.top)
topPart+="0px"; //In case this was not defined as 0px explicitly.
else
topPart = div.style.top;
let topPos = topPart.indexOf("px");
let topNumString = topPart.slice(0, topPos); // Get the Y value of the object.
gMouseDownOffsetY = gMouseDownY - parseInt(topNumString,10);
window.addEventListener('mousemove', divMove, true);
}
function divMove(e){
var div = document.getElementById('cursorImage');
div.style.position = 'absolute';
let topAmount = e.clientY - gMouseDownOffsetY;
div.style.top = topAmount + 'px';
let leftAmount = e.clientX - gMouseDownOffsetX;
div.style.left = leftAmount + 'px';
}
addListeners();
I found that your position is moved by setting top and left. Why not try to directly set the top and left values to the default values?
Update:
try this:
$('#clickMe').click(function(){
$("#cursorImage").css({ left: 0, top: 0});
});
I have a code for changing CSS when scroll value >= 500:
var appearScroll = function(){
let fline = document.getElementById("skills__listone");
var skills = document.getElementById("skills");
var baselocation = 0;
fline.style.opacity = 0;
var distance = window.pageYOffset;
window.addEventListener("click", function(){
if ( distance >= 600 ){
fline.style.opacity = 1;
}
})
};
appearScroll();
This works only one time for example when scroll value is 200 and I click the mouse, there are nothing happens(It is ok, because distance >= 600), but when scroll value, for example 700, there are nothing happens, because click function already was running. the function have to observe for the distance value and depend on IT make a result
var distance = window.pageYOffset; this line should be inside the click event function to get the current window.pageYOffset value on every click.
like this:
window.addEventListener("click", function(){
var distance = window.pageYOffset; // <-- here
if ( distance >= 600 ){
fline.style.opacity = 1;
}
})
I have created a range slider where I am displaying a bubble with slider value within it.
( This example is based on https://css-tricks.com/value-bubbles-for-range-inputs/, I am simply attempted to recreate based on JS)
Here is a function that is suppose to make the bubble move along with the slider:
function displayValue(event) {
var rangeInput = document.getElementById('myRange');
var width = rangeInput.offsetWidth;
var min = rangeInput.getAttribute('min');
var max = rangeInput.getAttribute('max');
var newPoint = (event.target.value - min)/(max - min);
var offset = -1.3;
var newPlace;
if (newPoint < 0) {
newPlace = 0;
} else if (newPoint > 1 ) {
newPlace = width;
} else {
newPlace = width * newPoint + offset;
offset -= newPoint;
}
var outputElement = document.getElementById('myOutput');
outputElement.value = event.target.value;
outputElement.style.left = newPlace;
outputElement.style.marginLeft = offset = "%";
}
This function only partially works (as in the value insider the bubble updates but not the position)
Why is the sldier failing to update it's position ?
http://plnkr.co/edit/lt99U0uvMkPsibY54GAU
I found couple of anomalies in your code which might be typos.
Instead of:
outputElement.style.left = newPlace;
outputElement.style.marginLeft = offset = "%";
Try:
outputElement.style.left = newPlace + 'px';
outputElement.style.marginLeft = offset + "%";
I am trying to make this function works only when the screen size is above 1024px.
//Parallax background image
var velocity = 0.5;
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};$(window).bind('scroll', update); update();
Here is what I have tried to do:
//Parallax background image
var velocity = 0.5;
$(window).on("ready resize", function() {
if ($(window).width() < 770) {
function update(){
var pos = $(window).scrollTop();
$('.parallax').each(function() {
var $element = $(this);
var height = $element.height();
$(this).css('background-position', '40%' + Math.round((height - pos) * velocity) + 'px');
});
};});$(window).bind('scroll', update); update();
I really don't know what I am doing wrong...
You haven't stated what the problem you're coming across is. If it's "my code doesn't work", then perhaps you should check your syntax first. Your braces are messed up.
//Initialize velocity and empty update function
var velocity = 0.5;
var update = function () {};
//When window is ready (content loaded) OR resized, execute the following function
$(window).on("ready resize", function () {
if ($(window).width() >= 1024) { //Check if window width is 1024px wide or larger
update = function () { //Set update to run this function when executed.
var pos = $(window).scrollTop(); //Get scrollbar position https://api.jquery.com/scrollTop/
//For each element with 'parallax' class, execute the following function
$('.parallax').each(function () {
var $element = $(this); //Get the current parallax-classed element
var height = $element.height(); //Save the current height of this element
//Set the CSS of this parallax-classed element set the background position
$(this).css('background-position', '40% + ' + Math.round((height - pos) * velocity) + 'px');
});
};
} else { //Execute if screen width is < 1024px
update = function () {}; //Set update to do nothing
}
});
//When window is scrolled through, run the update function
$(window).bind('scroll', update);
//update();
Last line is unnecessary, as resize will handle function value, and scroll will handle the execution.
You were missing a + or - within the background-position setting.
So for example, if the result of your Math.round() was "30", then Javascript would interpret that line as $(this).css('background-position', '40%30px'); which obviously would cause issues. I'm sure you wanted it to say something like $(this).css('background-position', '40% + 30px');.
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";