How to get the width on where the mouse clicks a div? - javascript

I would like to use HTML/CSS/JS to have a <div> change its colour only up to a certain width. This certain length depends on where it is clicked inside the <div>.
Example:
I would give code, but it would just be of a <div>.
I don't know how to use CSS/JS to detect where the mouse clicks on <div> (i.e. on what width size).

You can achieve this like this
function changeWidth(event) {
let outerDiv = document.getElementById('outerDiv');
document.getElementById('innerDiv').style.width = event.clientX-outerDiv.offsetLeft+'px';
}
#outerDiv {
width: 400px;
height:200px;
border: 1px solid black;
}
#innerDiv {
width: 0px;
height: 200px;
background-color: red;
}
<div id = 'outerDiv' onclick = 'changeWidth(event)'>
<div id = 'innerDiv' ></div>
</div>
You have keep in check the position of the outerbox which you can get by using el.offSetLeft

A simple approach using background-image to create the color.
document.querySelector(".box").addEventListener("click", function(e){
var position = e.clientX - this.getBoundingClientRect().left;
this.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
});
.box {
border: 2px solid #c3c3c3;
height: 200px;
width: 400px;
}
<div class="box"></div>
e.clientX is the position relative to the window. So you can use the left position of the div from .getBoundingClientRect().left and subtract it to get the exact click position.
If you need this to work for multiple divs:
1) Add inline onclick to each <div>
function colourBackground (e, div) {
var position = e.clientX - div.getBoundingClientRect().left;
div.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
};
.box {
border: 2px solid #c3c3c3;
height: 200px;
width: 400px;
}
<div class="box" onclick="colourBackground(event, this)"></div>
<div class="box" onclick="colourBackground(event, this)"></div>
<div class="box" onclick="colourBackground(event, this)"></div>
Or 2) Use a forEach loop to add a click event to each <div>
document.querySelectorAll(".box").forEach(function(div) {
div.addEventListener("click", function(e){
var position = e.clientX - div.getBoundingClientRect().left;
div.style.backgroundImage = "linear-gradient(90deg, red " + position + "px, transparent " + position + "px)";
});
})
.box {
border: 2px solid #c3c3c3;
height: 200px;
width: 400px;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

I would do like:
//<![CDATA[
/* js/external.js */
let get, post, doc, html, bod, nav, M, I, mobile, S, Q, aC, rC, tC; // for use on other loads
addEventListener('load', ()=>{
get = (url, success, context)=>{
const x = new XMLHttpRequest;
const c = context || x;
x.open('GET', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
x.send();
}
post = function(url, send, success, context){
const x = new XMLHttpRequest;
const c = context || x;
x.open('POST', url);
x.onload = ()=>{
if(success)success.call(c, JSON.parse(x.responseText));
}
if(typeof send === 'object' && send && !(send instanceof Array)){
if(send instanceof FormData){
x.send(send);
}
else{
const fd = new FormData;
for(let k in send){
fd.append(k, JSON.stringify(send[k]));
}
x.send(fd);
}
}
else{
throw new Error('send argument must be an Object');
}
return x;
}
doc = document; html = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
var w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
var w = within || doc;
return w.querySelectorAll(selector);
}
aC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.add(...a);
return aC;
}
rC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.remove(...a);
return rC;
}
tC = function(){
const a = [].slice.call(arguments), n = a.shift();
n.classList.toggle(...a);
return tC;
}
// you can ignore most of the above code (but it's useful, so keep it) - put below on a separate page on another load - except the load end
const block = I('block'), colorStyle = block.firstChild.style;
let down = false;
function colorIt(e){
if(down)colorStyle.width = e.clientX-e.target.offsetLeft+'px';
}
function touchMode(){
block.onmousedown = block.onmousemove = undefined;
block.ontouchstart = e=>{
down = true; colorIt(e.touches[0]);
}
block.ontouchmove = e=>{
colorIt(e.touches[0]);
}
}
function mouseMode(){
block.ontouchstart = block.ontouchmove = undefined;
block.onmousedown = e=>{
down = true; colorIt(e);
}
block.onmousemove = colorIt;
}
block.onclick = ()=>{
down = false;
}
if(mobile){
touchMode();
}
else{
mouseMode();
}
}); // load end
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%; background:#ccc;
}
.main{
padding:10px;
}
#block{
width:200px; height:75px; background:#fff; border:1px solid #000; cursor:pointer;
}
#block>div{
width:0; height:100%; background:green;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<div id='block'><div></div></div>
</div>
</body>
</html>

