DIV with CSS resize attribute detectable in Java Script - javascript

A DIV can be resize using CSS like this
resize: both;
overflow: auto;
So, when you mouse over the DIV , you will get the resize cursor on the lower right corner.
I tried to detect the cursor change to "resize" in Java Script with no luck so far. I tried to log the cursor style with this code on a "click event" when the cursor change to "resize" like this:
console.log(document.body.style.cursor);
console.log(e.target.style.cursor);
The log result id always a " " (empty) instead of a "resize" value.
Thanks in advance for your help.

Yes, I checked, string is empty for e.target.style.cursor. So I propose to solve the issue with a hack. We know, that an area where cursor changes is about 18×18 pixels, so we should detect cursor at this zone.
const textarea = document.querySelector('textarea');
const deltaX = 18;
const deltaY = 18;
const detectionOfCursorInLowerRightCorner = (e) => {
const rect = e.target.getBoundingClientRect();
const x = e.clientX; // Position X of cursor relative to the document.
const y = e.clientY; // Position Y of cursor relative to the document.
// Calculate lower and high edges of the area where cursor changes.
const lowEdgeX = rect.width - deltaX;
const highEdgeX = rect.width;
const lowEdgeY = rect.height - deltaY;
const highEdgeY = rect.height;
const elementCursorX = x - rect.x; // Position X of cursor relative to the element.
const elementCursorY = y - rect.y; // Position Y of cursor relative to the element.
console.log(' ');
console.log(elementCursorX, elementCursorY);
if (elementCursorX > lowEdgeX && elementCursorX <= highEdgeX && elementCursorY > lowEdgeY && elementCursorY <= highEdgeY) {
console.log('here'); // Cursor is in the area.
}
};
textarea.addEventListener('mousemove', detectionOfCursorInLowerRightCorner);
Do not forget do textarea.removeEventListener('mousemove', detectionOfCursorInLowerRightCorner) on element destroy. And define your own CSS class to detect when textarea has properties resize: both; and overflow: auto;.

Thanks for your answer. Indeed, I did something approximative (I skipped the Y axis logic) similar to your solution. On mousemove in the DIV, I consider that resize will occurs if my mouse X position is between the offetWidth-15px and offsetx. If not, I can drag my DIV.
I considered also the resize observer feature, but it was getting too complicated for multiple DIV elements.
The idea is to be add drag/resize events to my DIV elements for editing purpose over a canvas using absolute positioning.
Congratulation for your concise and well formatted answer and the time spent you spent on it.

Related

JS-based hidden image breaks body width and height

