Setting position to relative dynamically through Javascript - javascript

i am trying to create wave effect like Google but i am unable to set target's element position to 'relative' dynamically so that i can use 'waves-effect' class on any element.
Here is my code
let __ = (arg) => document.querySelectorAll(arg),
_ = (arg) => document.querySelector(arg);
Array.prototype.forEach.call( __(".waves-effect"), (elem) => {
elem.addEventListener('mousedown', makeWave);
elem.addEventListener('touchstart', makeWave);
});
function makeWave(event) {
let wave = document.createElement("div");
this.appendChild(wave);
// Here i want to set position to relative
// i have tried 'this.style.position = 'relative'' but it ain't working
wave.classList.add("c-ripple");
wave.setAttribute('id','i-ripple-effect');
let max = Math.max( this.clientWidth, this.clientHeight );
wave.style.height = wave.style.width = max + "px";
wave.style.left = event.clientX - this.offsetLeft - max / 2 + "px";
wave.style.top = event.clientY - this.offsetTop - max / 2 + "px";
wave.addEventListener("animationend", destroyRipple, false);
wave.addEventListener("webkitAnimationEnd", destroyRipple, false);
wave.addEventListener("oAnimationEnd", destroyRipple, false);
wave.addEventListener("MSAnimationEnd", destroyRipple, false);
}
function destroyRipple() {
_("#i-ripple-effect").remove();
}
I did search about this question, if this is answered already please correct me.
Thank YOU :)

Related

html2canvas won't take scrollHeight into account after resizing div

I am trying to usehtml2canvas to export some divs in .png format. My div has a greater height than my body which is not a problem because I can use the windowHeight option with myDiv.scrollHeight and it works perfectly.
function exp(e) {
html2canvas(e, {
windowWidth: e.scrollWidth,
windowHeight: e.scrollHeight * 1.12
}).then((canvas) => {
let a = document.createElement("a");
a.download = 'capture_' + date + '.png';
a.href = canvas.toDataURL("image/png");
a.click();
});
}
Now, the thing is, the div I'm "screening" is resizable. It shouldn't be a problem given I use the scrollHeight value but it takes the actual height into account instead of scrollHeight.
Working
Not working
I tried pretty much everything I could find on the internet, every configuration option on html2canvas, myDiv.scrollTo(0,0) as explain in this second answer
I don't know if it can help but here is my resize code :
function resize_height(e) {
topTab.scrollTop = 0
topTab.style.overflow = 'hidden'
const dx = m_pos_height - e.y;
m_pos_height = e.y;
topTab.style.height = (topTab.offsetHeight - dx) + "px"
botTab.style.height = cont - (topTab.offsetHeight - dx) + "px"
topTab.style.maxHeight = cont + 'px'
}
botTab.addEventListener("mousedown", function (e) {
if (e.offsetY < BORDER_SIZE_HEIGHT) {
m_pos_height = e.y;
document.addEventListener("mousemove", resize_height, false);
}
}, false);
document.addEventListener("mouseup", function () {
document.removeEventListener("mousemove", resize_height, false);
topTab.style.overflow = 'auto'
}, false);
topTab being the div I try to screen.

Draggable JS element not recentering on button click

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});
});

Keeping iframe/image ratio when resizing on height

I managed to keep the iframe's ratio for when the user resizes the window on width, but I have trouble adding the logic for when the user resizes the window on height due to conflicting logic, since the resize on width already alters the height of the iframe.
This is the function that gets called when resizing:
function calculateAspectRatioFit(width, height, ratio) {
if(height) {
let width = ((length)/(Math.sqrt((1)/(Math.pow(ratio, 2)+1))));
return Math.round(width);
} else if(width) {
let height = ((width)/(Math.sqrt((Math.pow(ratio, 2)+1))));
return Math.round(height);
}
}
But I believe that the problem lies in the trigger:
const resizeHandler = (e) => {
console.log("inside ", parseInt(iframeHeight), iframeElement.offsetHeight);
if(parseInt(iframeWidth) > iframeElement.offsetWidth) {
// overwrite inline styling
iframeElement.style.cssText = 'height: ' + calculateAspectRatioFit(iframeElement.offsetWidth, null, iframeRatio) + 'px!important';
} else if (parseInt(iframeHeight) > window.innerHeight) {
iframeElement.style.cssText = 'width: ' + calculateAspectRatioFit(null, iframeElement.offsetHeight, iframeRatio) + 'px!important';
}
}
Got any solutions for this? (pen below)
https://codepen.io/Dragosb/pen/WNoeXRa?editors=0011
Solved, as per the codepen (link is the same as the one in the original post):
Added a container for the iframe (if you are using a modal, that can be the container):
const resizeHandler = (e) => {
// get container measures
let computedContainerStyling = getComputedStyle(iframeContainer);
let containerWidth = parseInt(computedContainerStyling.width);
let containerHeight = parseInt(computedContainerStyling.height);
if ( (containerWidth / iframeRatio) > containerHeight){
iframeHeight = containerHeight;
iframeWidth = containerHeight * iframeRatio;
} else {
iframeWidth = containerWidth;
iframeHeight = containerWidth / iframeRatio;
}
iframeElement.style.width = Math.floor(iframeWidth) + 'px';
iframeElement.style.height = Math.floor(iframeHeight) + 'px';
}
window.addEventListener('resize', resizeHandler, false);
https://codepen.io/Dragosb/pen/WNoeXRa?editors=0011

Can't update my mouse position, because of my horizontal scroll (LocomotiveScroll)

