Attribute in Background Image url - javascript

First look at my code:
IMAGE:
<img class="small" src="http://thecodeplayer.com/uploads/media/iphone.jpg" width="200"/>
BACKGROUND URL:
<div class="small" style="background-image: url('http://thecodeplayer.com/uploads/media/iphone.jpg')" ></div>
In the IMAGE I can use an attribute src in jquery
attr("src");
But how can I do it to in a background Image URL? I made this code and added an attribute but it's not working, any ideas?
<div class="small" style="background-image: url(attr(data-image-src='http://thecodeplayer.com/uploads/media/iphone.jpg')" ></div>
attr("data-image-src");
Now the reason why I want this to happen is that if you will look in this CodePen:
codepen
The sample code is an image and they used an attr(src) in jquery code, but I want it to be a background image URL, not an image.

To get the background-image in jQuery you can use:
var urlFull = $('.small').css('background-image');
//You will get the full value here
url = urlFull.split('"');
//But for using it properly you have to split it and get the url with `"` which will be holding the url.
console.log(url[1]); //You will get URL here
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="small" style="background-image: url('http://thecodeplayer.com/uploads/media/iphone.jpg')"></div>
Now for your real issue:
$(document).ready(function() {
var native_width = 0;
var native_height = 0;
var urlFull = $('.small').css('background-image');
//You will get the full value here
url = urlFull.split('"');
//But for using it properly you have to split it and get the url with `"` which will be holding the url.
//console.log(urlFull);
$(".large").css("background-image", urlFull);
//Now the mousemove function
$(".magnify").mousemove(function(e) {
//When the user hovers on the image, the script will first calculate
//the native dimensions if they don't exist. Only after the native dimensions
//are available, the script will show the zoomed version.
if (!native_width && !native_height) {
//This will create a new image object with the same image as that in .small
//We cannot directly get the dimensions from .small because of the
//width specified to 200px in the html. To get the actual dimensions we have
//created this image object.
var image_object = new Image();
image_object.src = url[1];
//This code is wrapped in the .load function which is important.
//width and height of the object would return 0 if accessed before
//the image gets loaded.
native_width = image_object.width;
native_height = image_object.height;
} else {
//x/y coordinates of the mouse
//This is the position of .magnify with respect to the document.
var magnify_offset = $(this).offset();
//We will deduct the positions of .magnify from the mouse positions with
//respect to the document to get the mouse positions with respect to the
//container(.magnify)
var mx = e.pageX - magnify_offset.left;
var my = e.pageY - magnify_offset.top;
//Finally the code to fade out the glass if the mouse is outside the container
if (mx < $(this).width() && my < $(this).height() && mx > 0 && my > 0) {
$(".large").fadeIn(100);
} else {
$(".large").fadeOut(100);
}
if ($(".large").is(":visible")) {
//The background position of .large will be changed according to the position
//of the mouse over the .small image. So we will get the ratio of the pixel
//under the mouse pointer with respect to the image and use that to position the
//large image inside the magnifying glass
var rx = Math.round(mx / $(".small").width() * native_width - $(".large").width() / 2) * -1;
var ry = Math.round(my / $(".small").height() * native_height - $(".large").height() / 2) * -1;
var bgp = rx + "px " + ry + "px";
//Time to move the magnifying glass with the mouse
var px = mx - $(".large").width() / 2;
var py = my - $(".large").height() / 2;
//Now the glass moves with the mouse
//The logic is to deduct half of the glass's width and height from the
//mouse coordinates to place it with its center at the mouse coordinates
//If you hover on the image now, you should see the magnifying glass in action
$(".large").css({
left: px,
top: py,
backgroundPosition: bgp
});
}
}
})
})
/*Some CSS*/
* {
margin: 0;
padding: 0;
text-align: center
}
.magnify {
width: 200px;
margin: 50px auto;
position: relative;
cursor: none;
display: inline-block;
}
/*Lets create the magnifying glass*/
.large {
width: 175px;
height: 175px;
position: absolute;
border-radius: 100%;
/*Multiple box shadows to achieve the glass effect*/
box-shadow: 0 0 0 7px rgba(255, 255, 255, 0.85), 0 0 7px 7px rgba(0, 0, 0, 0.25), inset 0 0 40px 2px rgba(0, 0, 0, 0.25);
/*hide the glass by default*/
display: none;
background-repeat: no-repeat;
}
/*To solve overlap bug at the edges during magnification*/
.small {
display: block;
width: 200px;
height: 400px;
float: left;
background-size: contain;
background-repeat: no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Lets make a simple image magnifier -->
<div class="magnify">
<!-- This is the magnifying glass which will contain the original/large version -->
<div class="large"></div>
<!-- This is the small image -->
<div class="small" style="background-image:url('http://thecodeplayer.com/uploads/media/iphone.jpg')" width="200" />
</div>
</div>
Codepen if you want.
I hope this woks for you.

I think you have missed a Single quote in your attribute.
Change
<div class="small" style="background-image: url(http://thecodeplayer.com/uploads/media/iphone.jpg')" ></div>
to
<div class="small" style="background-image: url('http://thecodeplayer.com/uploads/media/iphone.jpg')" ></div>
Hope this helps.

First you have to set '' to url
<div class="small" style="background-image: url('http://thecodeplayer.com/uploads/media/iphone.jpg')" ></div>
To get url of background-image:
var url=$('.small').attr('src')
$('.large').css('background-image',"url('"+ url + "')");
.large{
background-repeat: no-repeat;
width: 175px;
height: 175px;
background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="small" src="http://thecodeplayer.com/uploads/media/iphone.jpg" width="200"/>
<div class="large"></div>

Related

Why am I receiving an "Expected an assignment or function call and instead saw an expression" and a "Missing semicolon" for this image zoom code"

I'm doing another image zoom project and again have encountered the same error where it states it "expected an assignment or function call and instead saw an expression"in the very last line in JS code. In addition, I have received an error in codepen stating that I am missing a semicolon even though there is a semicolon (unless I'm to put it somewhere else?) Help in resolving this issue would be greatly appreciated!
It is a bit disheartening that I encountered same error twice and twice, I am unable to resolve it on my own. I would also love to hear on what I can do to resolve issues like this and anything similar on my own.
Note:
I haven't added my code for the event listeners in the snippet.
// VARIABLES
const mainPic = document.querySelector("#pic");
const mainPicContainer = document.querySelector("#mainPictureContainer");
const pic1 = document.querySelector("#pic1");
const pic2 = document.querySelector("#pic2");
const pic3 = document.querySelector("#pic3");
const pic4 = document.querySelector("#pic4");
const pic5 = document.querySelector("#pic5");
const picArr = [
pic1,
pic2,
pic3,
pic4,
pic5
];
let picActive = 1;
const hoverRect = document.querySelector("#hoverRect");
//"zoom window"
const zoom = document.querySelector('#zoom');
//"zoom ratio"
let ratio = 3;
//"coordinates of mouse cursor"
let x, y, xx, yy;
//"Width & height of main picture in px"
let w1 = mainPicContainer.offsetWidth;
let h1 = mainPicContainer.offsetHeight;
//console.log(w1, h1); //420 854
//"width & height of selector"; the hoverbox
let w2 = hoverRect.offsetWidth;
let h2 = hoverRect.offsetHeight;
//"zoom window bg-img size"
zoom.style.backgroundSize = w1 * ratio + "px " + h1 * ratio + "px ";
//"zoom window width & height"
zoom.style.width = w2 * ratio + "px";
zoom.style.height = h2 * ratio + "px";
//"1/2 the selector shows outside of main picture; need 1/2 of width & height" (1/2 of the hoverbox)
w2 = w2 / 2;
h2 = h2 / 2;
pic1.classList.add("image-active");
// FUNCTION
//change the image of the mainPic block w/ current img
function changeImage(imgSrc, n){
//"This will change the main img"
mainPic.src = imgSrc;
//"remove box-shadow style from prev active side picture"
picArr[picActive - 1].classList.remove('image-active');
//"add box shadow to active side picture"
picArr[n - 1].classList.add('image-active');
//"update active side picture"
picActive = n;
}
//"moving the selector box" (#hoverRect)
function move(event){
//"how far the mouse cursor from an element"
x = event.offsetX; //"how far the cursor from left of element"
y = event.offsetY; //" ... top of element"
// console.log(x,y);
xx = x * ratio;
yy = y * ratio;
//"keeping the selector inside the main picture"
//"left of main picture"
if(x < w2){
x = w2;
}
//"right of main picture"
if(x > w1 - w2){
x = w1 - w2;
}
//"top..."
if(y < h2){
y = h2;
}
//"bottom..."
if(y > h1 - h2){
y = h1 - h2;
}
/* NOTE TO SELF
put the if statemnts before the hoverRect.style.left etc etc
for some reason, putting it after won't make the hover box stay w/i main picture"*/
//changing position of selector
//this is what will make the gray box move & the cursor will follow
hoverRect.style.left = x + "px";
hoverRect.style.top = y + "px";
//"changing bg image of zoom window"
zoom.style.backgroundPosition = '-' + xx + 'px ' + '-' yy + 'px'; //ERROR -
}
//IMAGES
.image-container{
display: flex;
flex-wrap: wrap;
background: lightGray;
padding: 10px;
div{
margin: 10px;
//background: blue;
}
}
.pictures{
width: 64px;
}
.shoe-image{
width: 100%;
}
///////// mainPic Div
.mainPicture{
width: 500px;//420px;
height: 500px; //840px;
position: relative;
background: yellow;
}
#pic{
width: 100%;
}
/* .explanation{
position: relative;
top: -514px;
height: 100%;
width: 30px;
background: blue;
}*/
//HOVER RECT
#hoverRect{
position: absolute;
margin: 0 !important;
padding: 0;
width: 200px;
height: 150px;
background-color: gray;
transform: translate(-50%, -50%); //this will make the cursor stay in center of the block
pointer-events: none; //this will resolve the glitchy movement of cursor
opacity: 0.4; //0
}
////////////////
//Zoom
.zoom{
position: relative;
top: 100px;
left: 20px;
background-image: url("https://assets.adidas.com/images/h_840,f_auto,q_auto:sensitive,fl_lossy/c3bd9dda9fdd4a7cbc9aad1e00dd0045_9366/NMD_R1_Primeblue_Shoes_White_GZ9260_01_standard.jpg");//pic1
box-shadow: 0 0 3px black;
}
// JS CLASS
.image-active{
box-shadow: 0 0 3px gray;
}
.hoverRect-active{
opacity: 1;
}
<header>
<div class="banner">
<span>for educational purposes only</span>
</div>
</header>
<section class="image-container">
<div class="pictures">
<img src="https://assets.adidas.com/images/h_840,f_auto,q_auto:sensitive,fl_lossy/c3bd9dda9fdd4a7cbc9aad1e00dd0045_9366/NMD_R1_Primeblue_Shoes_White_GZ9260_01_standard.jpg" alt="side view of shoes" id="pic1" class="shoe-image">
<img src="https://assets.adidas.com/images/h_840,f_auto,q_auto:sensitive,fl_lossy/a8dd72b84eb74a86a460ad1e00dd0db5_9366/NMD_R1_Primeblue_Shoes_White_GZ9260_02_standard_hover.jpg" alt="top view of shoes" id="pic2" class="shoe-image">
<img src="https://assets.adidas.com/images/h_840,f_auto,q_auto:sensitive,fl_lossy/680f4199aa6e4226b539ad1e00dd1513_9366/NMD_R1_Primeblue_Shoes_White_GZ9260_03_standard.jpg" alt="bottom/sole of shoes" id="pic3" class="shoe-image">
<img src="https://assets.adidas.com/images/h_840,f_auto,q_auto:sensitive,fl_lossy/8375f145b0f1441f8c7aad1e00dd0657_9366/NMD_R1_Primeblue_Shoes_White_GZ9260_06_standard.jpg" alt="inner side of shoes" id="pic4" class="shoe-image">
<img src="https://assets.adidas.com/images/h_840,f_auto,q_auto:sensitive,fl_lossy/497f4207b21b4933836bad1e00dd22d9_9366/NMD_R1_Primeblue_Shoes_White_GZ9260_05_standard.jpg" alt="back view of shoes" id="pic5" class="shoe-image">
</div>
<div class="mainPicture" id="mainPictureContainer">
<div class="hoverRect" id="hoverRect"></div>
<img src="https://assets.adidas.com/images/h_840,f_auto,q_auto:sensitive,fl_lossy/c3bd9dda9fdd4a7cbc9aad1e00dd0045_9366/NMD_R1_Primeblue_Shoes_White_GZ9260_01_standard.jpg" alt="side view of shoes" id="pic" >
<div class="explanation"></div>
</div>
<div class="zoom" id="zoom"></div>
</section>
<button>Show Var Explanation</button>
Because your missing a + at the end before yy
zoom.style.backgroundPosition = '-' + xx + 'px ' + '-' + yy + 'px';
neater and clearer
zoom.style.backgroundPosition = `-${xx}px -${yy}px`;

