So I am trying to allow the user to shift a div to the left or right in angularjs. Right now I have the function below. It works on the first click but all it does is toggle every click and is saying left is NaN. What am I doing wrong here? Also if someone has a better solution for this please let me know.
vm.scrollSelector = function(e, direction) {
var target = document.getElementById('item-selector');
var left = target.style.left;
if(direction === 'left') {
left += 600;
target.setAttribute('style', 'left: ' + left + 'px');
} else {
left -= 600;
target.setAttribute('style', 'left: ' + left + 'px');
}
}
So I quickly found the answer just by looking at the docs. Left is returned as a string so all I had to to was do parseInt(left) + 600 and it worked.
vm.scrollSelector = function(e, direction) {
var target = document.getElementById('item-selector');
var left = target.style.left.match(/\d+/);
left = parseInt(left[0], 10)
if(direction === 'left') {
left += 600;
target.setAttribute('style', 'left: ' + left + 'px');
} else {
left -= 600;
target.setAttribute('style', 'left: ' + left + 'px');
}
}
First try to see what value target.style.left is returning. It might be returning value like '10px'. You need to convert this into a number first then perform the addition or subtraction.
Related
this does not move the box when pressing the right and left arrow.
please post in the comments if you can help.
window.addEventListener("keydown", testkey , false );
var el = document.getElementById("player");
//changes the x position by a value
function changex(num) {
el.style.left = ((num + el.style.left) + "px");
}
//changes the y position by a value
function changey(num2) {
el.style.top = ((num2 + el.style.top) + "px");
}
//sets x and y position of box
function setpos(x, y) {
el.style.left = (x + "px");
el.style.top = (y + "px");
}
//this returns the key that is pressed
function testkey(e) {
if (e.keyCode == "37") {
//left key
changex(-10);
}
else if (e.keyCode == "39") {
//right key
changex(10);
}
}
setpos(0,0);
I see two issues:
First
You are adding numeric values to strings, which results in concatination. For example:
((num + el.style.left) + "px") is equivalent to 10 + 0px + px, which results in a string like 100pxpx. This is not a valid CSS value.
I suggest using parseInt to convert existing style values from strings to numbers:
el.style.left = parseInt(el.style.left) + num + "px";
For further reference, see Get a number for a style value WITHOUT the “px;” suffix.
Second
You'll need to position the element before you can use left,right,top, or bottom CSS definitions. The MDN notes that left (for example) only applies to "positioned elements".
Below, I've used position:absolute, but any valid position value will work.
For further reference, see css “left” not working.
Working Example
window.addEventListener("keydown", testkey, false);
var el = document.getElementById("player");
function changex(num) {
el.style.left = parseInt(el.style.left) + num + "px";
}
function changey(num) {
el.style.top = parseInt(el.style.top) + num + "px";
}
function setpos(x, y) {
el.style.left = (x + "px");
el.style.top = (y + "px");
}
function testkey(e) {
switch (e.keyCode) {
case 37: changex(-10); break;
case 38: changey(-10); break;
case 39: changex(10); break;
case 40: changey(10); break;
default:
}
}
setpos(0, 0);
#player {
position: absolute;
}
<div id="player">test</div>
in your changex() and changey() functions, you're trying to do calculations between a number and a string. num comes in as a number but el.style.left is the string '0px'. put parseInt() around el.style.left like this and it works:
el.style.left = ((num + parseInt(el.style.left)) + "px");
Also make sure your player element has position:absolute applied via CSS.
I am working on a jQuery tooltip module for personal use. In my code I'm using jQuery's mousemove and mouseout functions in order to generate the tooltip. However, when I move my mouse over the element it hits the if statement in the build function and says that the tooltip should be there even though I can see in Firebug and in the Chrome Dev Tools that it's not.
$.fn.tooltip = function(userOptions)
{
var defaultOptions = {
position: '',
follow: true
};
var options = $.extend(defaultOptions, userOptions);
$(this).mouseenter(function()
{
var title = $(this).data('title');
build(title, options.position, options.follow);
var top, left;
var tooltip = $('#tooltip');
if (tooltip.hasClass('top'))
{
top = $(this).offset().top - ($(this).height() * 2) - 10;
left = $(this).offset().left;
}
else if (tooltip.hasClass('right'))
{
top = $(this).offset().top - ($(this).height() / 2);
left = $(this).offset().left + tooltip.width();
}
else if (tooltip.hasClass('bottom'))
{
top = $(this).offset().top + $(this).height() + 10;
left = $(this).offset().left;
}
else if (tooltip.hasClass('left'))
{
top = $(this).offset().top - ($(this).height() / 2);
left = $(this).offset().left - (tooltip.width() * 1.5);
}
tooltip.css('top', top).css('left', left).show();
});
$(this).mousemove(function(e)
{
if (options.position === "" || options.position === undefined || options.follow === true)
{
var title = $(this).data('title');
build(title, options.position, options.follow);
var top = e.pageY + 25;
var left = e.pageX + 10;
$('#tooltip').css('top', top).css('left', left).show();
}
});
$(this).mouseout(function()
{
$('#tooltip').hide();
});
function build(title, position, follow)
{
if ($('#tooltip'))
{
console.log("The tooltiop should be on the page.");
$('#tooltip-content > p').text = title;
}
else
{
console.log("Position is: " + position);
var markup = '<div id="tooltip" class=' + position + '">';
markup += '<div id="tooltip-content">';
markup += '<p>' + title + '</p>';
markup += '<span id="tooltip-arrow"></span>';
markup += '</div>';
markup += '</div>';
$('body').append(markup);
}
}
};
The original goal was to create the tooltip the first time the user moves over the element and then when the mouse moves away I wanted to hide the tooltip and move it out of the way until it's needed again. That's why I'm checking to see if it exists in the build function. I know I'm overlooking something, I just can't figure out what it is. Any suggestions?
In build function change the check in the if like:
if ($('#tooltip').lenght) {
that will return false if #tooltip is not yet appended to body and true if it is.
The $('#tooltip') will return always a jQuery object thus it will never be false but its length will be 0, thus false, if the tooltip element is not yet added to the body.
jsFiddle
Regards.
Hi i want to calculate the position of the Div. Pardon me if i am not able to explain it properly but i will try to explain everything in the simplest way. I am creating sidepanel ad and to place the panels i want the position of the width. When i upload the script on my server then i get a small script which we place on the publisher website and where our script runs inside the iframe. I want to get the position of the div which has a class 'content'. Here is the screen shot.
in the above screenshot the yellow highlighted script is calculating the position of the div class="content" which is in red box. My code was working fine but on the publisher site it was not working fine and i was only able to get only two Divs whose id is like ebDiv..... (these divs are above the yellow highlighted js).
Then i found out to read the parentDiv in order to get the content positions.
i wrote this code.
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") {
alert(parentDiv[i].offsetWidth);
alert(parentDiv[i].offsetLeft);
}
The width is calcuated as 1010 which is fine but i am just missing left positioning which i am getting using parentDiv[i].offsetLeft is 2.
Above the screenshot has width 1010 which is fine but left positioning is not correct.
i had this code to calculate the width.
function ReadDivPos(selector) {
var _divPos = "";
$(selector).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
});
return _divPos;
}
console.log(ReadDivPos(".content"));
when i am using the same code to calculate the positioning then it is not working .
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") {
$(parentDiv[i]).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
}
}
Can someone me explain me how to fix this. Jquery/Javascript anythingwould be fine. I am not good in the frontend things so i am sorry if i could not explain it better. Thanks in advance
Here is a function used to get the position on the page of an element:
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while (element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
Used like this:
var pos = getPosition(element);
var x = pos["x"];
var y = pos["y"];
I'm not sure if this is exactly what you need, but if not maybe you can tweak it to fit your situation
Does that title sound confusing? I thought it might well anyways.
When I person clicks on the page I want them to be able to me a little line shorter and long.
You can see what I mean here:
http://jsfiddle.net/shawn31313/HKLhE/9/show/
Do a Mousedown and them move your move to the right. It works fine.
But now, move you mouse to the left. See the problem? It goes the same direction as it did when you dragged to the right. I know this is because i'm using width and obviously width on goes one way.
This is my code so far:
$(document).ready(function() {
var dragStatus = 0,
getPos, giveRandomID;
$(document).mousedown(function(event) {
dragStatus = 0;
getPos = {
top: event.clientY,
left: event.clientX
};
giveRandomID = Math.floor(Math.random() * 99999);
});
$(document).mousemove(function() {
var line = $('#line' + giveRandomID);
if (dragStatus == 0) {
$('body').append("<div id='line" + giveRandomID + "' class='line' style='position:absolute;top:" + getPos.top + "px;left:" + getPos.left + "px;background:black;width:2px;height:5px'></div>");
dragStatus = 1;
}
if (dragStatus == 1) {
if (event.clientX > line.offset().left) {
line.css({
width: event.clientX - line.offset().left
});
} else {
line.css({
width: line.offset().left - event.clientX
});
}
//for DEG "-" Top-Math.abs(DEG*2) for Deg "+" Top+(DEG*2)
}
});
$(document).mouseup(function() {
dragStatus = 2;
});
});
I hope someone can help me out with this. Maybe a complete different way to set this up. Just something to fix this issue
To make the line stretch to the left, you have to update the left property:
if (event.clientX > getPos.left) {
line.css({
left: getPos.left,
width: event.clientX - getPos.left
});
} else {
line.css({
left: event.clientX,
width: getPos.left - event.clientX
});
}
jsFiddle: http://jsfiddle.net/HKLhE/16/
You'll need to modify the else case (moving right) to set the left property to auto and the right property to the initial mouse click X position. Comparing to the offset().left when moving left won't work because that value is changing.
Try this out for size:
http://jsfiddle.net/HKLhE/20/
Edit: Brilliand's solution is much more elegant.
I've been trying to get this javascript animation to work for hours now, and I got nothing. The problem isn't getting my div box to move from left to right(or from top to bottom), it's the opposite of each case that I have trouble with it. Here's what I have so far(In addition, I have set boundaries set to keep my moving box contained within the view window so if it hits any one of sides, it should move to the opposite direction). Any help is awesome at this point.
Note: the next step is to create a bouncing effect for the box, but i'll worry about that once i get simple animation working.
setInterval(function(){
if(parseInt(box.style.left) > parseInt(viewDim.width - 57)){
box.style.left -= parseInt(box.style.left) - 2 + 'px';
/* } else if(parseInt(box.style.left) < 0){
//debug_log("HIT!!");
//parseInt(box.style.left) += 2 + 'px';
} else if(parseInt(box.style.top) > parseInt(viewDim.height-58)){
} else if(parseInt(box.style.top) < 0){*/
} else {
box.style.left = parseInt(box.style.left) + 2 + 'px';
//box.style.top = parseInt(box.style.top) + 5 + 'px';
}
}, 20);
Code like this always works for me:
var boxWidth = 57, delta = 2;
setInterval(function(){
var left = parseInt(box.style.left);
if(left >= parseInt(viewDim.width - boxWidth)){
delta = -2;
}
if (left <= 0) {
delta = 2;
}
box.style.left = left + delta + 'px';
}, 20);
Although you have your solution now, I couldn't help myself from making complete code here.
The bouncing box bounces around inside the parent element. Tested in IE8, FF3, and Opera11.
This can give an idea, how to do it with jQuery
http://jsfiddle.net/rFkpy/
$('#myDiv').click(function() {
$(this).animate({
left: '+=250'
}, 1500, "easeOutBounce", function() {
// callBack
});
});