I'm trying to make a custom cursor with the Ink Cursor by Ricardo Mendieta. https://codepen.io/mendieta/pen/WgvENJ
The cursor is working, but the problem I have is that I use a horizontal scroll with Locomotive Scroll. When I scroll, the mouse position doesn't get updated. I tried to fix this with a mousewheel function. I can console log the mousewheel event, but it doesn't update my mouse position.
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mousewheel', onMouseScroll);
const onMouseMove = (event) => {
mousePosition.x = event.clientX - width / 2;
mousePosition.y = event.clientY - width / 2;
resetIdleTimer();
};
const onMouseScroll = (event) => {
console.log(event);
mousePosition.x = event.clientX - width / 2;
mousePosition.y = event.clientY - width / 2;
resetIdleTimer();
};
const render = (timestamp) => {
const delta = timestamp - lastFrame;
positionCursor(delta);
lastFrame = timestamp;
requestAnimationFrame(render);
};
const positionCursor = (delta) => {
let x = mousePosition.x;
let y = mousePosition.y;
dots.forEach((dot, index, dots) => {
let nextDot = dots[index + 1] || dots[0];
dot.x = x;
dot.y = y;
dot.draw(delta);
if (!idle || index <= sineDots) {
const dx = (nextDot.x - dot.x) * 0.35;
const dy = (nextDot.y - dot.y) * 0.35;
x += dx;
y += dy;
}
});
};
Is there a way I can update the mouse position when I scroll when the scroll direction is horizontal.
I just figured this out for my situation, which I think is similar to yours. Not sure if this will help or not - hopefully it does.
scroll.on('scroll', (instance) => {
let customCursor = document.querySelector(".customCursor");
let scrollPx = instance.scroll.x + "px";
customCursor.style.left = scrollPx;
});
So instead of trying to reconfigure where the mouse position is, I'm simply updating the "left" attribute of the custom cursor to be in sync with how much the horizontally laid out Locomotive scroll container is being scrolled.

Draggable dot on rotatable div, dot following rotation after dragend

i'm trying to make dot that follows mouse cursor. It was all working, but when i rotated it a bit it all messed up, because bounding box has changed.
I was using this:
http://en.wikipedia.org/wiki/Rotation
(That's why i initially negated y, and than negated new value again)
I will need to read how far that dot is from center and it's angle (but related to the initial "0" rotation state)
I have to add something to rPX based on angle, but i don't know how to calculate it. Can anyone relate?
Inner div is only for creating center of coordinate system.
https://jsfiddle.net/jre86rdd/14/
var currentMousePosition = {
x:0,
y:0
}
var angle = Math.PI/6
document.addEventListener("mousemove",function(event){
currentMousePosition.x = event.clientX;
currentMousePosition.y = event.clientY;
applyMovement(event)
})
function applyMovement(event){
var rPX = event.clientX - getElementOffSetFromParentLeft(document.getElementById("light").parentNode) - 5;
var rPY = -(event.clientY - getElementOffSetFromParentTop(document.getElementById("light").parentNode) - 5);
var XinCircle = rPX*Math.cos(angle)-rPY*Math.sin(angle)
var YinCircle = rPX*Math.sin(angle)+rPY*Math.cos(angle)
if(XinCircle > -70 && XinCircle < 70)
document.getElementById("light").style.left = XinCircle + "px";
if(rPY > -70 && rPY < 70)
document.getElementById("light").style.top = -YinCircle + "px";
//console.log(rPX + " X " + XinCircle )
//console.log(rPY + " Y " + YinCircle )
}
var getElementOffSetFromParentLeft = function (htmlElement) {
var parentRect = htmlElement.parentNode.getBoundingClientRect(),
bodyRect = document.body.getBoundingClientRect();
console.log(parentRect.left)
//I need to add something here, it's 75 for 30, i have no idea how i have calculated it
return parentRect.left - bodyRect.left + 75;
}
var getElementOffSetFromParentTop = function (htmlElement) {
var parentRect = htmlElement.parentNode.getBoundingClientRect(),
bodyRect = document.body.getBoundingClientRect();
return parentRect.top - bodyRect.top;
}
For the mouse movement, it's a very simplified code using jQuery:
$('.wrapper, .outer').mousemove(function(e){
$('#light').css('left', e.pageX);
$('#light').css('top', e.pageY);
});
https://jsfiddle.net/jre86rdd/30/
Tell me if this was what you wanted.
Edit: Also you need to move the light div outside of the wrapper class because it is affected by your CSS
With your new comment, this is my answer:
HTML:
<div class="wrapper">
<div class="outer">
<div class="inner">
</div>
</div>
</div>
<div class="dot" id="light"></div>
JS:
var timeout;
var down = false;
var inside = 0; //Not a boolean because .outer can trigger false when .wrapper is true
$(document).mousedown(function() {
down = true;
}).mouseup(function() {
down = false;
}).mouseleave(function() {
down = false;
});
$('.wrapper, .outer').mouseenter(function(){
inside++;
}).mouseleave(function() {
inside--;
});
$('#light').mousedown(function () {
var x, y;
timeout = setInterval(function () {
if(down){
$(document).mousemove(function(event) {
x = event.pageX;
y = event.pageY;
});
if (inside > 0){
$('#light').css('left', x - 5);
$('#light').css('top', y - 5);
}
}
else
{
clearTimeout(timeout);
}
}, 20);
});
https://jsfiddle.net/jre86rdd/124/

Categories