Interesting question.
First, use this to get the location of your div: https://stackoverflow.com/a/10445639/11444910
Then get your mouse position on click: https://stackoverflow.com/a/23744762/11444910
Now that you can tell where your div is and where your mouse is when clicked, you should be able to tell if you are clicking inside of the div or not. Then it's a matter of applying the Y location of your mouse to the div, and using that to inform the color change.

Related

Why getComputedStyle() is not getting actual width and height is there any callback or event exists

I'm in such a situation where i need to wait till the image gets loaded once the image gets loaded i need to gets its computed height so that i can set the yellow color selector accordingly.
Question: based on computed height of image i'm setting yellow color selector. it works with setTimeout() randomly but i don't want such approach.
let images = ['https://via.placeholder.com/150','https://via.placeholder.com/110/0000FF/808080%20?Text=Digital.com','https://via.placeholder.com/80/0000FF/808080%20?Text=Digital.com'];
let image = `<img src="${images[Math.floor(Math.random()*images.length)]}"/>`
document.getElementById('content').innerHTML = `<div class="box">${image}</div>`;
//actual code
let height = window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height');
let imageWidth = window.getComputedStyle(document.querySelector('.box img'), null).getPropertyValue('width');
console.log('height',height,'width',imageWidth);
wrapImage = `<div style="width:calc(${imageWidth} + 10px);height:calc(${height} + 10px);position:absolute;left:0;top:0;border:1px solid yellow;"></div>`;
document.querySelector('.box').insertAdjacentHTML('beforeend',wrapImage);
.box{
width:100%;
height:auto;
border:1px solid red;
position:relative;
}
<div id="content">
</div>
with setTimeout it works but i don't want such approach,i want callback or some event once element is ready
let images = ['https://via.placeholder.com/150','https://via.placeholder.com/110/0000FF/808080%20?Text=Digital.com','https://via.placeholder.com/80/0000FF/808080%20?Text=Digital.com'];
let image = `<img src="${images[Math.floor(Math.random()*images.length)]}"/>`
document.getElementById('content').innerHTML = `<div class="box">${image}</div>`;
//actual code
setTimeout(() => {
let height = window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height');
let imageWidth = window.getComputedStyle(document.querySelector('.box img'), null).getPropertyValue('width');
console.log('height',height,'width',imageWidth);
wrapImage = `<div class="select" style="width:calc(${imageWidth} + 10px);height:${height};position:absolute;left:0;top:0;border:1px solid yellow;"></div>`;
document.querySelector('.box').insertAdjacentHTML('beforeend',wrapImage);
document.querySelector('.select').height = document.querySelector('.select').height + 10;
console.log('after computed height and added 10px',window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height'));
},700);
.box{
width:100%;
height:auto;
border:1px solid red;
position:relative;
}
<div id="content">
</div>
Please help me thanks in advance !!!
The image hasn't finished loading when you retrieved the height and width. To solve this, you'll need to wait for the images to load first, then get their height and width.
Listen for the window load event, which will fire when all resources (including images) have loaded completely:
let images = ['https://via.placeholder.com/150', 'https://via.placeholder.com/110/0000FF/808080%20?Text=Digital.com', 'https://via.placeholder.com/80/0000FF/808080%20?Text=Digital.com'];
let image = `<img src="${images[Math.floor(Math.random()*images.length)]}"/>`
document.getElementById('content').innerHTML = `<div class="box">${image}</div>`;
//actual code
window.addEventListener('load', function() {
let height = window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height');
let imageWidth = window.getComputedStyle(document.querySelector('.box img'), null).getPropertyValue('width');
console.log('height', height, 'width', imageWidth);
wrapImage = `<div class="select" style="width:calc(${imageWidth} + 10px);height:${height};position:absolute;left:0;top:0;border:1px solid yellow;"></div>`;
document.querySelector('.box').insertAdjacentHTML('beforeend', wrapImage);
document.querySelector('.select').height = document.querySelector('.select').height + 10;
console.log('after computed height and added 10px', window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height'));
});
.box {
width: 100%;
height: auto;
border: 1px solid red;
position: relative;
}
<div id="content">
</div>
To indicate selection you can use CSS outline property. That way you won't have to manage selection dimensions yourself.
Following is demo code. As you want to do it over multiple images, I've added 3 images. And you can select multiple images.
function changeImages() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].src = "https://via.placeholder.com/" + Math.floor(Math.random() * 50 + 50).toString() + "/0a0a0a/ffffff";
}
}
function setClickEvents() {
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].addEventListener("click", function(event) {
event.target.classList.toggle("selected");
});;
}
}
function init() {
document.getElementById('content').innerHTML = `<div id="box"></div>`;
var box = document.getElementById('box');
var img = document.createElement("img");
img.classList.add("selected");
box.appendChild(img);
box.appendChild(document.createElement("img"));
box.appendChild(document.createElement("img"));
setClickEvents();
changeImages();
}
#content {
padding: 15px;
margin: 10px;
}
#box {
width: 100%;
height: 120px;
border: 1px dotted red;
position: relative;
}
img {
margin: 15px;
}
/* use this class for marking selected elements */
.selected {
outline: thick double #f7d205;
outline-offset: 7px;
}
<!DOCTYPE html>
<html lang="en">
<body onload="init()">
<button onclick="changeImages()">Change Images</button>
<div id="content"></div>
</body>
</html>
Click on image to toggle selection.
If you want more flexibility then you can use Resize Observer. With this when you change src attribute of image tag you'll able to change selection size.
const imageObserver = new ResizeObserver(function(entries) {
for (let entry of entries) {
var img = entry.target;
let height = img.height + 10;
let width = img.width + 10;
console.log('Added 10px. height:', height, ' width:', width);
wrapImage = `<div class="select" style="width:${width}px;height:${height}px;position:absolute;left:0;top:0;border:1px solid #f7d205;"></div>`;
document.querySelector('.box').insertAdjacentHTML('beforeend', wrapImage);
}
});
function init() {
document.getElementById('content').innerHTML = `<div id="box" class="box"></div>`;
var box = document.getElementById('box');
var img = document.createElement("img");
img.src = "https://via.placeholder.com/" + Math.floor(Math.random() * 50 + 80).toString() + "/0a0a0a/ffffff";
box.appendChild(img);
imageObserver.observe(img);
}
<!DOCTYPE html>
<html lang="en">
<style>
#box {
width: 100%;
border: 1px dotted red;
position: relative;
}
</style>
<body onload="init()">
<div id="content"></div>
</body>
</html>
Note: Using same ResizeObserver you can observe multiple images:
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
imageObserver.observe(images[i]);
}
Edit: As requested, demonstrating observing img resize from parent div element. Here the image is wrapped in div #box. On resize img dispatches a custom event and parent handles it.
function handleChildResize(event) {
console.log('parent: got it! handling it.. ')
var img = event.data;
let height = img.offsetHeight + 10;
let width = img.offsetWidth + 10;
console.log('Added 10px. height:', height, ' width:', width);
wrapImage = `<div class="select" style="width:${width}px;height:${height}px;position:absolute;left:0;top:0;border:2px solid #f7d205;"></div>`;
if (document.querySelector('.box > .select')) {
document.querySelector('.box > .select').remove();
}
document.querySelector('.box').insertAdjacentHTML('beforeend', wrapImage);
event.stopPropagation();
}
const imgObserver = new ResizeObserver(function(entries) {
for (let entry of entries) {
var img = entry.target;
var event = new Event('childResized');
event.data = img;
console.log("img: i am resized. Raising an event.");
img.dispatchEvent(event);
}
});
function init() {
var box = document.getElementById('box');
box.addEventListener('load', (event) => {
console.log('The page has fully loaded');
});
var img = document.createElement("img");
img.src = "https://via.placeholder.com/" + Math.floor(Math.random() * 50 + 80).toString() + "/0a0a0a/ffffff";
box.appendChild(img);
imgObserver.observe(img);
box.addEventListener('childResized', handleChildResize, true);
}
<!DOCTYPE html>
<html>
<head>
<style>
#box {
width: 100%;
padding: 10px;
border: 1px solid red;
position: relative;
}
</style>
</head>
<body onload="init()">
<div id="content">
<div id="box" class="box"></div>
</div>
</body>
</html>
You could consider adding the 'load' event listener as a callback for image loading.
Please check the example:
const image = document.getElementById('image');
const handler = () => {
alert(image.height);
};
image.addEventListener('load', handler);
<img src="https://image.shutterstock.com/z/stock-vector-sample-stamp-grunge-texture-vector-illustration-1389188336.jpg" id="image" />
I see that you want to compute the final value of the get computed style
you see. The thing is that the getComputedStyle doesn't get updated.
So just make a function to do it!
let images = ['https://via.placeholder.com/150','https://via.placeholder.com/110/0000FF/808080%20?Text=Digital.com','https://via.placeholder.com/80/0000FF/808080%20?Text=Digital.com'];'
let image = `<img src="${images[Math.floor(Math.random()*images.length)]}"/>`
document.getElementById('content').innerHTML = `<div class="box">${image}</div>`;
//actual code
setTimeout(() => {
let height;
let imageWidth;
function calculateHeightAndWidth() {
height = window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height');
imageWidth = window.getComputedStyle(document.querySelector('.box img'), null).getPropertyValue('width');
}
calculateHeightAndWidth()
console.log('height',height,'width',imageWidth);
wrapImage = `<div class="select" style="width:calc(${imageWidth} + 10px);height:${height};position:absolute;left:0;top:0;border:1px solid yellow;"></div>`;
document.querySelector('.box').insertAdjacentHTML('beforeend',wrapImage);
document.querySelector('.select').height = document.querySelector('.select').height + 10;
calculateHeightAndWidth()
console.log('after computed height and added 10px',window.getComputedStyle(document.querySelector('.box'), null).getPropertyValue('height'));
},700);
.box{
width:100%;
height:auto;
border:1px solid red;
position:relative;
}
<div id="content">
</div>
I see that you are creating your imgNode on a fly using ternary which means you do not have it pre-created in your HTML. So for that, you can use the solution as below by creating an Image constructor.
const images = [
"https://via.placeholder.com/150",
"https://via.placeholder.com/110/0000FF/808080%20?Text=Digital.com",
"https://via.placeholder.com/80/0000FF/808080%20?Text=Digital.com"
];
const img = new Image();
img.addEventListener("load", (ev) => {
console.log(ev);
document.getElementById(
"content"
).innerHTML = `<div class="box">${ev.target}</div>`;
const height = window
.getComputedStyle(document.querySelector(".box"), null)
.getPropertyValue("height");
const imageWidth = window
.getComputedStyle(document.querySelector(".box img"), null)
.getPropertyValue("width");
console.log("height", height, "width", imageWidth);
const wrapImage = `<div style="width:calc(${imageWidth} + 10px);height:calc(${height} + 10px);position:absolute;left:0;top:0;border:1px solid yellow;"></div>`;
document.querySelector(".box").insertAdjacentHTML("beforeend", wrapImage);
});
img.src = `${images[Math.floor(Math.random() * images.length)]}`;

