I need the image in the both divs below to be in the same position even if the other div changes height or width. I have tried calculating top and left to % from px but still it is not working. I have also tried calculating the % of how big or small other div is and adding or removing the top and left to the image in other div and still no luck.
To check the issue, drag the image around inside the first div and click on submit. Now the image inside the bottom div should be in the same position as the above div, same top and left distance.
Please help. Thanks.
Here is the fiddle : https://jsfiddle.net/kashyap_s/gLdt62nh
var zoomLevel = 1;
$("#myimage").draggable({
start: function() {
},
stop: function() {
}
});
$('#save').click(function() {
var topcss = $('#myimage').css('top');
var leftcss = $('#myimage').css('left');
var transformcss = zoomLevel;
topcss = topcss.replace('px', '');
leftcss = leftcss.replace('px', '');
topcss = parseInt(topcss);
leftcss = parseInt(leftcss);
var parentWidth = $('#dragDiv').outerWidth()
var parentHeight = $('#dragDiv').outerHeight()
console.log('leftcss', leftcss, 'width', parentWidth)
console.log('topcss', topcss, 'height', parentHeight)
var percentLeft = leftcss / parentWidth * 100;
var percentTop = topcss / parentHeight * 100;
console.log('percentLeft', percentLeft, 'percentTop', percentTop)
transformcss = parseFloat(transformcss).toFixed(2);
var result = {
"top": topcss,
"left": leftcss,
'percentTop': percentTop,
'percentLeft': percentLeft,
'parentWidth': parentWidth,
'parentHeight': parentHeight,
"transform": "scale(" + transformcss + ")"
};
var output = JSON.stringify(result);
console.log('output', output)
$("#newimg").css({
'left': leftcss
});
$("#newimg").css({
'top': topcss
});
});
.transperentimage {
width: 497px;
height: 329px;
border: 1px solid black;
margin: 0 auto;
}
#bigimg {
width: 651px;
height: 431px;
border: 1px solid black;
margin: 0 auto;
}
img {
border: 2px solid red;
padding: 3px;
width: auto;
height: auto;
cursor: move;
max-height: 180px;
}
#newimg {
position: absolute;
max-height: 180px;
width: auto!important;
height: auto!important;
max-width: 100%!important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="transperentimage" id="dragDiv">
<img id="myimage" src="agent.png">
</div>
<button id="save">Save</button>
<div id="bigimg">
<img id="newimg" src="agent.png" />
</div>
$(function() {
$("#logo1").draggable({
containment: "parent",
drag: function() {
}
});
});
function setpos() {
var image1_w = $("#logo1").width();
var div1_w = $(".div1").width();
var image2_w = $("#logo2").width();
var div2_w = $(".div2").width();
var image1_h = $("#logo1").height();
var div1_h = $(".div1").height();
var image2_h = $("#logo2").height();
var div2_h = $(".div2").height();
var div1_aw = div1_w - image1_w;
var div2_aw = div2_w - image2_w;
var div1_ah = div1_h - image1_h;
var div2_ah = div2_h - image2_h;
var div
var xPos = $('#logo1').css('left');
var yPos = $('#logo1').css('top');
var ratio_w = parseFloat(div1_aw) / parseFloat(div2_aw);
var ratio_h = parseFloat(div1_ah) / parseFloat(div2_ah);
//let act = 1.39;
var div2_nw = parseFloat(xPos) / ratio_w;
var div2_nh = parseFloat(yPos) / ratio_h;
$("#posX").text('Div left:' + div2_nw);
$("#posA").text('Div Top:' + div2_nh);
$("#logo2").css({
'left': div2_nw,
'top': div2_nh
});
}
.div1 {
width: 497px;
height: 329px;
border: 1px solid black;
}
.div2 {
width: 651px;
height: 431px;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<p>Drag my logo.</p>
<div class="div1">
<img src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" style=" position: relative; left: 0px; top: 0px;" width="100" id="logo1">
</div>
<br>
<div class="div2">
<img style="position: relative;left: 0px;top: 0px" src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" width="100" id="logo2">
</div>
<br>
<button onclick="setpos();">
Save
</button>
<div id="posX">
</div>
<div id="posA">
</div>
<div id="posz">
</div>
<div id="posZ1">
</div>
Solved! check this out
HTML
<p>Drag my logo.</p>
<div class="div1">
<img src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" style=" position: relative; left: 0px; top: 0px;" width="100" id="logo1">
</div>
<br>
<div class="div2">
<img style="position: relative;left: 0px;top: 0px" src="https://smteg.sefion.com/perfectmetal/assets/ui/sefion.jpg" width="100" id="logo2">
</div>
<br>
<button onclick="setpos();">
Save
</button>
<div id="posX"></div>
<div id="posA"></div>
JS CODE
$( function() {
$( "#logo1" ).draggable(
{
containment: "parent",
drag: function() {
}
}
);
} );
function setpos()
{
var image1_w = $("#logo1").width();
var div1_w = $(".div1").width();
var image2_w = $("#logo2").width();
var div2_w = $(".div2").width();
var image1_h = $("#logo1").height();
var div1_h = $(".div1").height();
var image2_h = $("#logo2").height();
var div2_h = $(".div2").height();
var div1_aw = div1_w-image1_w;
var div2_aw = div2_w-image2_w;
var div1_ah = div1_h-image1_h;
var div2_ah = div2_h-image2_h;
var div
var xPos = $('#logo1').css('left');
var yPos = $('#logo1').css('top');
var ratio_w = parseFloat(div1_aw)/parseFloat(div2_aw);
var ratio_h = parseFloat(div1_ah)/parseFloat(div2_ah);
//let act = 1.39;
var div2_nw = parseFloat(xPos)/ratio_w;
var div2_nh = parseFloat(yPos)/ratio_h;
$("#posX").text('Div left:' + div2_nw);
$("#posA").text('Div Top:' + div2_nh);
$("#logo2").css({ 'left' : div2_nw, 'top' : div2_nh});
}
CSS
.div1{
width: 497px;
height: 329px;
border: 1px solid black;
}
.div2{
width: 651px;
height: 431px;
border: 1px solid black;
}
For your newimg, the parent must have a position that is relative. This way, the absolute positioning will be relative to the parent and not the body.
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
Consider the following code.
$(function() {
var zoomLevel = parseFloat(1 - ($("#dragDiv").outerWidth() / $("#bigimg").outerWidth()).toFixed(2));
function log(str) {
if ($(".log").length) {
$(".log").html(str);
} else {
$("<div>", {
class: "log"
}).html(str).appendTo("body");
}
}
function getPos(el) {
var par = $(el).parent();
var pos = {
top: parseInt($(el).css("top")),
left: parseInt($(el).css("left")),
zoom: "scale(" + (1 + zoomLevel) + ")",
parWidth: par.outerWidth(),
parHeight: par.outerHeight()
};
pos['perLeft'] = parseFloat((pos.left / pos.parWidth).toFixed(2)) * 100;
pos['perTop'] = parseFloat((pos.top / pos.parHeight).toFixed(2)) * 100;
return pos;
}
$("#myimage").draggable({
containment: "parent",
drag: function(e, ui) {
log("Left: " + ui.position.left + ", Top: " + ui.position.top);
},
start: function() {
// coordinates('#myimage');
},
stop: function() {
// coordinates('#myimage');
var p = getPos(this);
$(this).attr("title", JSON.stringify(p));
}
});
$('#save').click(function() {
var result = getPos($("#myimage"));
var output = JSON.stringify(result);
var nLeft = Math.round(result.perLeft * (1 + zoomLevel)) + "%";
var nTop = Math.round(result.perTop * (1 + zoomLevel)) + "%"
console.log(output, nLeft, nTop);
$("#newimg").css({
left: nLeft,
top: nTop
});
var p = getPos($("#newimg"));
$("#newimg").attr("title", JSON.stringify(p));
});
});
.transperentimage {
width: 497px;
height: 329px;
border: 1px solid black;
margin: 0 auto;
}
#bigimg {
width: 651px;
height: 431px;
border: 1px solid black;
margin: 0 auto;
position: relative;
}
img {
border: 2px solid red;
padding: 3px;
width: auto;
height: auto;
cursor: move;
/* max-width: 100%; */
max-height: 180px;
}
#newimg {
position: absolute;
max-height: 180px;
width: auto!important;
height: auto!important;
max-width: 100%!important;
}
.log {
font-size: 11px;
font-family: "Arial";
position: absolute;
top: 3px;
left: 3px
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="transperentimage" id="dragDiv">
<img id="myimage" src="https://i.imgur.com/4ILisqH.jpg">
</div>
<button id="save">Save</button>
<div id="bigimg">
<img id="newimg" src="https://i.imgur.com/4ILisqH.jpg" />
</div>
See More: https://www.w3schools.com/css/css_positioning.asp
Updated
Looking at it further, I am guessing that you might be trying to reposition the bigimg in relationship to myimage position. This requires scaling the percentage.
For example, if we move myimage to the far left, it will be at left: 247, and this is roughly 49% of 499px. 49% of 653 is around 319, and this would not place the image where we want it. We want it at 401.
bigimg is about 24% larger than dragDiv, so we need to scale our percentage. 49 * 1.24 = 60.74, round up to 61. 653 * .61 = 398.33 so better yet not perfect.
Related
Here is an example of what i want to achieve:
https://www.flambette.com/en/
I have tried to change the css properties of images but that effect does not satisfy my needs.
I have tried the following code:
mydocument.on('scroll',function() {
if (mydocument.scrollTop() > 10 && mydocument.scrollTop() < 200 ) {
$('#first').css('top', '320px');
$('#first').css('left', '215px');
$('#first').css('transition', '0.5s');
}
else {
$('#first').css('top', '300px');
$('#first').css('left', '200px');
$('#first').css('transition', '0.5s');
}
});
This is supposed to move an image when you scroll between 10 and 200 px.
var container = document.getElementById('container');
var windowHeight = window.innerHeight;
var windowWidth = window.innerWidth;
var scrollArea = 1000 - windowHeight;
var square1 = document.getElementsByClassName('square')[0];
var square2 = document.getElementsByClassName('square')[1];
// update position of square 1 and square 2 when scroll event fires.
window.addEventListener('scroll', function() {
var scrollTop = window.pageYOffset || window.scrollTop;
var scrollPercent = scrollTop/scrollArea || 0;
square1.style.left = scrollPercent*window.innerWidth + 'px';
square2.style.left = 800 - scrollPercent*window.innerWidth*0.6 + 'px';
});
body {
overflow-x: hidden;
}
.container {
width: 100%;
height: 1000px;
}
.square {
position: absolute;
}
.square-1 {
width: 100px;
height: 100px;
background: red;
top: 600px;
}
.square-2 {
width: 120px;
height: 120px;
background: black;
left: 800px;
top: 800px;
}
<div class="container" id="container">
<div class="square square-1"></div>
<div class="square square-2"></div>
</div>
Hope to help you.
Here you can see more examples about movable elements and scroll events.
I have a function which counts the number of line breaks in a div, depending on the width of the window. While the functions works fine when placed in the $(window).on('resize') function, it does not work when put in $(document).ready() function. I want it to work right on page load, and also window resize, how do I support both?
JSFiddle
Javascript/jQuery:
// functions called in both document.ready() and window.resize
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.line').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
You'll see at the start of the page, it incorrectly shows 17 lines, and then once you resize it will show the correct amount.
The issue lies in the first line of getLineCount(). Originally you had
var lineWidth = $('.line').width();
but no elements with the class "line" exist yet on your page (since they get added in your postItems() method. I changed it to
var lineWidth = $(".container").width();
instead, and now your code should be working. Snippet posted below:
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.container').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
body {
text-align:center;
}
.answer {
position: fixed;
left: 0;
bottom: 0;
}
.container {
position: relative;
width: 50%;
margin: 0 auto;
border: 1px solid #e8e8e8;
display: inline-block;
}
.item {
height: 50px;
padding:0 10px;
background-color: #aef2bd;
float: left;
opacity:0.2;
white-space: nowrap;
}
.line-wrap {
position: absolute;
border: 1px solid red;
width: 100%;
height: 100%;
top:0; left: 0;
}
.line {
height: 50px;
width: 100%;
background-color: blue;
opacity:0.5;
color: white;
transition: all 0.5s ease;
}
.line:hover {
background-color: yellow;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="item-wrap">
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
</div>
<div class="line-wrap">
</div>
</div>
<h1 class="answer"></h1>
When I click-drag (#cssNav) to the right, it is not moving proportionately along with the #html and #css div.
This might be something very obvious, but still am not able to figure it out, what am I missing here, please help?
Note: I don't want to use display:flex
codepen
$("#htmlNav").on("mousedown", dragStartH);
$("#cssNav").on("mousedown", dragStartH);
$("#jsNav").on("mousedown", dragStartH);
function dragStartH(e) {
e.preventDefault();
dragMeta = {};
dragMeta.pageX0 = e.pageX;
dragMeta.elem = this;
dragMeta.offset0 = $(this).offset();
dragMeta.codeWindow = "#" + $(e.target).attr("id").replace("Nav", "");
function handle_dragging(e) {
var change = e.pageX - dragMeta.pageX0;
var left = dragMeta.offset0.left + change;
$(dragMeta.elem).offset({ left: left });
$("#css").width($("#css").width() - change + "px");
$("#html").width($("#html").width() + change + "px");
}
function handle_mouseup(e) {
$("body")
.off("mousemove", handle_dragging)
.off("mouseup", handle_mouseup);
}
$("body").on("mouseup", handle_mouseup).on("mousemove", handle_dragging);
}
$(document).ready(function() {
var widthPercent = ($(window).width() - 30) / 3;
$("#html").width(widthPercent + "px");
$("#css").width(widthPercent + "px");
$("#js").width(widthPercent + "px");
});
html, body {
height: 100%;
margin: 0;
}
.container{
width:100%;
height: 100%;
background-color:#343;
display: flex;
flex-direction: column;
color: #fff;
margin: 0;
}
#preview, #code{
background-color:#433;
height: 50%;
width: 100%;
margin: 0;
}
#code{
border-bottom: #333 solid 2px;
width: 100%
}
#previewNav, #codeNav{
background-color:#bbb;
height: 10px;
width: 100%;
cursor: row-resize;
}
#html{
background-color: #BFB;
}
#css{
background-color: #FBB;
}
#js{
background-color: #BBF;
}
#html, #css, #js{
float: left;
width: 32%;
height: 100%;
}
#htmlNav, #cssNav, #jsNav{
background-color:#bbb;
float: left;
height:100%;
width: 10px;
cursor: col-resize;
z-index:10;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div id="codeNav"></div>
<div id="code">
<div id="htmlNav"></div>
<div id="html">H</div>
<div id="cssNav"></div>
<div id="css">C</div>
<div id="jsNav"></div>
<div id="js">J</div>
</div>
<div id="previewNav"></div>
<div id="preview">P</div>
</div>
This is how I would do it:
Keep track of which handle you press with navTypeand check if the user is holding its mouse down with dragging.
Then when the user moves the mouse in the document and it is holding its mouse down (dragging) it will move the #html, #css and #js accordingly
Change your javascript into this:
var mouseX, prevMouseX, navType, change;
var dragging = false;
$("#cssNav").mousedown(function () {
dragging = true;
navType = "css";
});
$("#jsNav").mousedown(function () {
dragging = true;
navType = "js";
});
$(document).mousemove(function (e) {
mouseX = e.pageX;
if(dragging){
e.preventDefault();
change = mouseX - prevMouseX;
if(navType == "css" && ($("#css").width() - (change)) > 0 && ($("#html").width() + (change)) > 0){
var hw = $("#html").width();
var cw = $("#css").width();
$("#html").width(hw + change);
$("#css").width(cw - change);
} else if(navType == "js" && ($("#css").width() + (change)) > 0 && ($("#js").width() - (change)) > 0){
var cw = $("#css").width();
var jw = $("#js").width();
$("#css").width(cw + change);
$("#js").width(jw - change);
}
}
prevMouseX = mouseX;
}).mouseup(function () {
dragging = false;
}).mouseleave(function () {
dragging = false;
});
i want move my #timebase1 div into draghere div. now its move only the start of the div, i want to drop it in anywhere inside the dragehere div.
function funct(e) {
var id = e.id;
mouseXY(id);
}
function mouseXY(id) {
//alert(id);
var x = event.pageX,
y = event.pageY
$('#' + id).css({
top: y,
left: x + ''
});
}
.activelevel1 {
background-color: #EA623E;
}
.timescalebase {
margin-top: 13px;
height: 7px;
position: relative;
width:0px;
}
<div id="draghere"style="width:100%;margin-top:25px;">
<div id="timebase1"draggable="true"class="timescalebase activelevel1" ondrag=funct(this)>
</div>
You must allowdrop on your target div like this :
function funct(e) {
var id = e.id;
mouseXY(id);
}
function allowDrop(ev) {
ev.preventDefault();
}
function mouseXY(id) {
var x = event.pageX,
y = event.pageY
$('#' + id).css({
left: x
});
}
.activelevel1 {
background-color: red;
width: 10px;
height: 10px;
}
.timescalebase {
margin-top: 13px;
height: 7px;
position: relative;
}
#draghere {
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="draghere" style="width:100%;margin-top:25px;" ondragover="allowDrop(event)">
<div id="timebase1" draggable="true" class="timescalebase activelevel1" ondrag="javascript:funct(this)">
</div>
</div>
EDIT
One example with jquery-ui :
https://jsfiddle.net/2gaq2r15/
$(document).ready(function(e) {
$("#timebase1").draggable({
containment: "#draghere",
axis: "x"
});
});
I have a pretty huge image being displayed in a container, the image stretches with the view port as it gets resized, but as the image is so big I have added scroller buttons to the side of the page, up and down, the only problem I have now is that when I press up or down there is no limit, the user can keep going until the image is completely out of sight, how can I stop that from happening?
Here is the code I have thus far,
HTML:
<body>
<div id="wrapper">
<div class="scroll top"></div>
<div id="content">
<div id="zoom_container">
<img id="image" src="8052x2000px" />
</div>
</div>
<div class="scroll bot"></div>
</div>
</body>
CSS:
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#wrapper {
overflow: hidden;
height: 100%;
max-height: 100%;
}
#content {
min-height: 100% !important;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#image {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
jQuery:
//side scroller bar
$('.scroll').live('click', function(){
var direction = $(this).hasClass('top');
var img_pos_top = $("#zoom_container img").position().top;
var inc = 0;
inc = $("#zoom_container img").height() / 10;
if(direction)
{
inc = $("#zoom_container img").position().top + inc;
}
else
{
inc = $("#zoom_container img").position().top - inc;
}
$("#zoom_container img").css({ position: 'relative',top: inc });
});
so as you can see I am incrementing or decrementing the top positioning of the image by 10% of it's height each click, how can I make sure the top of the image will never go further down than the top of the viewport and the bottom of the image never further up than the bottom of the viewport?
Is there a better more efficient way of achieving the same result?
Have a try this one.
<html>
<head>
<title>Canvas Sizing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var canvasContext;
resizeCanvas();
$(window).resize(function() { resizeCanvas() });
function resizeCanvas()
{
var w = window.innerWidth - 40;
var h = window.innerHeight - 40;
var canvasString = '<canvas id="mainCanvas" width="' + w + '" height="' + h + '">Canvas is not supported</canvas>';
$('#contentholder').empty();
$(canvasString).appendTo('#contentholder');
canvasContext = $('#mainCanvas').get(0).getContext('2d');
drawOnCanvas();
}
function drawOnCanvas()
{
var x = 15;
var y = 35;
canvasContext.font = "30pt serif";
canvasContext.fillStyle="#0f0";
canvasContext.fillText("Hello World!", x, y);
}
});
</script>
<style>
#mainCanvas
{
background-color: #000;
border: solid 3px #0F0;
}
body
{
background: #000;
}
#contentholder
{
width: 99%;
height: 99%;
margin: auto;
}
</style
</head>
<body>
<div id="contentholder"></div>
</body>