I use a Zoom JavaScript for zoom my images when I click on it.
This JavaScript creates a hidden copy of my image with bigger dimensions.
Problem is, when I load my page, the body takes a height and width according to the hidden image.
You can see at the right of the screen the menu doesn't fit with the width of the screen (the hidden image is not displayed).
Is there a solution when I load the page, the size of the body does not take into account the hidden image?
// To achieve this effect we're creating a copy of the image and scaling it up. Next we'll pull the x and y coordinates of the mouse on the original image. Then we translate the big image so that the points we are looking at match up. Finally we create a mask to display the piece of the image that we're interested in.
let settings = {
'magnification': 3,
'maskSize': 200
}
// Once our images have loaded let's create the zoom
window.addEventListener("load", () => {
// find all the images
let images = document.querySelectorAll('.image-zoom-available');
// querySelectorAll produces an array of images that we pull out one by one and create a Zoombini for
Array.prototype.forEach.call(images, (image) => {
new Zoombini(image);
});
});
// A Zoombini (or whatever you want to call it), is a class that takes an image input and adds the zoomable functionality to it. Let's take a look inside at what it does.
class Zoombini {
// When we create a new Zoombini we run this function; it's called the constructor and you can see it taking our image in from above
constructor(targetImage) {
// We don't want the Zoombini to forget about it's image, so let's save that info
this.image = targetImage;
// The Zoombini isActive after it has opened up
this.isActive = false;
// But as it hasn't been used yet it's maskSize will be 0
this.maskSize = 0;
// And we have to start it's coordinates somewhere, they may as well be (0,0)
this.mousex = this.mousey = 0;
// Now we're set up let's build the necessary compoonents
// First let's clone our original image, I'm going to call it imageZoom and save it our Zoombini
this.imageZoom = this.image.cloneNode();
// And pop it next to the image target
this.image.parentNode.insertBefore(this.imageZoom, this.image);
// Make the zoom image that we'll crop float above it's original sibling
this.imageZoom.style.zIndex = 1;
// We don't want to be able to touch it though, we want to reach whats underneat
this.imageZoom.style.pointerEvents = "none";
// And so we can translate it let's make it absolute
this.imageZoom.style.position = "absolute";
// Now let's scale up our enlarged image and add an event listener so that it resizes whenever the size of the window changes
this.resizeImageZoom();
window.addEventListener("resize", this.resizeImageZoom.bind(this), false);
// Now that we're finishing the constructor we need to addeventlisteners so we can interact with it
// This function is just below, but still exists within our Zoombini
this.UI();
// Finally we'll apply an initial mask at default settings to hide this image
this.drawMask();
}
// resizeImageZoom resizes the enlarged image
resizeImageZoom() {
// So let's scale up this version
this.imageZoom.style.width = this.image.getBoundingClientRect().width * settings.magnification + 'px';
this.imageZoom.style.height = "unset"
}
// This could be inside the constructor but it's nicer on it's own I think
UI() {
this.image.addEventListener('mousemove', (event) => {
// When we move our mouse the x and y coordinates from the event
// We subtract the left and top coordinates so that we get the (x,y) coordinates of the actualy image, where (0,0) would be the top left
this.mousex = event.clientX - this.image.getBoundingClientRect().left;
this.mousey = event.clientY - this.image.getBoundingClientRect().top;
// if we're not active then don't display anything
if (!this.isActive) return;
// The drawMask() function below displays our the portion of the image that we're interested in
this.drawMask();
});
// When they mousedown we open up our mask
this.image.addEventListener('mousedown', () => {
// But it can be opening or closing, so let's pass in that information
this.isExpanding = true;
// To do that we start the maskSizer function, which calls itself until it reaches full size
this.maskSizer();
// And hide our cursor (we know where it is)
this.image.classList.add('is-active');
});
// if the mouse is released, close the mask
this.image.addEventListener('mouseup', () => {
// if it's not expanding, it's closing
this.isExpanding = false;
// if the mask has already expanded we'll need to start another maskSizer to shrink it. We don't run the maskSizer unless the mask is changing
if (this.isActive) this.maskSizer();
});
// same as above, caused by us moving out of the zoom area
this.image.addEventListener('mouseout', () => {
this.isExpanding = false;
if (this.isActive) this.maskSizer();
});
}
// The drawmask function shows us the piece of the image that we are hovering over
drawMask() {
// Let's use getBoundingClientRect to get the location of our images
let image = this.image.getBoundingClientRect();
let imageZoom = this.imageZoom.getBoundingClientRect();
// We'll start by getting the (x,y) of our big image that matches the piece we're mousing over (which we stored from our event listener as this.mousex and this.mousey). This is a clunky bit of code to help the zooms work in a variety of situations.
let prop_x = this.mousex / image.width * imageZoom.width * (1 - 1 / settings.magnification) - image.x - window.scrollX;
let prop_y = this.mousey / image.height * imageZoom.height * (1 - 1 / settings.magnification) - image.y - window.scrollY;
// Shift the large image by that amount
this.imageZoom.style.left = -prop_x + "px";
this.imageZoom.style.top = -prop_y + "px";
// Now we need to create our mask
// First let's get the coordinates of the point we're hovering over
let x = this.mousex * settings.magnification;
let y = this.mousey * settings.magnification;
// And create and apply our clip
let clippy = "circle(" + this.maskSize + "px at " + x + "px " + y + "px)";
this.imageZoom.style.clipPath = clippy;
this.imageZoom.style.webkitClipPath = clippy;
}
// We'll use the maskSizer to either expand or shrink the size of our mask
maskSizer() {
// We're in maskSizer so we're changing the size of our mask. Let's make the mask radius larger if the Zoombini is expanding, or shrink it if it's closing. The numbers below might need to be adjusted. It closes faster than it opens
this.maskSize = this.isExpanding ? this.maskSize + 35 : this.maskSize - 40;
// It has the form of: condition ? value-if-true : value-if-false
// Think of the ? as "then" and : as "else"
// if we've reaached max size, don't make it any larger
if (this.maskSize >= settings.maskSize) {
this.maskSize = settings.maskSize;
// we'll no longer need to change the maskSize so we'll just set this.isActive to true and let our mousemove do the drawing
this.isActive = true;
} else if (this.maskSize < 0) {
// Our mask is closed
this.maskSize = 0;
this.isActive = false;
this.image.classList.remove('is-active');
} else {
// Or else we haven't reached a size that we want to keep yet. So let's loop it on the next available frame
// We bind(this) here because so that the function remains in context
requestAnimationFrame(this.maskSizer.bind(this));
}
// After we have the appropriate size, draw the mask
this.drawMask();
}
}
function zoom(e) {
var zoomer = e.currentTarget;
e.offsetX ? offsetX = e.offsetX : offsetX = e.touches[0].pageX
e.offsetY ? offsetY = e.offsetY : offsetX = e.touches[0].pageX
x = offsetX / zoomer.offsetWidth * 100
y = offsetY / zoomer.offsetHeight * 100
zoomer.style.backgroundPosition = x + '% ' + y + '%';
}
//My image generated after page load
.image-zoom-available {
height: unset;
border-radius: 30px;
z-index: 1;
pointer-events: none;
position: absolute;
width: 834.688px;
left: 526.646px;
top: 231.729px;
clip-path: circle(0px at 439.062px 987.812px);
}
<div class="col-12 col-xl-3 col-lg-5 justify-content-center ">
<div class="mb-3">
<img class="image-zoom-available" style="height:75%; border-radius: 30px" src='{{ asset(' /radio/ ') }}{{examen.idpatient.id}}_examen_{{examen.id}}_radio.png' id="image_radio" draggable="false" />
</div>
</div>
Try adding the following property in your hidden image css :
display: none
A non visible element still take space in the web page. Cf: What is the difference between visibility:hidden and display:none?
Remove or override the display: none property when you want to display the image.
I add
this.imageZoom.style.display = "none";
on the event : mouseup and
this.imageZoom.style.display = "block";
on mousedown event. And it's fix thanks !