How to prevent a div from moving up when zooming in

So for starters this question may seem kind of vague, so I am going to do the best I can to describe my situation.
I have created a html page with adjustable sections (top left, top right, and bottom). There are dividers to adjust the X axis (between the top two sections) and to adjust the Y axis (between the top and bottom section). Everything appears to be working fine, however when I zoom in (using command + on the keyboard), it pushes the text within the bottom section above the Y axis adjuster.
I want instead for the text to be contained in the div beneath the Y axis adjuster and never slide on top of it (even when the screen is resized or zoomed in on).
The above image is what it looks like before zooming in. Notice how the text 'Element 3' is below the green line (Y axis adjuster).
The above image is what it looks like after zooming in. Notice how the text 'Element 3' raises above the green line (Y axis adjuster).
The error should be in the HTML code, not the JS, however I included the JS files for good measure.
I looked all over the internet for a solution but came up empty handed. I have tried simply bootstrapping the page by including the appropriate script tags but that did not work, as well as adjusting various css styles.
html file:
<!doctype html>
<head>
<title>resizer</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="Common.js"></script>
<script type="text/javascript" src="resizer.js"></script>
<style>
.element{
border: 1px solid #999999;
border-radius: 4px;
margin: 5px;
padding: 5px;
}
</style>
<script type="text/javascript">
function onresize() {
var element1 = document.getElementById("element1");
var element2 = document.getElementById("element2");
var element3 = document.getElementById("element3");
var ResizerY = document.getElementById("resizerY");
ResizerY.style.top = element3.offsetTop - 15 + "px";
var topElements = document.getElementById("topElements");
topElements.style.height = ResizerY.offsetTop - 20 + "px";
var height = topElements.clientHeight - 32;
if (height < 0)
height = 0;
height += 'px';
element1.style.height = height;
element2.style.height = height;
}
function resizeX(x) {
var element2 = document.getElementById("element2");
element2.style.width =
element2.parentElement.clientWidth
+ document.getElementById('rezizeArea').offsetLeft
- x
+ 'px';
}
function resizeY(y) {
var element3 = document.getElementById("element3");
var height =
element3.parentElement.clientHeight
+ document.getElementById('rezizeArea').offsetTop
- y
;
if ((height + 100) > element3.parentElement.clientHeight)
return;//Limit of the height of the elemtnt 3
element3.style.height = height + 'px';
onresize();
}
var emailSubject = "Resizer example error";
</script>
</head>
<body>
<div id="rezizeArea" style="top=0; bottom=0; right=0; left=0; width:100%; height:100%; overflow:hidden; position: absolute;" class="element">
<div id="topElements" class="element" style="overflow:auto; position:absolute; left: 0; top: 0; right:0;">
<div id="element2" class="element" style="width: 30%; height:10px; float: right; position: relative;">
Element 2
</div>
<div id="resizerX" style="width: 10px; height:100%; background: red; float: right;"></div>
<script type="text/javascript">
resizerX("resizerX", function (e) {
resizeX(e.pageX + 25);
});
</script>
<div id="element1" class="element" style="height:10px; overflow:auto;">
Element 1
</div>
</div>
<div id="resizerY" style="height:10px; position:absolute; left: 0; right:0; background: green;"></div>
<script type="text/javascript">
resizerY("resizerY", function (e) {
resizeY(e.pageY + 25);
});
</script>
<div id="element3" class="element" style="display: inline-block; height:100px; position:absolute; left: 0; bottom: 0; right:0;">
Element 3
</div>
</div>
<script type="text/javascript">
onresize();
</script>
<hr>
</body>
</html>
resizer.js:
function resizer(resizerID, mousemove, cursor) {
consoleLog("resizer(" + resizerID + ")");
var resizer = document.getElementById(resizerID);
resizer.style.cursor = cursor;
resizer.mousemove = mousemove;
resizer.onmousedown = function (e) {
try{
consoleLog("resizer.onmousedown(e)");
document.documentElement.addEventListener('mousemove', resizer.doDrag, false);
document.documentElement.addEventListener('mouseup', resizer.stopDrag, false);
} catch (e) {
ErrorMessage("resizer.onmousedown(...) failed! Your browser does not support this feature. " + e.message);
}
}
resizer.doDrag = function (e) {
if (e.which != 1){
consoleLog("mouseup");
resizer.stopDrag(e);
return;
}
//consoleLog("doDrag(e)");
resizer.mousemove(e);
}
resizer.stopDrag = function (e) {
consoleLog("stopDrag(e)");
document.documentElement.removeEventListener('mousemove', resizer.doDrag, false);
document.documentElement.removeEventListener('mouseup', resizer.stopDrag, false);
}
}
function resizerX(resizerID, mousemove) {
resizer(resizerID, mousemove, "e-resize");
}
function resizerY(resizerID, mousemove) {
resizer(resizerID, mousemove, "n-resize");
}
Common.js:
function MessageElement(Message) {
var element = document.getElementById('Message');
if (element == null) {
alert('ERROR: element Message == null. ' + Message);
return;
}
if (element.innerHTML != Message)
{
//consoleLog('Message: ' + Message);
element.innerHTML = Message + '<hr><div align="center"><input type="button" onclick="javascript: return MessageElement(\'\')" value="Close" style="margin-top:5px;" /></div>';
if (Message == "")
element.style.display = "none";
else element.style.display = "block";
}
}
function ErrorMessage(message, emailMe) {
consoleError(message);
//http://www.htmlhelp.com/reference/html40/entities/special.html
var body;
if (emailMe != false) {
body = message;
body = body.replace(/\n/g, "%0D%0A");
body = body.replace(/ /g, "%20");
body = body.replace(/"/g, "%22");
body = body.replace(/&/g, "%26");
}
message = message.replace(/</g, '<');
message = message.replace(/>/g, '>');
message = message.replace(/\n/g, '<BR>');
if (emailMe != false) {
//http://www.rapidtables.com/web/html/mailto.htm
if (typeof myEmail == 'undefined')
myEmail = "XXX";
message += "<BR><BR><a href=\"mailto:" + myEmail + "?subject=" + emailSubject + "&body=" + body + "\" >Email me about problem</a>"
}
MessageElement('<FONT style="color: red; background-color: white">ERROR: ' + message + '</FONT>');
}
function consoleLog(message) {
try{
console.log(message);//Do not works in WP
} catch(e) {
}
}
function consoleError(msg)
{
try
{
console.error(msg);
} catch(e) {
// alert(msg);
}
}

javascript applied border for group of absolute positioned images

I'm trying to apply a border to a div group of images (that need to be in absolute position mode, because the user select and move them around), and for some reason can't figure out why it doesn't work. In my code, I move the images around inside the div container, and want the overall div container to show a proper border, based on the size of the things inside. Here is some simplified code, perhaps only one small bug, I can't see it, to get it working.
Editing the code, after someone puts it into a snippet, is buggy for some reason. Here's one code fix: fixBorder() to tryBorder()
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test</title>
<style type="text/css">
.item {
position: absolute;
height: auto;
opacity: 1;
}
.mouseover { border:1px dashed green; }
</style>
<script>
function id(name) { return document.getElementById(name); }
function tryBorder() {
var w1 = id("part-1").style.width.replace("px", "");
var h1 = id("part-1").style.height.replace("px", "");
var l1 = id("part-1").style.left.replace("px", "");
var t1 = id("part-1").style.top.replace("px", "");
var w2 = id("part-2").style.width.replace("px", "");
var h2 = id("part-2").style.height.replace("px", "");
var l1 = id("part-2").style.left.replace("px", "");
var t1 = id("part-2").style.top.replace("px", "");
// "math" for the group size and position
var wOverlay = l2 - w1;
var hOverlay = t2 - h1;
var wg = w1 + w2 - wOverlay;
var hg = h1 + h2 - hOverlay;
var lg = ( l1 < l2 ) ? l1 : l2;
var tg = ( h1 < h2 ) ? h1 : h2;
// ok, now how to I apply that math? is it easy?
id('group').onmouseover = function(event) {
alert("on mouseover");
if (! event.shiftKey) elem.classList.add('mouseover');
else elem.classList.remove('mouseover');
}
id('group').style.left = lg + "px";
id('group').style.top = hg + "px";
id('group').style.width = width + "px";
id('group').style.height = height + "px";
}
</script>
</head>
<body onload="tryBorder();">
<div id="group" style="border:5px solid red">
<img id="part-1" class="item" src="https://dummyimage.com/640x4:3/">
<img id="part-2" class="item" src="https://dummyimage.com/300/09f.png/fff">
</div>
</body>
</html>
if i understood u try this code
function id(name) { return document.getElementById(name); }
function tryBorder() {
var w1 = id("part-1").style.width.replace("px", "");
var h1 = id("part-1").style.height.replace("px", "");
var l1 = id("part-1").style.left.replace("px", "");
var t1 = id("part-1").style.top.replace("px", "");
var w2 = id("part-2").style.width.replace("px", "");
var h2 = id("part-2").style.height.replace("px", "");
var l1 = id("part-2").style.left.replace("px", "");
var t1 = id("part-2").style.top.replace("px", "");
// "math" for the group size and position
var wOverlay = l2 - w1;
var hOverlay = t2 - h1;
var wg = w1 + w2 - wOverlay;
var hg = h1 + h2 - hOverlay;
var lg = ( l1 < l2 ) ? l1 : l2;
var tg = ( h1 < h2 ) ? h1 : h2;
// ok, now how to I apply that math? is it easy?
id('group').onmouseover = function(event) {
alert("on mouseover");
if (! event.shiftKey) elem.classList.add('mouseover');
else elem.classList.remove('mouseover');
}
id('group').style.left = lg + "px";
id('group').style.top = hg + "px";
id('group').style.width = width + "px";
id('group').style.height = height + "px";
}
#group{
border:5px solid red;
position: relative;
max-width: 100%;
height: 600px;
}
.item1 {
position: absolute;
height: auto;
opacity: 1;
max-width: 100%;
}
.item2 {
position: absolute;
height: auto;
opacity: 1;
max-width: 100%;
}
.mouseover { border:1px dashed green; }
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test</title>
</head>
<body>
<div id="group">
<img id="part-1" class="item1" src="https://dummyimage.com/640x4:3/">
<img id="part-2" class="item2" src="https://dummyimage.com/300/09f.png/fff">
</div>
</body>
</html>