Use an image as a mask for another image

I'm making a website that I wanted to be a white page that you could stamp to make another image appear under. So when you click, you make a holepunch.
Like this exemple :
So I managed to have a randomized image in the background as I click which is fine for what I want, and to be able to .append() the holepunches.
But I don't know how to do the mask thing I've been digging online for a few things and help, and managed to make it work in certain cases but not that one...
It should be like that (I guess) :
image in the background
white shape in front
the star shape is making a holepunch in the white shape
For now, the only thing I managed to do is to have the picture besides a bigger holepunch (which is my original img) but when I click it doesn't make any holepunch, it justs add the stamp.
Here is the code :
var images = ["https://icatcare.org/app/uploads/2018/07/Thinking-of-getting-a-cat.png", "https://ichef.bbci.co.uk/news/1024/cpsprodpb/151AB/production/_111434468_gettyimages-1143489763.jpg"];
$(document.body).click(function(c) {
var tw = 100 / 2;
var th = 30 / 2;
var x = Math.floor((Math.random() * images.length));
document.getElementById('random').src = images[x];
$("#random").css({
position: 'absolute',
display: "block",
left: 0,
top: 0
});
var tw = 50 / 2;
var th = tw;
$('#holepunch:last').clone().appendTo(this).css({
position: 'absolute',
display: "block",
left: c.pageX - tw - $(this).position().left,
top: c.pageY - th + $(this).scrollTop()
});
});
body{
background: lightgrey;
width: 100vw;
height: 100vh;
z-index: 1;
opacity: 1;
}
.fauxbody{
z-index: 100;
position: fixed;
width: 100vw;
height: 100vh;
background-color: white;
top: 0;
left: 0;
-webkit-mask:
-moz-element(#holepunch) 1vw 1vh no-repeat,
linear-gradient(#fff 0 0);
mask-composite:exclude;
}
#random{
z-index: -100;
width: 100vw;
height: auto;
}
#holepunch{
width: 50px;
height: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<img id="random">
<div class ="fauxbody">
<img id="holepunch" src="https://oshi.at/iimtXg/Jqtz.png">
</div>
</body>
Here is an idea using multiple mask and CSS variables. The trick is to add an extra layer on each click. I removed the code related to background generation since it's irrelevant and quite easy to be added
var mask = "";
w = 60;
h = 60;
document.documentElement.addEventListener("click", function (c) {
mask+="url(https://i.ibb.co/FzmCjLL/Jqtz.png)"+(c.pageX-w/2)+"px "+(c.pageY-h/2)+"px/"+w+"px "+h+"px no-repeat,";
document.documentElement.style.setProperty("--mask", mask)
});
html {
background:url(https://picsum.photos/800/800) center/cover;
}
html::before {
content:"";
position: fixed;
background-color: #f3f3f3;
inset: 0;
-webkit-mask:
var(--mask)
linear-gradient(#fff 0 0);
-webkit-mask-reepat: no-repeat;
-webkit-mask-composite: destination-out;
mask-composite: exclude;
}
Also like below without mask-composite:
var mask = "";
w = 60;
h = 60;
document.documentElement.addEventListener("click", function(c) {
if (mask != "")
mask += ",";
mask += "url(https://i.ibb.co/FzmCjLL/Jqtz.png)" + (c.pageX - w / 2) + "px " + (c.pageY - h / 2) + "px/" + w + "px " + h + "px no-repeat";
document.documentElement.style.setProperty("--mask", mask)
});
html::before {
content: "";
position: fixed;
background: url(https://picsum.photos/800/800) center/cover;
inset: 0;
-webkit-mask: var(--mask, linear-gradient(#0000 0 0));
}
I would try to use canvas with white background and add a mouseclick event listener, which cuts out the canvas. I found another question on stack overflow what may can help you:
HTML5 Cut out circle from previous drawn strokes

Matching Wrapper+Canvas+Div to an Image's Size

I'm using heatmap.js in Google Apps Script and I am trying to resize the heatmap canvas (where I can actually plot points) to fit an image. How can I change the javascript or styling to make this work?
CODE: https://jsfiddle.net/nateomardavis/51h2guL9/
The wrapper has a black border.
The heatmap div has a blue border.
The canvas has a red border.
How it Should Work: I should be able to mark the heatmap anywhere on the image. The wrapper, heatmap div and canvas should all be sized based on the size of the image.
How it Currently Works: I can only mark the heatmap inside the blue/black border. My javascript resizes the canvas to fit the image, but not the bounds of the heatmap.
What I've Tried: You can see in the fiddle how I've tried to change what the javascript is resizing (lines 88-90).I also thought about using the using the image as the background-image of the heatmap div but the sizing wasn't right and I wanted to be able to save the heatmap and image as one layer (for printing/saving). I also tried changing the size of the image (line 101) but anything above 55% would cut the image off.
The screenshot below is just for reference, but the full working code is in the fiddle. I have it all under HTML because that's how it works in Google Apps Script.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script type="text/javascript" src="https://www.patrick-wied.at/static/heatmapjs/assets/js/heatmap.min.js"></script>
<style>
html, body {
width: 100%;
height: 100%;
}
html {
color: #333;
font-family: sans-serif;
font-size: 16pt;
font-weight: 100;
line-height: 1.5em;
}
.wrapper {
width: 100%;
height:100%;
background:rgba(0,0,0,.03);
border:3px solid black;
}
.heatmap {
width:100%;
height:100%;
background-position: top;
background-repeat: no-repeat;
background-size: contain;
position: relative;
border:3px solid blue;
}
.canvas {
border:3px solid red;
}
</style>
</head>
<body>
<button class="clear">Clear</button>
<button onclick="printPage()" class="print-btn no-print" style="">Print</button>
<p id="coords"></p>
<div id="wrapper" class="wrapper"> <!-- black box on web app-->
<div id="heatmap" class = "heatmap" style="position: relative;"> <!-- blue box on web app-->
<canvas id="canvas" class="canvas"></canvas> <!-- red box on web app-->
</div>
</div>
<script>
//CREATE HEATMAP
window.onload = function() {
var heatmapInstance = h337.create({
container: document.querySelector('.heatmap'),
gradient: {
'.25': 'black',
'.5': 'red',
'.75': 'white'
},
radius: 20
});
document.querySelector('.wrapper').onclick = function(ev) {
heatmapInstance.addData({
x: ev.layerX,
y: ev.layerY,
value: 1
});
};
document.querySelector('.clear').onclick = function() {
//heatmapInstance._renderer._clear();
heatmapInstance.setData({data:[]});
};
//RESIVE CANVAS TO FIT IMAGE
//http://jsfiddle.net/6ZsCz/1135/
var canvas = document.getElementById('canvas'); //v1
//var canvas = document.getElementById('heatmap'); //v2
//var canvas = document.getElementById('wrapper'); //v3
var ctx = canvas.getContext('2d');
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
var imageObj = new Image();
imageObj.onload = function() {
canvas.width = imageObj.width; // version 2
canvas.height = imageObj.height; // version 2
ctx.drawImage(imageObj,0,0); // version 2
//ctx.drawImage(imageObj, 0, 0, imageObj.width * 0.5, imageObj.height * 0.5); //version 1
};
imageObj.src = 'https://upload.wikimedia.org/wikipedia/commons/thumb/8/82/Soccer_Field_Transparant.svg/1200px-Soccer_Field_Transparant.svg.png';
};
//MOUSE COORDINATES
//works inside heatmap
function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
var coor = "X coords: " + x + ", Y coords: " + y;
document.getElementById("coords").innerHTML = coor;
}
const canvas = document.querySelector('.heatmap')
canvas.addEventListener('mousedown', function(e) {
getCursorPosition(canvas, e)
})
function printPage() {
window.print();
}
</script>
</body>
</html>
After lots of tinkering, I was able to figure it out: https://jsfiddle.net/nateomardavis/p1kwrhmv
I used img and gave it a background-image with CSS.
I then set the heatmap layer to relative and the image layer to absolute using the solution HERE.
Last, I then set the image layer css using the method outlined HERE.
.heatmap {
background-size: contain;
background-repeat: no-repeat;
width: 100%;
height: 300%; /*if the image is bigger than screen, this is needed */
position: relative;
}
.backgroundIMG {
background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/8/82/Soccer_Field_Transparant.svg/1200px-Soccer_Field_Transparant.svg.png');
background-size: contain;
background-repeat: no-repeat;
position: absolute;
width: 100%;
height: 0;
padding-top: 151.33%;
}

div's have margins when i set margin to 0 for div, and body

Im trying to get a div called touch-container to hold a canvas with 3 div's on top. I'm sizing them using javascript as well.
The problem is that each of the 3 div's have a margin which takes up the rest of the space in the container even though i specifically state 0 margin.
Here is a jsFiddle, if you inspect, you can see the margin Jsfiddle
HTML:
<div id = "touch-container">
<div id = "touch-left" class = "touch-control"></div>
<div id = "touch-middle" class = "touch-control"></div>
<div id = "touch-right" class = "touch-control"></div>
<canvas id = "canvas" width = "960" height = "560"></canvas>
</div>
CSS:
body {
margin: 0;
}
#touch-container{
width: 964px;
height: 560px;
display: inline-block;
margin: 0;
}
.touch-control{
position: relative;
margin: 0;
}
#touch-left{
background-color: red;
}
#touch-middle{
background-color: green;
}
#touch-right{
background-color: blue;
}
JS:
var leftTouch = document.getElementById('touch-left');
var upTouch = document.getElementById('touch-middle');
var rightTouch = document.getElementById('touch-right');
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var width = (canvas.width > canvas.height ? canvas.width : canvas.height);
var height = (canvas.height > canvas.width ? canvas.width : canvas.height);
leftTouch.style.width = (width/ 4) + 'px';
leftTouch.style.height = height + 'px';
upTouch.style.width = (width/ 2) + 'px';
upTouch.style.height = height + 'px';
rightTouch.style.width = (width/ 4) + 'px';
rightTouch.style.height = height + 'px';
ctx.fillRect(0,0,canvas.width, canvas.height);
I've colored them in so it should be a black square on the bottom, then from left to right, a red, green and blue square that takes up 25%, 50% 25% of the container respectively so you wont even be able to see the black canvas.
You didn't add any float in your elements(squares) so the squares don't know how they should be located, You most use float:left; to force squares to be in a same line and display:inline-block; wont works in your case (it just works for text only):
Jsfiddle
css:
#touch-container{
width: 964px;
height: 560px;
display: block;/* new update */
margin: 0;
}
#touch-left{
background-color: red;
float:left;/* new update from here to below */
display:block;
}
#touch-middle{
background-color: green;
float:left;/* new update from here to below */
display:block;
}
#touch-right{
background-color: blue;
float:left;/* new update from here to below */
display:block;
}
Margin refers to the spacing between block and inline-block level elements. Since divs are block elements, they stack on top of each other, and margin: 0 removes any space between them.
If you are looking to place the divs on top of the canvas element, you can achieve that with absolute positioning.
.touch-control {
position: absolute;
top: 0;
}
Then you can use your javascript to set the 'left' property of each div to where you want it, or positioning them individually with the css.

