how to position multiple div`s with a variable as selector - javascript

i am trying to get a bigger picture when hovering over another picture on an input field with multiple pictures.
I tried the bellow code.
But the positioning of the bigger picture does not work when i use a variable to get the mouse position.
My problem is this part of the code:
var tooltipSpan = document.getElementById('\"' + popid + '\"');..........
tooltipSpan.style.top = (y - 320) + "px";
tooltipSpan.style.left = (x - 310) + "px";
when i alert this variable"('\"' + popid + '\"')", everything looks good,
when i put in the same as alerted manualy to the last function, everything works fine.
What do i am wrong? Please can someone give me a tip or improve the code.
This is the HTML, i cant change this, it is generated.
<div id= "yyy" class = ..........
<input class =.......
<label for="something" class='ClassExample1'>
something
</label>
<label for="something" class='ClassExample2'>
something
</label>
This is addeded by me, the id of the divs are the class names of the inputs ,
i get the class name of the input fields and make a variable from that
and try to set them for positioning the bigger pictures.
<div id='ClassExample1' class='Class a'>
<p><img src="some source"/></p>
</div>
<div id='ClassExample2' class='Class a'>
<p><img src="some source"/></p>
</div>
.
.
.
.
.
This is the code that i made:
document.getElementById( 'id yyy' ).getElementsByClassName( 'ClassExample1' )[0].onmouseover = function() {mouseOn1()};
document.getElementById( 'id yyy' ).getElementsByClassName( 'ClassExample1' )[0].onmouseout = function() {mouseOut1()};
function mouseOn1() {document.getElementById('ClassExample1').style.display = 'block';};
function mouseOut1() {document.getElementById('ClassExample1').style.display = 'none';};
document.getElementById( 'id yyy' ).getElementsByClassName( 'ClassExample2' )[0].onmouseover = function() {mouseOn2()};
document.getElementById( 'id yyy' ).getElementsByClassName( 'ClassExample2' )[0].onmouseout = function() {mouseOut2()};
function mouseOn2() {document.getElementById('ClassExample2').style.display = 'block';};
function mouseOut2() {document.getElementById('ClassExample2').style.display = 'none';};
.
.
.
.
.
/*Position of mouse hover picture*/
var poper;
window.onmouseover=function(e) {
poper = (e.target.className);
};
var popid = "\'" + poper + "'\";
var tooltipSpan = document.getElementById(popid);
window.onmousemove = function (e) {
var x = e.clientX,
y = e.clientY;
tooltipSpan.style.top = (y - 320) + "px";
tooltipSpan.style.left = (x - 310) + "px";
};

The popid and tooltipspan are not reassigned on mouse move as it is not inside the mousemove function. You could move them inside the function.
var poper;
var popid;
var tooltipspan;
window.onmouseover = function(e) {
poper = (e.target.className);
popid = "\'" + poper + "'\";
tooltipSpan = document.getElementById(popid);
};

Related

Screen following the "character"

I'm trying to achieve the following image,
Then whenever the player moves (he moves by click) I want the visible area to move with him. the visible area should be displayed over the whole screen.
I've currently got the following code but I have no idea how to make it so just the visible area is visible;
Code
<body>
<div class="map">
<div class="screen">
<div class="player">
<img class="ship" src="https://vignette.wikia.nocookie.net/darkorbit/images/a/a9/Neuergoli.jpg/revision/latest?cb=20120819231510">
</div>
</div>
</div>
</body>
$(function(){
$('.map .screen').on('click', function(event){
var clickedPosX = event.pageX,
clickedPosY = event.pageY;
var $player = $('.screen');
$player.animate({left:clickedPosX, top:clickedPosY}, 1000);
});
});
JSFiddle
try this one
$(function(){
var $map = $(".map");
var $player = $('.player');
var centerPlayerX = $player.offset().left + $player.width() / 2;
var centerPlayerY = $player.offset().top + $player.height() / 2;
$('.map').on('click', function(event){
var clickedPosX = event.pageX,
clickedPosY = event.pageY;
var currentMapPositionX = parseFloat($map.css("background-position-x"));
var currentMapPositionY = parseFloat($map.css("background-position-y"));
var moveMapX = currentMapPositionX - clickedPosX + centerPlayerX;
var moveMapY = currentMapPositionY - clickedPosY + centerPlayerY;
$map.animate({ "background-position-x": `${moveMapX}px`, "background-position-y": `${moveMapY}px` }, 1000);
});
});
and add background-repeat: repeat; to .map css

Get cursor writing positions

Is it possible to get the positions of cursor of writing (absolute x,y pixels positions of the last character) inside the input textarea
Note: its not just count number of characters, but I have to deal with new lines, for example, if the user type the Enter key (I have to detect the new position in pixels of the last character
I want this because i need to display a popup with suggestions while users type texts
if you have an example in reactjs or in classic javascript (not jquery) please share with your code
i hope that my question was clear.
Thank you in advance
Finally i found a solution:
here the code for reactjs
var text = this.refs.areatext,
coords = {};
var carPos = text.selectionEnd,
div = document.createElement("div"),
span = document.createElement("span"),
copyStyle = getComputedStyle(text);
[].forEach.call(copyStyle, function(prop){
div.style[prop] = copyStyle[prop];
});
div.style.position = "absolute";
document.body.appendChild(div);
div.textContent = text.value.substr(0, carPos);
span.textContent = text.value.substr(carPos) || ".";
div.appendChild(span);
coords = {
"TOP": span.offsetTop,
"LEFT": span.offsetLeft
};
document.body.removeChild(div);
this.setState({x:coords.LEFT,y:coords.TOP})
for javascript
(function() {
var text = document.querySelector(‘textarea’),
indicator = document.querySelector(‘.indicator’),
getCoord = function(e) {
var carPos = text.selectionEnd,
div = document.createElement(‘div’),
span = document.createElement(‘span’),
copyStyle = getComputedStyle(text),
coords = {};
[].forEach.call(copyStyle, function(prop){
div.style[prop] = copyStyle[prop];
});
div.style.position = ‘absolute’;
document.body.appendChild(div);
div.textContent = text.value.substr(0, carPos);
span.textContent = text.value.substr(carPos) || ‘.’;
div.appendChild(span);
coords = {
‘TOP’: span.offsetTop,
‘LEFT’: span.offsetLeft
};
console.log(coords);
indicator.style.left = coords.LEFT + ‘px’;
indicator.style.top = coords.TOP + ‘px’;
document.body.removeChild(div);
};
text.addEventListener(‘input’, getCoord);
}());
Please check this code, i have made cursor detection in javascript, hope will help you.
window.onload = init;
function init() {
if (window.Event) {
document.captureEvents(Event.MOUSEMOVE);
}
document.onmousemove = getCursorXY;
}
function getCursorXY(e) {
document.getElementById('cursorX').value = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
document.getElementById('cursorY').value = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
<html>
<body>
<input type="text" id="cursorX" size="3"> X-position of the mouse cursor
<br /><br />
<input type="text" id="cursorY" size="3"> Y-position of the mouse cursor
</body>
</html>

Fabricjs - How to detect canvas on mouse move?

In my fabricjs application, I had created dynamic canvases(variable's also dynamic). Here, I need to detect particular canvas while mouse move on canvas.
Sample code,
var i = 0, canvasArray = [];
$(this).find('canvas').each(function() {
i++;
var DynamicCanvas = 'canvas_'+i;
canvasArray[DynamicCanvas] = new fabric.Canvas('canvas_'+i,{
width : '200',
height : '200'
});
});
after this, I have 4 different canvases. Last added canvas has been activated. But i need to add object on any canvas.
So that i have to activate canvas using mouse move event. How can i achieve it.? Please help me on this.
Mullainathan,
Here some quick solution using jQuery:
var canvasStr = '';
var canvasArray = [];
var fabricCanvasArray = [];
var htmlStr = '';
var canvas = null;
//generate canavases
for (var i = 0; i < 4; i++){
canvasArray.push('c' + i);
htmlStr += '<canvas id="c' + i + '" width="200" height="200"></canvas>'
}
//append canvasses to the body
$('body').append(htmlStr);
//to the fabricjs parent div elements assign id's and generate string for jQuery with div id's
for (var i in canvasArray){
fabricCanvasArray[i] = new fabric.Canvas(canvasArray[i], {
isDrawingMode: true
});
$('#' + canvasArray[i]).parent().attr('id', ('div' + canvasArray[i]));
canvasStr += '#div' + canvasArray[i];
if (i < canvasArray.length - 1){
canvasStr += ',';
}
}
//jQuery event for mouse over each div element of the fabric canvas
$(canvasStr).mouseover(function(){
for (var i in fabricCanvasArray){
if (fabricCanvasArray[i].lowerCanvasEl.id == $(this).children(':first').attr('id')){
canvas = fabricCanvasArray[i];
canvas.freeDrawingBrush.width = 10;
var r = 255 - i*50;
var g = i * 50;
var b = 200 - i * 40;
canvas.freeDrawingBrush.color = 'rgb(' + r + ',' + g + ',' + b + ')';
canvas.on('mouse:up', function() {
//do your stuff
// canvas.renderAll();
});
break;
}
}
});
Also, you can run fiddle

JavaScript mouseover/mousemove cusor postion without clicking in input text box

I'm attempting to combine a JavaScript mechanism for auto placing the users cursor inside of an input box through the mouseover and mousemove listeners.
I have an almost perfect working example here: http://codepen.io/anon/pen/doxNLm?editors=101
var current_element = document.getElementById("hover");
current_element.onmousemove = function showCoords(evt) {
var form = document.forms.form_coords;
var parent_id = this.id;
form.parentId.value = parent_id;
form.pageXCoords.value = evt.pageX;
form.pageYCoords.value = evt.pageY;
form.layerXCoords.value = evt.layerX;
form.layerYCoords.value = evt.layerY;
function getTextWidth(text, font) {
// re-use canvas object for better performance
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
};
var element_base_browser_styles = window.getDefaultComputedStyle(current_element);
var total_text_pixal_length = getTextWidth(current_element.value, element_base_browser_styles.fontFamily + " " + element_base_browser_styles.fontSize);
var add_char_pixal_lengths = 0;
var myStringArray = current_element.value.split('');
var arrayLength = myStringArray.length;
for (var i = 0; i <= arrayLength; i++) {
var get_char_value = getTextWidth(myStringArray[i], element_base_browser_styles.fontFamily + " " + element_base_browser_styles.fontSize);
add_char_pixal_lengths = add_char_pixal_lengths + (get_char_value) + 1.311111111111; //every char value is added together.
// console.log("Total: " + x);
if ((add_char_pixal_lengths)> (evt.layerX)) {
this.setSelectionRange(i, i);
add_char_pixal_lengths = 0;
break;
}
}
}
current_element.onmouseover = function() {
this.focus()
}
The problem I'm having is like Geosynchronous orbit; the cursor shifts out of place sometimes a few pixels (left or right). My calculation probably sucks, but I'm not sure canvas is really the best way to do the measurement? Is there a better way?
mousemove listener to receive element cursor coordinates from e.pageX
font style using window.getComputedStyles(input_element)
arr.split('') from input_element.text string: x = ['a','b','c']
'for loop' the array, generate a canvas and measure each characters width
add all char widths one by one until the value is greater than e.pageX
set the 'for loop' iterate as the setSelectionRange(i, i)
Any help or suggestions on making this better would be appreciated. Thanks!

Div positioning calculation explanation required

I have attached the screenshot below to explain what i am trying to do.
The yellow highlighted line is the script which is run to get the position of the div (The red box in the picture).
I have used this code to calculate the position.
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
var left = 0;
var top = 0;
var i = 0;
while (element) {
xPosition = (element.offsetLeft);
yPosition = (element.offsetTop);
console.log("TOP Pos: "+yPosition+"Left Pos: "+xPosition);
if (i == 1) {
left = xPosition;
top = yPosition;
}
element = element.offsetParent;
i++;
}
return {
x: left,
y: top
};
}
And here i have used this method
function ReadDivPos(selector) {
var _divPos = "";
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
var pos = getPosition(parentDiv[i]);
var x = pos["x"];
var y = pos["y"];
console.log("Values+ Top: " + y + " Left: " + x);
var w = parentDiv[i].offsetWidth;
_divPos += x + "," + w + "," + y + "," + (x + w) + ","+window.screen.availWidth+"\\n";
}
}
console.log("Values+ x: " + _divPos);
return _divPos;
}
Interestingly i am getting three values and on the second attempt i am getting the correct values. Here is the screenshot showing all the three values.
The correct value is
TOP Pos: 185Left Pos: 197
which i got it in the second attempt. Can anyone explain me why i did not get the correct values in the first attempt or is there any efficient way to get these values. I have to get the parent node because this was the only way to access the div class='content' as script is placed before the div content so i have to read the parent nodes and then i am able to access the required div.
Please Note this is the copy of my original question(Div Positioning is calculated fine but need explanation how it is working). The guy asked me to accept his answer and then he will show how it is done but he never came back to me once i accepted his answer and unfortunately i have also forgot my userid so i am able to logon to my orignal account.
If someone just explain me why this is giving me correct positions in the second attempt. I am new to frontend development if i understand this concept then it will help in my future projects. Thanks in advance

Categories

Resources