javascript for draw rectangle over a image

I was doing a project on php with java script.I was try to draw a rectangle over a image using javascript.The rectangle can draw any where of the image with any size as compare with image size and also display the co ordinate of drawing rectangle.Please any one help me...I was tried different ways.....
<STYLE>
#rubberBand {
position: absolute;
visibility: hidden;
width: 0px; height: 0px;
border: 2px solid red;
}
</STYLE>
</HEAD>
<BODY>
<img name="myImage" id="myImage" src="a.jpg">
<DIV ID="rubberBand"></DIV>
<SCRIPT>
var IMG;
function startRubber (evt) {
if (document.all) {
var r = document.all.rubberBand;
r.style.width = 0;
r.style.height = 0;
r.style.pixelLeft = event.x;
r.style.pixelTop = event.y;
r.style.visibility = 'visible';
IMG.ondragstart = cancelDragDrop; // otherwise IE will try to drag the image
}
else if (document.getElementById) {
// firefox
evt.preventDefault();
var r = document.getElementById('rubberBand');
r.style.width = 0;
r.style.height = 0;
r.style.left = evt.clientX + 'px';
r.style.top = evt.clientY + 'px';
r.style.visibility = 'visible';
r.onmouseup = stopRubber;
}
IMG.onmousemove = moveRubber;
}
function moveRubber (evt) {
if (document.all) { // IE
var r = document.all.rubberBand;
r.style.width = event.x - r.style.pixelLeft;
r.style.height = event.y - r.style.pixelTop;
}
else if (document.getElementById) { // firefox
var r = document.getElementById('rubberBand');
r.style.width = evt.clientX - parseInt(r.style.left);
r.style.height = evt.clientY - parseInt(r.style.top);
}
return false; // otherwise IE won't fire mouseup :/
}
function stopRubber (evt) {
IMG.onmousemove = null;
}
function cancelDragDrop()
{
window.event.returnValue = false;
}
IMG = document.getElementById('myImage');
IMG.onmousedown = startRubber;
IMG.onmouseup = stopRubber;
</SCRIPT>
You need a wrapper so you can absolutely-position elements inside. The dimensions will vary, depending on your photo and where you want the box.
HTML:
<div class="wrapper">
<img src="...." />
<div class="box"></div>
</div>
CSS:
.wrapper {
position:relative;
}
.box {
position:absolute;
top:10px;
left:10px;
width:50px;
height:50px;
border:2px solid #ffffff;
background-color:transparent
}