Resize a div from two ends

I am making a div resizer and cannot use any plugin as I need to customize many things on it's basis. I have achieved the task to resize the div from right side. In this I am manipulating the drag and calculating the units accordingly.
This script works fine if I keep the drag limited to right side.
But now my task is to resize it on both ends. I understand that some technique would be applied.
One technique I am trying to apply is the half the div and notice the distance from that center point e.g if the center is 200px and the mouse is at 10px then we can start decreasing the div from right and vice-versa.
var handle, measurement, isResizing;
var pageWidth = $(window).width();
var maxUnit = 300;
var minUnit = 50;
var maxLimit;
var adjustment = 0;
var container;
function calculateUnit(maxUnit, maxLimit, currentWidth) {
var offset = maxLimit - currentWidth;
return Math.ceil(maxUnit - offset);
}
function adjustContainer(innerContainerWidth, widthDiff, heightDiff) {
handle.css({
'width': (innerContainerWidth - widthDiff) + 'px',
'left': (widthDiff / 2) + 'px',
'top': (heightDiff / 2) + 'px'
});
}
function InitSizeCalculator() {
container = $("#topDrag");
console.log('height c', container.height());
//console.log('width c', container.width());
handle = $('#drag'), measurement = document.getElementById('measurement'), isResizing = false;
var heightDiff = container.height() - 170;
var widthDiff = container.width() - handle.width();
console.log('height c', heightDiff);
//maxLimit = (pageWidth <= 720) ? (pageWidth - 20) : (pageWidth - (pageWidth / 3)) - 60;
maxLimit = container.width();
adjustContainer(handle.width(), widthDiff, heightDiff);
//handle.css('width', maxLimit);
measurement.innerHTML = maxUnit + ' m';
}
InitSizeCalculator(); //initialize the variable first
handle.on('mousedown touchstart', function(e) {
isResizing = true;
lastDownX = e.clientX;
});
$(document).on('mousemove touchmove', function(e) {
var currentWidth = e.clientX - adjustment;
console.log(e.clientX);
// we don't want to do anything if we aren't resizing.
var unit = calculateUnit(maxUnit, maxLimit, currentWidth);
if (!isResizing || unit < minUnit || e.clientX > maxLimit)
return;
handle.css('width', currentWidth);
measurement.innerHTML = unit + ' cm';
})
.on('mouseup touchend', function(e) {
// stop resizing
isResizing = false;
});
//start
.imgContainer-p {
position: relative !important;
border-right: black 1px dashed;
border-left: black 1px dashed;
cursor: w-resize;
height: 220px
}
#drag {
position: absolute;
/*right: 500px;*/
top: 0;
bottom: 0;
/*width: 500px;*/
}
.imgWinder {
position: absolute;
top: 0;
left: 0;
width: 100%;
/*height: 200px;*/
height: 90%;
}
.imgPaper {
position: relative;
top: 0;
left: 0;
width: 100%;
/*height: 200px;*/
height: 90%;
}
.measurment-p {
width: 100%;
height: 20px;
border-bottom: 1px dashed black;
border-left: 1px dashed black;
border-right: 0px dashed black;
padding-top: 10px;
text-align: center;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-9 col-sm-12" id="topDrag">
<div class="imgContainer-p" id="drag">
<img id="imgWinder" class="imgWinder" draggable="false" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f6/Cylinder_geometry_rotated.svg/2000px-Cylinder_geometry_rotated.svg.png" />
<div style="width: 100%; height: 20px; border-bottom: 1px dashed black; border-left: 1px dashed black; border-right: 0px dashed black; padding-top: 10px; text-align: center">
<span style="background-color: #FFFFFF; padding: 0 10px;">
<span class="label label-default">Size</span>
<span class="label label-warning" id="measurement">01</span>
<!--Padding is optional-->
</span>
</div>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
When you drag an element from the right side to expand it, you're effectively updating the the right position of the element by adding the number of pixels covered in the drag action to its width.
This is how elements behave in a browser - left to right and hence similar to increasing width using CSS. But when you drag the opposite side of it, meaning the left hand side, the browser doesn't know how to handle this.
Now since you're resizing an element to the left hand side, you have space there, and the left edge of the element moves to a new position in that space, but you can't add width to the left. So, you have to give an illusion of it being added to the left hand side, by maintaining the right edge at its current position.
When you drag the element's left edge towards the left, calculate the difference between its old left position and its new left position, and add it to the width of the element. This will make sure the width expands to fit the new displacement.
When you drag the left edge towards the right side, to shrink the element, do the same procedure, except reduce it from the total width instead of adding it.
When you drag the right side towards the left, hence reducing the resize, calculate the difference and reduce it from the width.
This should help you with the code:
Adjust a div's height/width by dragging its left/top border without jQuery draggable?

Categories

Resources