I want to show a vertical line that will appear as and of my charts are hovered over and will disappear when the mouse exits the chart elements. Weirdly, the mouseleave and mouseout events seem to fire when the mouse is not moving or when it is moving up and down (rather than side-to-side), see the code snippet below. I don't want the line to disappear when the mouse pauses and I want it to track the mouse wherever it goes.
I've tried firing the code on hover, mouseenter and mouseover but mousemove (see below code) is the only event that continuously fires as the position of the cursor changes.
//$(document).ready(function() {
function showVerticalLine(e) {
var topBarHeight = 56;
var bottomHeight = 100;
var posX = $(this).offset().left;
var x = e.pageX;
var y = $(window).innerHeight();
//Change line so that it appears at the position of the cursor
$('.verticalTrackerLine').css({
'opacity': '1',
'left': x,
'top': topBarHeight,
'height': y - topBarHeight - bottomHeight + "px",
'transition': 'left 0.1s'
});
//Update string to show when the charts are being hovered over
$("#testSTRING").html('you are moving/hovering');
};
function hideVerticalLine(){
//Hide the line
$('.verticalTrackerLine').css({
'opacity': '0'
});
//Update string to show when the charts are being hovered over
$("#testSTRING").html('you have left');
}
$("#chart1").add("#chart2").mousemove(showVerticalLine);
$("#chart1").add("#chart2").mouseout(hideVerticalLine);
//})
.chart {
margin-top: 30px;
width: 100px;
height: 30px;
border: 1px solid black;
background-color: red;
}
.verticalTrackerLine {
border-left: 2px dashed RGB(68,74,79);
position: fixed;
z-index: 1;
opacity: 0;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<SPAN id="testSTRING"></SPAN>
<SPAN class="verticalTrackerLine"></SPAN>
<DIV id="chart1" class="chart">Chart 1</DIV>
<DIV id="chart2" class="chart">Chart 2</DIV>
</head>
Any help/suggestions would be gratefully received.
Your guess is right, when you hover over the actual line that interferes with hovering over the buttons. So, just adding pointer-events: none; to the .verticalTrackerLine selector will fix this so that the mouse has no interaction with the line at all.
I also did some minor JS cleanup on your code, nothing too major. The CSS rule transition: left 0.1s doesn't need to be re-applied every time the mouse moves, so that has now been set in the CSS instead.
$(function() {
var topBarHeight = 56;
var bottomHeight = 100;
var $line = $('.verticalTrackerLine');
var $charts = $("#chart1, #chart2");
var $test = $("#testSTRING");
function showVerticalLine(e) {
var posX = $(this).offset().left;
var x = e.pageX;
var y = $(window).innerHeight();
//Change line so that it appears at the position of the cursor
$line.css({
'opacity': 1,
'left': x,
'top': topBarHeight,
'height': y - topBarHeight - bottomHeight + "px"
});
//Update string to show when the charts are being hovered over
$test.html('you are moving/hovering');
};
function hideVerticalLine() {
//Hide the line
$line.css('opacity', 0);
//Update string to show when the charts are being hovered over
$test.html('you have left');
}
$charts
.mousemove(showVerticalLine)
.mouseout(hideVerticalLine);
});
.chart {
margin-top: 30px;
width: 100px;
height: 30px;
border: 1px solid black;
background-color: red;
}
.verticalTrackerLine {
border-left: 2px dashed RGB(68, 74, 79);
position: fixed;
z-index: 1;
opacity: 0;
transition: left 0.1s;/* <------ this was moved from JS */
pointer-events: none; /* <------ this was added */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<output id="testSTRING">nothing has happened yet...</output>
<span class="verticalTrackerLine"></span>
<div id="chart1" class="chart">Chart 1</div>
<div id="chart2" class="chart">Chart 2</div>
You can simplify it further:
move the tracking line into an :after pseudo element inside each chart element and position it absolutely within the chart
position it 10px more to the top and bottom using:
top: -10px;
bottom: -10px;
set opacity: 0 to the tracking line and on :hover set it to one - now you'll have the line on hover - see demo below:
.chart {
margin-top: 30px;
width: 100px;
height: 30px;
border: 1px solid black;
background-color: red;
position: relative;
box-sizing: border-box;
}
.chart:after {
content: '';
border-left: 2px dashed rgb(68, 74, 79);
position: absolute;
z-index: 1;
opacity: 0;
top: -10px;
bottom: -10px;
}
.chart:hover:after {
opacity: 1;
}
<div id="chart1" class="chart">Chart 1</div>
<div id="chart2" class="chart">Chart 2</div>
Now comes the javascript part - we can modify the left property to show the line moving with the mouse:
first add a CSS variable (say --left) that can be adjusted from JS
now in a mousemove listener you can use e.pageX - this.offsetLeft to get the relative position (left value) of the mouse inside the box.
update the --left CSS variable using document.documentElement.style.setProperty('--left', ...
Note that I've made a maximum value for the left value to be on the safe side to this.offsetWidth - 2.
See demo below:
$(".chart").mousemove(function (e) {
document.documentElement.style.setProperty('--left', Math.min(e.pageX - this.offsetLeft, this.offsetWidth - 2) + 'px');
});
:root {
--left: 0;
}
.chart {
margin-top: 30px;
width: 100px;
height: 30px;
border: 1px solid black;
background-color: red;
position: relative;
box-sizing: border-box;
}
.chart:after {
content: '';
border-left: 2px dashed rgb(68, 74, 79);
position: absolute;
z-index: 1;
opacity: 0;
top: -10px;
bottom: -10px;
left: var(--left);
}
.chart:hover:after {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="chart1" class="chart">Chart 1</div>
<div id="chart2" class="chart">Chart 2</div>
Add pointer-events: none; to .verticalTrackerLine
//$(document).ready(function() {
function showVerticalLine(e) {
var topBarHeight = 56;
var bottomHeight = 100;
var posX = $(this).offset().left;
var x = e.pageX;
var y = $(window).innerHeight();
//Change line so that it appears at the position of the cursor
$('.verticalTrackerLine').css({
'opacity': '1',
'left': x,
'top': topBarHeight,
'height': y - topBarHeight - bottomHeight + "px",
'transition': 'left 0.1s'
});
//Update string to show when the charts are being hovered over
$("#testSTRING").html('you are moving/hovering');
};
function hideVerticalLine(){
//Hide the line
$('.verticalTrackerLine').css({
'opacity': '0'
});
//Update string to show when the charts are being hovered over
$("#testSTRING").html('you have left');
}
$("#chart1").add("#chart2").mousemove(showVerticalLine);
$("#chart1").add("#chart2").mouseout(hideVerticalLine);
//})
.chart {
margin-top: 30px;
width: 100px;
height: 30px;
border: 1px solid black;
background-color: red;
}
.verticalTrackerLine {
border-left: 2px dashed RGB(68,74,79);
position: fixed;
z-index: 1;
opacity: 0;
pointer-events: none;
}
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<SPAN id="testSTRING"></SPAN>
<SPAN class="verticalTrackerLine"></SPAN>
<DIV id="chart1" class="chart">Chart 1</DIV>
<DIV id="chart2" class="chart">Chart 2</DIV>
</head>
Related
For my portfolio website, I want to include info text that becomes visible when hovering over the according image and I want the text to follow along the cursor.
I'm by no means a coding expert, so I tried to achieve the effect by replacing the default cursor with an image of the text on white background via css and the cursor-property.
However, this left me with weird gray edged around the image that the image originally doesn't have.
So I figured that this was a sloppy approach anyway and that I should rather try solving it via javascript... which left me with the following code:
$(document).bind('mousemove', function(e){
$('#tail').css({
left: e.clientX + 20,
top: e.clientY + document.body.scrollTop
});
});
#tail {
position: absolute;
background-color: #ffffff;
padding: 5px;
opacity: 0;
}
#tail p {
margin: 0px;
}
.project-01:hover > #tail {
opacity: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="project-01">
<a href="project-site-01.html">
<img src="images/project-cover-01.png" alt="Project description">
</a>
<div id="tail">
<p>Project description</p>
</div>
</div>
I am now left with text that appears when hovering over the image and it follows the cursor properly, even if the cursor position changes due to scrolling (which it didn't do properly at first, which is why I added the 'document.body.scrollTop').
The only problem: The info text is way to far away from the cursor. I tried adjusting the offset, adding '- 900' after 'document.body.scrollTop' but that only makes it look right with my specific browser height – if I switch to a smaller or bigger screen, the '- 900' of course doesn't fit anymore.
Is there anyone who can explain what I'm doing wrong on a dummy level or even better – tell me how to fix the problem? I've been trying to get that hover text effect working for literally the past two days. HELP!
PS: You can see the effect I want to create on https://playgroundparis.com
I hope this can help you!
Edit: Technically this is a duplicated. I realized the problem with scrolling that you talking about. I've found a solution in this post and I readaptated it for
your specific case.
var mouseX = 0, mouseY = 0, limitX, limitY, containerWidth;
window.onload = function(e) {
var containerObjStyle = window.getComputedStyle(document.querySelectorAll(".project-01")[0]);
containerWidth = parseFloat(containerObjStyle.width).toFixed(0);
containerHeight = parseFloat(containerObjStyle.height).toFixed(0);
var follower = document.querySelector('#tail');
var xp = 0, yp = 0;
limitX = containerWidth;
limitY = containerHeight;
var loop = setInterval(function(){
//Change the value 5 in both axis to set the distance between cursor and text.
xp = (mouseX == limitX) ? limitX : mouseX + 5;
xp = (xp < 0) ? 0 : xp;
yp = (mouseY == limitY) ? limitY : mouseY + 5;
yp = (yp < 0) ? 0 : yp;
follower.style.left = xp + 'px';
follower.style.top = yp + 'px';
}, 15);
window.onresize = function(e) {
limitX = parseFloat(window.getComputedStyle(document.querySelectorAll(".project-01")[0]).width).toFixed(0);
}
document.onmousemove = function(e) {
mouseX = Math.min(e.pageX, limitX);
mouseY = Math.min(e.pageY, limitY);
}
};
//Change the 100 value to set the fade time (ms).
$(".project-01").hover(function () {
$(this).find('#tail').fadeIn(100);
},
function () {
$(this).find('#tail').fadeOut(100);
});
#tail {
position: absolute;
background-color: #ffffff;
padding: 5px;
overflow: hidden;
}
#debug {
position: absolute;
right: 0;
top: 100px;
width: 100px;
height:100px;
background-color: red;
color: black;
}
#tail p {
margin: 0px;
}
.project-01 {
width: 300px;
overflow: hidden;
}
.project-01 img {
height: 100%;
width: 100%;
}
.project-01 a {
height: 100%;
width: 100%;
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="project-01">
<a href="project-site-01.html">
<img src="https://picsum.photos/200/300" alt="Project description">
</a>
<div id="tail">
<p>Project descriptions</p>
</div>
</div>
You can use the below code's
.description {
display: none;
position: absolute;
z-index: 2000 !important;
color: black;
padding: 15px;
margin-left: 32px;
margin-top: -200px;
top: auto;
height: auto;
width: 500px;
}
.image {
height: 200px;
width: 200px;
}
.my-image:hover + .description {
display: block;
position: absolute;
background-color: black;
color: white;
}
.description:hover {
display: block;
background-color: black;
color: white;
}
<div class="project-01">
<a href="project-site-01.html" class="my-image">
<img src="https://homepages.cae.wisc.edu/~ece533/images/monarch.png" alt="Project description" class="image">
</a>
<div id="tail" class="description">
Butterflies are insects in the macrolepidopteran clade Rhopalocera from the order Lepidoptera, which also includes moths. Adult butterflies have large, often brightly coloured wings, and conspicuous, fluttering flight.
</div>
</div>
I hope this helps i recenty made one myselff for my website a few days ago
No info cursor:
.info:hover .tooltip {
color: red;
visibility: visible;
opacity: 1;
transition: opacity 1s
}
.tooltip {
visibility: hidden;
opacity: 0;
transition: opacity 1s
}
}
.tootip:hover {
visibility: visible
}
<span class="info"><img src="https://google.com/favicon.ico">Hover Me</img> <span class="tooltip">Welcome</span></a></span>
With info cursor:
.info:hover .tooltip {
color: red;
visibility: visible;
opacity: 1;
transition: opacity 1s
}
.tooltip {
visibility: hidden;
opacity: 0;
transition: opacity 1s
}
}
.tootip:hover {
visibility: visible
}
.info {
cursor: help
}
<span class="info"><img src="https://google.com/favicon.ico">Hover Me</img> <span class="tooltip">Welcome</span></a></span>
I am trying to implement a crosshair cursor which will be activated through MouseEnter once the cursor enters the canvas. However, after the cursor has been changed to the crosshair, and even if it leaves the canvas, it still remains as the crosshair. I want the crosshair cursor to only be activated inside the canvas, and for the cursor to revert back to the default cursor once it leaves the canvas.
CSS:
#crosshair-h {
width: 100%;
}
#crosshair-v {
height: 100%;
}
.hair {
position: fixed;
top:0; left:0;
margin-top: -3px;
margin-left: -2px;
background: transparent;
border-top: 1px dotted #000;
border-left: 1px dotted #000;
pointer-events: none;
z-index: 2;
}
#mousepos {
position: absolute;
top:0; left:0;
padding: 10px;
margin: 10px;
font: 14px arial;
color: #fff;
background: rgba(0,0,0,0.5);
border-radius: 24px;
z-index: 1;
}
JavaScript:
$(document).ready(function() {
// Setup our variables
var cH = $('#crosshair-h'),
cV = $('#crosshair-v');
$(this).on('mousemove touchmove', function(e) {
var x = e.pageX - 1;
var y = e.pageY - 1;
cH.css('top', e.pageY);
cV.css('left', e.pageX);
$('#mousepos').css({
top: e.pageY + 'px',
left: e.pageX + 'px'
}, 800);
$('#mousepos').text( "X: " + x + "px, Y: " + y + "px");
e.stopPropagation();
});
// Anchor Hover Effects
$("a").hover(function() {
$(".hair").stop().css({borderColor: "#fff"}, 800)},
function() {
$(".hair").stop().css({borderColor: "black"},800)
});
e.stopPropagation();
});
Any help is appreciated, thank you!
If the default crosshair cursor suffices, you can do this with a simple CSS hover rule:
canvas {
border: 1px solid grey;
height: 50px;
width: 100px;
}
canvas:hover {
cursor: crosshair;
}
<canvas></canvas>
If you really have need for the custom one, you can use a mouseleave or mouseout event on the canvas to remove the css class.
Hey guys I’m trying to make simple point & click game, in background will be some nice landscape which will be moved by arrows on the left and right (same like slider works), I want object to move only within the lower div (#boxMap), I tried to build contructor to main object but together with friend who helps me, we wrote it in way below. The problem is that this object still doesn’t move how it should be, idea is that when game starts, and when I click right arrow, object appears on the left, if I click left arrow object appears on the left side of the div. When I click the mouse, object should moves to position I clicked. I’m kinda desperate as I have ideas how to make It work later but I totally cannot manage this positioning and movement of the object.
I found some nice yt tutorial about moving objects and tried to set statements to move only within the div without getting outside the edge, unfortunately now it moves only on the bottom edge of div.
So I created new object with class .hero inside the boxMap, and set it’s starting position with css properties, then with function getClickPosition I try to manage it’s movement, I try also set that if object is clicked outside the frame of div, it set it’s position on particular value. Unfortunately now it moves only through the bottom edge, right side it doesn’t exceed the edge, left side it does.
Hope I was able to more or less explain what I try to achieve and what I have already done.
Any idea how to set position and some simple movement in much simpler way?
I would be grateful for any tips
HTML
<body>
<div id="emptySpace">
<span class="left"></span>
<span class="right"></span>
</div>
<div id="boxMap">
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="js/app.js"></script>
</body>
CSS
body {
margin: 0;
padding: 0;
background-color: antiquewhite;
#emptySpace {
width: 100%;
height: 70vh;
background-color: azure;
position: relative;
.left {
position: absolute;
left: 10px;
top: 40vh;
border-top: 40px solid transparent;
border-bottom: 40px solid transparent;
border-right:40px solid blue;
//display: none;
}
.right {
position: absolute;
right: 10px;
top: 40vh;
border-top: 40px solid transparent;
border-bottom: 40px solid transparent;
border-left: 40px solid green;
//display: none;
}
}
#boxMap {
width: 100%;
height: 30vh;
border: 1px solid black;
background-color: #d8fffa;
position: relative;
.hero {
position: absolute;
width: 50px;
height: 50px;
display: inline-block;
border: 1px solid black;
border-radius: 50%;
background-color: blue;
transform: translate3d(0px, -45px, 0);
transition: 2s linear;
}
}
}
Javascript
function Game() {
this.hero = new Hero();
this.counter = 0;
var self = this;
this.boxMap = document.querySelector("#boxMap");
// Placing hero on the map
this.showHero = function () {
var heroElement = document.createElement('div');
heroElement.classList.add('hero');
console.log(self, self.boxMap);
self.boxMap.appendChild(heroElement);
$(heroElement).css({top: 130, left: 30})
}
}
var game = new Game();
game.showHero();
var heroMovement = document.querySelector(".hero");
var boxMap = document.querySelector("#boxMap");
boxMap.addEventListener("click", getClickPosition, false);
// Set position on hero and set movement
function getClickPosition(e) {
var xPosition = e.clientX;
var maxWidth = 1350;
var minWidth = -20;
if (xPosition < minWidth) {
xPosition = minWidth;
} else if (xPosition > maxWidth) {
xPosition = maxWidth
} else {
var xPosition = e.clientX - (heroMovement.offsetWidth + 3);
}
var yPosition = e.clientY;
var maxHeight = 60;
var minHeight = -130;
if (yPosition < minHeight) {
yPosition = minHeight;
} else if (yPosition > maxHeight) {
yPosition = maxHeight
} else {
var yPosition = e.clientY - (heroMovement.offsetHeight + 558);
}
console.log(xPosition, yPosition);
var translate3dValue = "translate3d(" + xPosition + "px" + "," + yPosition + "px, 0)";
console.log(translate3dValue);
heroMovement.style.transform = translate3dValue;
}
I write some code for text rotate , resize and text drag . Everything is working fine on the starting . Please see this code
$( '.new-div').draggable({
containment: "#bord",
create: function() {
$(".new-div").css("width",'auto');
} ,
drag: function() {
$(".new-div").css("width",'auto');
} ,
start: function() {
$(".new-div").css("width",'auto');
} ,
stop: function() {
$(".new-div").css("width",'auto');
}
});
$(document).on("click",".closeButton",function(){
$(this).closest('div').remove();
});
$('.new-div').on("click", function(){
var uscontent= $(this).text();
if(uscontent.trim()==="Add Your Text"){
$('.mc').text('');
$(this).css("width","100px");
$(this).css("height","6%");
}
});
$('.resizeButton').draggable({
containment: '#bord',
drag: function() {
$('.new-div').height($('.resizeButton').position().top + 17);
$('.new-div').width($('.resizeButton').position().left + 17);
$('.new-div').width($('.resizeButton').position().left + 17);
$('.new-div').css({ 'font-size': ($('.new-div').height() / 2.3)});
}
});
var rotation = 0;
var rotating = false;
var startX = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
};
$(document).mousemove(function(e){
if (!rotating) return;
rotation = startX - e.clientX;
$('.new-div').rotate(rotation);
});
$(document).on("mouseup", function(){
rotating = false;
});
$('.rotateButton').on("mousedown", function(e) {
e.stopImmediatePropagation();
rotating = true;
startX = e.clientX;
});
.new-div {
z-index: 1;
position: absolute;
width: auto;
word-break: break-all;
text-align: center;
left: 30%;
top: 55px;
border:2px solid black;
}
.parent-div {
max-width: 236px;
width: 236px;
position: relative;
overflow: hidden;
}
.closeButton
{
display:block;
position:absolute;
top:-10px;
left:-10px;
width:27px;
height:27px;
background:url('http://cdn-sg1.pgimgs.com/images/pg/close-button.png') no-repeat center center;
}
.resizeButton
{
display:block;
position:absolute;
bottom:-10px;
right:-10px;
width:27px;
height:27px;
background:url('http://img.freepik.com/free-icon/resize-button_318-99883.jpg') no-repeat center center;
background-size: contain;
cursor: resize;
}
.rotateButton
{
display:block;
position:absolute;
top:-10px;
left:82px;
width:27px;
height:27px;
background:url('http://cdn-sg1.pgimgs.com/images/pg/close-button.png') no-repeat center center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="http://thdoan.github.io/scalem/javascripts/jquery.scalem.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<div class="col-sm-12">
<div class="parent-div">
<div class="new-div" contenteditable="true">
<span data-scale-ratio="1" class="mc" data-scale-reference="new-div">
Add Your Text
</span>
<a class="closeButton"></a>
<a class="rotateButton"></a>
<a class="resizeButton"></a>
</div>
<div class="bord" style="z-index: -1;">
<img src="https://s-media-cache-ak0.pinimg.com/236x/8b/8a/00/8b8a007ae01adf400e12b26f3b93fb3a.jpg">
</div>
</div>
</div>
https://jsfiddle.net/felixtm/jaboLc3u/20/
But after text rotate this problems are arrived
Rotate icon and close icon is missing when we rotate the text and edit it .
Some time text is going outside the border box
After rotate and edit text then div resize is not working
Resize button, close button is going far from the border box
Some time webpage is alerting unresponsive script is running
Please Help to solve these issues .
Rotate icon and close icon is missing when we rotate the text and edit it.
This is because they are positioned relative to rotated content. The easiest fix is to embed the rotated content in a container and position your icons outside of the rotated content.
Some time text is going outside the border box.
The size of your font is not related to the height of the container. Additionally, you cannot know the resulting height of your text without changing the font size. I would recommend dynamically filling the font size based on the container instead of assuming the height of the container is related to the desired font size.
After rotate and edit text then div resize is not working
This could be caused by the previously mentioned issue of the browser not properly understanding where to position child elements of rotated content.
Resize button, close button is going far from the border box
Possibly related to the first issue
Some time webpage is alerting unresponsive script is running
You should either store jQuery results in a variable or chain your queries to avoid having to reexecute the selector.
The following may work for you. I haven't fully tested any of this, but preliminary tests work well enough in firefox. If you wish to have multiple containers, you'll need to modify the code a bit, as it is assuming there is only one element with the given 'new-div' class attached.
https://jsfiddle.net/ye53kcre/
$('.container').draggable({
containment: "#bord"
});
$(document).on("click", ".closeButton", function() {
$(this).closest('div').remove();
});
$(document).on("click", ".new-div", function() {
$(this).focus();
});
$('.resizeButton').draggable({
containment: '#bord',
drag: function() {
var pos = $(this).position();
$(this).closest('.container')
.height(pos.top + 17)
.width(pos.left + 17);
$('.new-div').resizeFontToFillParent();
}
});
var rotation = 0;
var rotating = false;
var startX = 0;
$.fn.resizeFontToFillParent = function() {
return this.each(function() {
var containerHeight = $(this).parent().height();
var $el = $(this).css('font-size', '');
var fontSize = parseInt($el.css('font-size')) || 12;
while ($el.height() < containerHeight) {
$el.css('font-size', fontSize++);
}
});
};
$(document).mousemove(function(e) {
if (rotating) {
rotation = startX - e.clientX;
$('.new-div').css({
'transform': 'rotate(' + rotation + 'deg)'
});
}
});
$(document).on("mouseup", function() {
rotating = false;
});
$('.rotateButton').on("mousedown", function(e) {
e.stopImmediatePropagation();
e.preventDefault();
rotating = true;
startX = e.clientX;
});
.new-div {
display: inline-block;
position: absolute;
top: 0;
left: 0;
width: 100%;
word-break: break-all;
text-align: center;
}
.container {
z-index: 1;
position: absolute;
display: inline-block;
left: 30%;
top: 55px;
width: 100px;
height: 30px;
border: 2px solid black;
}
.parent-div {
max-width: 236px;
width: 236px;
position: relative;
overflow: hidden;
}
.closeButton {
display: block;
position: absolute;
top: -10px;
left: -10px;
width: 27px;
height: 27px;
background: url('http://cdn-sg1.pgimgs.com/images/pg/close-button.png') no-repeat center center;
}
.resizeButton {
display: block;
position: absolute;
bottom: -10px;
right: -10px;
width: 27px;
height: 27px;
background: url('http://img.freepik.com/free-icon/resize-button_318-99883.jpg') no-repeat center center;
background-size: contain;
cursor: resize;
}
.rotateButton {
display: block;
position: absolute;
top: -10px;
left: 82px;
width: 27px;
height: 27px;
background: url('http://cdn-sg1.pgimgs.com/images/pg/close-button.png') no-repeat center center;
}
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<div class="col-sm-12">
<div class="parent-div">
<div class="container">
<div class="new-div" contenteditable="true" tabindex="0">
Add Your Text
<a class="rotateButton"></a>
</div>
<a class="closeButton"></a>
<a class="resizeButton"></a>
</div>
<div class="bord" style="z-index: -1;">
<img src="https://s-media-cache-ak0.pinimg.com/236x/8b/8a/00/8b8a007ae01adf400e12b26f3b93fb3a.jpg">
</div>
</div>
</div>
I have a script to draw a selection box over a grid (just a .png image) however I have an error where the selection box is drawn in the wrong place.
I think it's because the script which the mousedown position uses calculates top and left on page load. If the page is resized before creating a selection box, it uses the original calculations of top and left and is therefore not in the correct position.
Is there a way to fix this problem without completely bastardising my script?
Below is the code used along with a .zip and a jsFiddle, thank you for your help!
jsFiddle
.zip
CSS:
body{
background-color: #3AB3F0;
}
#board-background{
width: 1000px;
height: 1000px;
padding: 25px 25px 25px 25px;
margin: 25px auto 25px;
position: relative;
background: url(https://abs.twimg.com/a/1366134123/t1/img/wash-white-30.png);
border: 0px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
box-shadow: 0 1px 2px rgba(0,0,0,.05);
}
#board {
position: absolute;
background-color: #FFF;
z-index: 1;
width: 1000px;
height: 1000px;
border-bottom: 1px solid black;
border-right: 1px solid black;
}
#board img {
position: absolute;
z-index: 2;
user-drag: none;
-moz-user-select: none;
-webkit-user-drag: none;
}
#selectionBox {
position: absolute;
z-index: 3;
display: none;
background-color: red;
min-width: 0px;
min-height: 0px;
width: 10px;
height: 10px;
opacity: 0.8;
}
HTML:
<html>
<head>
<link href="css/test.css" rel="stylesheet">
<script type="text/javascript" src="http://code.jquery.com/jquery-git.js"></script>
<script type="text/javascript" src="js/board_script.js"></script>
</head>
<body>
</body>
</html>
JS:
// GRID CREATION SCRIPT //
// -------------------- //
function creategrid(){
//Outside background for the board
var BoardBackground = document.createElement('div');
BoardBackground.id = 'board-background';
BoardBackground.class = 'board-background';
document.body.appendChild(BoardBackground);
//Generated image
var Board = document.createElement("div");
Board.id = 'board';
Board.className = 'board';
BoardBackground.appendChild(Board);
//grid image
var grid = document.createElement("img");
grid.id = 'grid';
grid.className = 'grid';
grid.src = "media/grid.png";
Board.appendChild(grid);
}
// Selection Box Script //
// -------------------- //
var isDragging = false,
dragStart,
cellSpacing = 10,
gridOffset,
selectionBox;
function getMousePos (e) {
return {
'left': Math.floor((e.pageX - gridOffset.left) / cellSpacing) * cellSpacing .toFixed( 0 ),
'top': Math.floor((e.pageY - gridOffset.top) / cellSpacing) * cellSpacing .toFixed( 0 )
};
};
$(document).ready(function(){
creategrid(10);
gridOffset = $('#board').offset();
selectionBox = $('<div>').attr({id: 'selectionBox'})
.appendTo($('#board'));
$('#board').on('mousedown', function(e){
isDragging = true;
var pos = getMousePos(e);
dragStart = pos;
selectionBox.css({
left: pos.left,
top: pos.top,
width: 10,
height: 10
}).show();
});
$('#board').on('mousemove', function(e){
if(!isDragging)
return false;
var pos = getMousePos(e);
var diff = {
'left': pos.left - dragStart.left,
'top': pos.top - dragStart.top
};
selectionBox.css({
left: Math.min(pos.left, dragStart.left),
top: Math.min(pos.top, dragStart.top),
width: Math.abs(diff.left),
height: Math.abs(diff.top)
});
});
$('#board').on('mouseup', function(e){
isDragging = false;
});
});
Media:
(I need 10 rep to post a third link, so here's plaintext and 'code')
oi43.tinypic.com/33opjtd.jpg
[grid.png](http://oi43.tinypic.com/33opjtd.jpg "grid lined image with transparent background")
Other things that I need help with:
another minor error is the fact that, when selecting to the left and the top, the box rotates around the top left corner rather than the bottom right (try selecting the entire grid from the bottom right square).
I think that this has something to do with putting an if statement around the math.abs in the css and subtracting 10px from either side... but I can't work it out
Also in the future I want to be able for the user to upload an image and have it displayed over the selection box (dynamically changing in size) it should be possible by changing the css of the selection box... I might open a separate question for that though.
A single line can solve your selection probleme on resize :
$(window).resize(function(){gridOffset = $('#board').offset();})