Error in DIV tag scrolling

I had created one div window which is draggable,and created one child div (with in the window div) which is scrollable.Those work individually fine,but when I am trying to scroll the inner div by clicking on up and down arrow of scroll, the drag event is triggered once scrolling has been finished.I am not able to solve the issue....Any suggestions please...
Here is the code...
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE> Reporting</TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<style>
body{
font-family:Arial,Helvetica,sans-serif;
font-size:0.7em;
}
.Object{
width:190px;
height:100px;
border:1px solid black;
border-radius:7px 7px 7px 7px;
box-shadow:3px 3px 2px #D2D2D2;
position:absolute;
resize:
}
.ObjHdr{
color:#fff;
background:#363636;
padding:3px 0px 3px 7px;
border-radius:6px 6px 0px 0px;;
font-weight:bold;
cursor:move;
}
.ObjBody{
width:190px;
height:77px;
overflow:scroll;
}
.ObjEle{
padding:1px 0px 1px 4px;
color:#000;
border-bottom:1px solid black;
cursor:pointer;
}
</style>
</HEAD>
<BODY>
<div id="ObjCountry" class="Object">
<div class="ObjHdr">Country</div>
<div id =sd class="ObjBody" unselectable="on">
<div class="ObjEle">India</div>
<div class="ObjEle">China</div>
<div class="ObjEle">USA</div>
<div class="ObjEle">Iran</div>
<div class="ObjEle">Iraq</div>
<div class="ObjEle">Indonesia</div>
</div>
</div>
</BODY>
</HTML>
<script>
var DragHandler = {
// private property.
_oElem : null,
// public method. Attach drag handler to an element.
attach : function(oElem) {
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
// private method. Begin drag process.
_dragBegin : function(e) {
var oElem = DragHandler._oElem = this;
if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;
oElem.dragBegin(oElem,x,y);
//document.onmousemove = DragHandler._drag;
document.onmouseup = DragHandler._dragEnd;
oElem.onmousemove = DragHandler._drag;
oElem.onmouseup = DragHandler._dragEnd;
return false;
},
// private method. Drag (move) element.
_drag : function(e) {
var oElem = DragHandler._oElem;
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
e = e ? e : window.event;
var tmpX = x + (e.clientX - oElem.mouseX);
var tmpY = y + (e.clientY - oElem.mouseY);
if(tmpX<=0){tmpX = 0;}
if(tmpY<=0){tmpY = 0;}
oElem.style.left = tmpX + 'px';
oElem.style.top = tmpY + 'px';
oElem.mouseX = e.clientX;
oElem.mouseY = e.clientY;
oElem.drag(oElem, x,y);
return false;
},
// private method. Stop drag process.
_dragEnd : function() {
var oElem = DragHandler._oElem;
var x = parseInt(oElem.style.left);
var y = parseInt(oElem.style.top);
oElem.dragEnd(oElem, x, y);
oElem.onmousemove = null;
oElem.onmouseup = null;
document.onmousemove=null;
document.onmouseup=null;
DragHandler._oElem = null;
}
}
DragHandler.attach(document.getElementById('ObjCountry'));
</script>
I would made it as follows:
-create a new method in draghandler which calls only the dragend private method
-create a mousedown event to id="ObjHdr" - it starts the dragging
-create a mouseup event to id="ObjHdr" - it ends the dragging
into draghandler:
detach: function(oElem) {oElem.onmousedown = DragHandler._dragEnd; return oElem; },
document.getElementById("ObjHdr").onmousedown="DragHandler.attach(document.getElementById("ObjCountry"));"
document.getElementById("ObjHdr").onmouseup="DragHandler.detach(document.getElementById("ObjCountry"));"
result:
Drag-drop event starts only if you click on the header and ends on mouseup.
No action if you try to click on "ObjBody" - no dragprocess will start..
regards
Ozsi
This is because, the drag is applicable all-through the div, including scroll bar. since it is invoked on mousedown, it is invoked on clicking scroll bar too.

Categories