e.pageX and pageY puts tooltip in an odd area

I've been looking for a way for a tooltip to sort of hover just above the cursor, I've seen a lot of posts recommending using the event pageX and pageY coordinates something like this:
const showToolTip = (evt, text) => {
let tooltip = document.getElementById("tooltip");
tooltip.innerHTML = text;
console.log(evt)
tooltip.style.visibility = "visible";
tooltip.style.left = evt.pageX +'px';
tooltip.style.top = evt.pageY + 'px';
}
However, when I do this the tooltip is generally like 400 pixels right of the mouse and 300 pixels below the mouse.
Something to note I'm doing this on an SVG:
<div id="tooltip" style="position: absolute; visibility: hidden;"></div>
<svg id="calendar" width="636px" height="84px"></svg>
....
// SVG is made up of several boxes and when one is hovered over the tooltip should appear:
box.addEventListener("mouseenter", (e) => {showToolTip(e, day)})
box.addEventListener("mouseout", () => {hideToolTip()})
svg.appendChild(box);
}
Again all this functionality works and the tooltip appears and moves around but it's just super far away from where the mouse is. I've tried to offset this by writing something like tooltip.style.left = (event.pageX - 300) + 'px' which sort of works but feels hacky and sometimes at different sizes it will do weird things.
Make sure your tooltip is not in a relative container, as that'll make the absolute position relative to that element.

Canvas with mousemove blocking links in div underneath

I'm having problems with using the canvas/mousemove. I want to be able to draw on the entire page whenever the mouse moves with a mousemove draw/paint tool but also still click text links that appear in various other divs. The issue I have is that the canvas which is currently fixed, has a transparent background color and is set to 100% width and height blocks the div underneath with a lower z-index, meaning the links can't be clicked. Using pointer-events:none on the canvas isn't the solution as it disables the mousemove effect. If I make the canvas z-index lower than the div's with the links I want to click, the drawing will just appear outside of the div.
What do I need to add or change to make this work? I basically just want to have a functioning webpage with a mouseover effect that will draw over the page whenever it moves.
Below is the script I'm using. And here's an example http://jsfiddle.net/zAF4d/1/
$(function() {
var letsdraw = false;
var theCanvas = document.getElementById('paint');
var ctx = theCanvas.getContext('2d');
theCanvas.width = window.innerWidth;
theCanvas.height = window.innerHeight;
var canvasOffset = $('#paint').offset();
$('#paint').mousemove(function(e) {
if (letsdraw === true) {
ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
ctx.stroke();
}
});
$('#paint').mousemove(function(e) {
$('.v').css('left', e.clientX + 'px');
$('.h').css('top', e.clientY + 'px');
letsdraw = true;
ctx.strokeStyle = 'blue';
ctx.lineWidth = 0.5;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
});
$(window).mouseout(function(e) {
// bind to the window mouse up, that way if you mouse up and you're not over
// the canvas you'll still get the release of the drawing.
letsdraw = true;
});
});
You say:
The issue I have is that the canvas which is currently fixed, has a transparent background color and is set to 100% width and height blocks the div underneath with a lower z-index, meaning the links can't be clicked. Using pointer-events:none on the canvas isn't the solution as it disables the mousemove effect. If I make the canvas z-index lower than the div's with the links I want to click, the drawing will just appear outside of the div.
I think you need to either do everything on canvas or use DOM and some sort of CSS tricks/animations.
$(function() {
var letsdraw = false;
var theCanvas = document.getElementById('paint');
var ctx = theCanvas.getContext('2d');
.
.
.
//if your div's are not same every time, determine similar prop so u can pull it here on to a canvas...by'ID' || 'Class' ...etc.
var div = document.getElementByID('div01');
dix.x;
div.y;
div.h;
.
.
.
**etc. or if u cannot for any reason pull actual div, just pass on it parameters here....
then u can use them here...*
like making collision model for drawing line over the top of it...
if (mouse.x > div.x && mouse.x < div.x + div.width && mouse.y > div.y && mouse.y < div.height) {
letsdraw = false;
}
....**within draw function
**'onclick' event listener try **
$(div)onclick function();
if whole div was pulled here then it will open links...but even if u pulled just div's parameters u just pass click coordinates on to div if link coordinates match
$(div)onclick function(){
load.page(url: <link>your link</>
}
sorry if mistaken something, didn't run it all together
But give it a go hope it helps;

how do i get the x and y position directly under the left bottom side of the input rectangle?

I'm thinking of implementing a custom auto-complete feature so basically my idea now is that i will make an abs positioned div and give it the position here:
(image) http://i.stack.imgur.com/3c5BH.gif
So my question is with a variable referencing the textbox, how do i get the x and y position directly under the left bottom side of the input rectangle?
My script must work in latest versions of IE / FF / Safari / Opera / Chrome
I know i can use a library to do it, but no i'm interested in learning how do they do it (or maybe better ways)?
This question is a lot more complicated than it seems and involves getting the position of the element relative to the document. The code to do so can be pulled from the jquery source (http://code.jquery.com/jquery-1.6.1.js -- search for "jQuery.fn.offset")
in jQuery:
var node = $('#textbox'),
pos = box.offset(); // the complicated piece I'm using jQuery for
node.top += node.height(); // node.offsetHeight without jQuery
node.left += node.width(); // node.offsetWidth without jQuery
The answer can be extremely simplified if you don't care about FF2 or Safari3:
var box = document.getElementById('yourTextBox').getBoundingClientRect(),
left = box.left,
bottom = box.bottom;
x = x offset
y = y offset - ( textbox height +
padding-top + padding-bottom )
Good comments! For my scenario, there is always an offset parent (which is why I use position - http://api.jquery.com/position/). In hopes that it might help someone else wanting a quick fix, here's the code:
// I have a parent item (item) and a div (detail)
// that pops up at the bottom left corner of the parent:
var jItem = $(item);
var pos = jItem.position();
var marginTop = parseInt(jItem.css('margin-top'));
if (isNaN(marginTop)) {
marginTop = 0;
}
$(detail).css("top", pos.top + jItem.outerHeight() + marginTop)
.css("left", pos.left);
$(detail).show();
Just give the box a defined width and height. Then, get its top and left property and add it with the width and height. Simple. I am gonna give you Pseodocode.
<STYLE>
object{width: 100px; height: 20px;}
</STYLE>
<SCRIPT>
x = object.left;
y = object.top;
x = x + object.width;
y = y + object.height;
</SCRIPT>

Get position of map area(html)?

Is this possible? I'm trying to find the x and y coordinates of the element in relation to the browser.
var position = $(this).position();
x = position.left;
y = position.right;
Doesn't work.
Is there any way to do this?
http://adamsaewitz.com/housing/
highlight the blue room 070
The problem lies in the fact that you are accessing the top/left of an area element.
The area element is not positioned where its coords say. This is handled behind the scenes by the dom/browser.
So you need to find the image that the area relates to and grab its offset.
var imgId = $(this).closest('map').attr('name');
var imgPos = $('#' + imgId).offset();
Then, you grab the coords attribute of the area and split it to get left/top/width and use those to pinpoint the location inside the image.
var coords = $(this).attr('coords').split(',');
var box = {
left: parseInt(coords[0],10),
top: parseInt(coords[1],10),
width: parseInt(coords[2],10)-parseInt(coords[0],10),
height: parseInt(coords[3],10)-parseInt(coords[1],10)
};
Take into consideration the width/height of the info box that appears (and since you animate it, take that into consideration as well) and you get to
x = imgPos.left + box.left + box.width/2 - 65; // 65 is the info width/2
y = imgPos.top + box.top -20 -160 -1; // 20 is the animation, 160 is the info height, 1 is a safe distance from the top
demo: http://www.jsfiddle.net/XBjwN/
Edit for updated question: Since you're using <area> it's a different story, and fetching from the coords attribute is much easier, like this:
var position = $(this).attr('coords').split(',');
x = +position[0] - 50;
y = +position[1] - 170;
The offsets are just to account for the hard-coded width/height of the tooltip itself. In addition to the above, you want to use top and left rather than margin-top and margin-left. Also to account for the #content <div>'s position in the page, give it a relative position for the tooltip to sit in, like this:
#content { position: relative; }
Then...instead of .after(), use .append() so it gets added inside that parent.
You can test the result here.
For original question:
The object .position() returns has top and left properties...but you want .offset() here anyway (it's relative to the document, where .position() is relative to the offset parent), so it should look like this:
var position = $(this).offset(),
x = position.left,
y = position.top; //not right!
Or this:
var position = $(this).offset();
var x = position.left;
var y = position.top;
...but without a single var comma-separated statement, or a var on each line, you're also creating (or trying to) global variables, which will blow up in IE.
$(document).ready(function () {
$('map').imageMapResize();
$('area').hover(function () {
$('.imgpopover').css({ "display": "block", "top": $(this).attr("coords").split(',')[1]+"px", "left": $(this).attr("coords").split(',')[0]+"px" })
$('.imgpopover label').text($(this).attr("title"))
}, )
});

Categories

Resources