Let say I got this: http://puu.sh/6rqZc.jpg
How can I know the x/y or left/top properties of my canvas assuming that it is centered via this:
#canvas-container {
width: 100px;
height:100px;
margin: 0px auto;
}
Note: $('#myCanvas')[0].style.top returns ""
You can try to use offset() which will return the coordinates of the element relative to the document:
var eTop = $('#myCanvas').offset().top,
eLeft = $('#myCanvas').offset().left;
I think you need .offset() or .position():
if you need absolute left/top values:
var offLeft = $('#myCanvas').offset().left;
var offTop = $('#myCanvas').offset().top;
if you need relatively positioned elem's left/top values:
var posLeft = $('#myCanvas').position().left;
var posTop = $('#myCanvas').position().top;
Using JQuery
$('#myCanvas').eq(0).offset();
// or
$('#myCanvas:first').offset();
Related
How would I be able to create a new element and have it placed right where the mouse/cursor is located?
I have some example code below:
<div id = "adivthing></div>
<script>
var newthing = document.createElement("input");
document.getElementById("adivthing").appendChild(newthing);
</script>
If you use either the position: fixed or position: absolute style properties on the newthing element, you can then use the left and top properties to move the element around the box.
If you get the mouse coordinates from your triggering event (e.g. click), you can add the appropriate left and top to your element.
Example below:
function createInput(event){
var newthing = document.createElement("input");
document.getElementById("adivthing").appendChild(newthing); // Your existing code
// get the coordinates of the mouse
var x = event.clientX; // get the horizontal coordinate
var y = event.clientY; // get the vertical coordinate
// position newthing using the coordinates
newthing.style.position = "fixed"; // fixes el relative to page. Could use absolute.
newthing.style.left = x + "px";
newthing.style.top = y + "px";
}
/* Optional - Making new things more obvious in the pen */
input{
height: 10px;
width: 50px;
background: red;
}
#adivthing{
height: 600px;
width: 600px;
background: blue;
}
<!-- Onclick event added to your existing markup -->
<div id="adivthing" onclick="createInput(event)"></div>
I have a loop:
var takediv = document.getElementById('eye');
for(var i=0; i<categories.length; i++){
takediv.innerHTML +=^
'<img alt="'+(categories.length-i)+'" '+
'onclick="changef(this.alt)" '+
'src="mobile/img/pic/'+loc+"/mini/"+categories[categories.length-i-1][0]+'" '+
'style="cursor: pointer;"/>';
}
All images are having this css:
height: 80px;
width: auto;
And finally after loop I need to give the div this css
document.getElementById('eye').style.width
which will be sum of all inner img widhts
It is my first post here so sorry for mistakes.
Please help, and thanks!
You can use several approaches, for example getBoundingClientRect() which returns absolute values for position and width/height:
var width = document.getElementById('eye').getBoundingClientRect().width;
Just note it does not include border or padding, only the inner box.
Then there is getComputedStyle() - this will return a string suffixed with "px" so we also need to parse it using parseInt():
var width = parseInt(getComputedStyle(document
.getElementById('eye'))
.getPropertyValue("width"), 10);
Both returns size in pixels.
And as in #Rudi's answer, there is offsetWidth, and also clientWidth. This won't include margin.
Maybe you're looking for this:
var width = document.getElementById('eye').offsetWidth;
I want to make floating HTML5 element move back and forward on my page. Exactly like SmoothDivScrolling that is already out there. I did try SmoothDivScrolling and it is not working well with the layout of my page.
So I have started to write my own.
If I give a position to my element using CSS I will be able to retrieve the position with:
element = document.getElementById(image);
position = element.style.left;
// removing px from the value
position = parseInt(position.substring(0,position.length-2));
This will return the left position of the element inside its parent only if the CSS contain:
left:0px;
As mentioned, I want my elements to be floating because I plan to have many more than one element;
Now since I want to animate my element I have to change the position by changing the value of 0px with:
fish.style.left = (newPosition)+'px';
It is working if I provide the style of my floating element with:
position:relative; //This doesnt really afect my floating
left:0px; //this does
So I tried to retrieve the position with DOM instead of CSS using:
var element = document.getElementById(image);
var rect = element.getBoundingClientRect();
position = rect.left;
Now this is working. It retrieves the position of the element relative to the body even if no left positioning was specified in the style.
I am wondering if there is way to change the position of that element without going trough CSS style. Because each element might have different width, floating them take care of the positioning. If I provide a position to each of them they won't be floating anymore.
The floating option avoid all the math involved on positioning. But if it's really needed I guess I will do the math.
Any suggestions?
Here is the full code for who ever wants to reinvent the wheel with me
<body style="margin:0px;">
<div id="scroller" style="position:absolute;left:400px;width:800px;border:1px solid #000000;overflow:hidden;height:auto;">
<div id="scrollWrap" style="margin:0px;position:relative;width:400px;margin:auto;border:1px solid #000000;overflow:hidden;height:150px;">
<figure id="shark" style="float:left;margin:0px;padding:0px;width:150px;display:inline-block;">
<img id="image" src="shark.jpeg" alt="The Shark" style="border:1px solid #000000;position:relative;left:0px;width:150px;height:150px;">
</figure>
</div>
</div>
<script type="text/javascript">
setInterval(function(){ do_move("shark"); }, 10);
</script>
</body>
<script type="text/javascript">
var frameDirection;
function do_move(image) {
var container = document.getElementById("scrollWrap");
var bodyRect = container.getBoundingClientRect();
var element = document.getElementById(image);
var rect = element.getBoundingClientRect();
offset = rect.left - bodyRect.left;
fish = document.getElementById(image);
horz = fish.style.left;
fishSize = document.getElementById(image).offsetWidth;
horz = parseInt(horz.substring(0,horz.length-2));
var frameWidth = document.getElementById('scroller').offsetWidth;
var wrapWidth = document.getElementById('scrollWrap').offsetWidth;
var nbrImg = document.getElementById("scrollWrap").getElementsByTagName("figure").length;
if (horz==0) {
frameDirection='right';
}
else if (horz == (wrapWidth-fishSize)) {
frameDirection='left';
}
if (horz<=wrapWidth && frameDirection == 'right') {
horz += 1;
fish.style.left = (horz)+'px';
}
else if (horz<=wrapWidth && frameDirection == 'left') {
horz -= 1;
fish.style.left = (horz)+'px';
}
}
</script>
If I understand correctly, you want to initially float your elements, then switch to absolute positioning, but keep everything in the same place, so you can animate them?
If so, this code may help you. It's not based on your html, just an example.
// get all the floating elements
var floaters = document.getElementsByClassName("floater"),
index, floater, rect;
// go over them backwards
for (index=floaters.length-1; index>=0; index--) {
floater = floaters[index];
// get current position
rect = floater.getBoundingClientRect();
// convert it to style
floater.style.left = rect.left + "px";
floater.style.top = rect.top + "px";
// switch to absolute positioning
floater.style.position = "absolute";
floater.style.float = "none";
}
I made a little jsfiddle, so you can test it.
Consider these simple CSS rules:
jsFiddle
div#container {
width: 50%;
height: 260px;
background-image: url('Image.png');
background-repeat: repeat-x;
}
The problem is that I only want full images. If there is not enough space for another duplicate, it should NOT be shown.
I've never heard that CSS provides a rule for it. So how can I achieve it in JavaScript (jQuery already included)?
This is not possible with current CSS rules. You can repeat once, or repeat forever. The alternative is to shrink the size of the containing element to fit the nearest repeating point in either CSS (if you know the width before page load) or JS (if you don't).
Here's the latter implentation using jQuery:
var $container = $("#container");
var bgImg = extractUrl($container.css("background-image"));
var $img = $("<img />", { "src" : bgImg }).hide().appendTo("body");
$container.width(nearest($("#container").width(), $img.width()));
$img.remove();
function extractUrl(input) {
// remove quotes and wrapping url()
return input.replace(/"/g, "").replace(/url\(|\)$/ig, "");
}
function nearest(n, v) {
n = n / v;
n = Math.floor(n) * v;
return n;
}
Example fiddle
This will work for percentage widths and auto adjusts on sreen resize.
$(window).on('load resize', function () {
var img = $('<img/>');
img.attr('src', 'http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg').load(function () {
var height = this.height;
var width = this.width;
var divWidth = $('#containerwrap').width();
var extra = divWidth % width;
$('div#container').width(divWidth - extra);
});
});
div#container {
width: 670px;
height: 260px;
margin:0 auto;
background: url('http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg') left center;
background-repeat: repeat-x;
}
#containerwrap{
width:100%;
height: 260px;
background-color:#000000;
}
<div id="containerwrap">
<div id="container">
Test
</div>
</div>
http://jsfiddle.net/upjkd/14/show
As the width is fixed by the server, and the server knows the size of the image - why not construct the image to be correct and forget the repeat, or make the width the appropriate size so it will fit whole number of images?
See http://jsfiddle.net/upjkd/10/
var img=document.createElement('img');
img.src="http://upload.wikimedia.org/wikipedia/commons/0/0c/Fussball.jpg";
document.body.appendChild(img);
var con=document.getElementById('container'),
numImages=Math.round(con.clientWidth/img.clientWidth);
con.style.backgroundSize=con.clientWidth/numImages+'px';
document.body.removeChild(img);
You can use Math.round(con.clientWidth/img.clientWidth) to determine the number of repetitions of the image, and then use con.style.backgroundSize=con.clientWidth/numImages+'px' to be sure that the number of images is an integrer (only full images).
Is this possible? I'm trying to find the x and y coordinates of the element in relation to the browser.
var position = $(this).position();
x = position.left;
y = position.right;
Doesn't work.
Is there any way to do this?
http://adamsaewitz.com/housing/
highlight the blue room 070
The problem lies in the fact that you are accessing the top/left of an area element.
The area element is not positioned where its coords say. This is handled behind the scenes by the dom/browser.
So you need to find the image that the area relates to and grab its offset.
var imgId = $(this).closest('map').attr('name');
var imgPos = $('#' + imgId).offset();
Then, you grab the coords attribute of the area and split it to get left/top/width and use those to pinpoint the location inside the image.
var coords = $(this).attr('coords').split(',');
var box = {
left: parseInt(coords[0],10),
top: parseInt(coords[1],10),
width: parseInt(coords[2],10)-parseInt(coords[0],10),
height: parseInt(coords[3],10)-parseInt(coords[1],10)
};
Take into consideration the width/height of the info box that appears (and since you animate it, take that into consideration as well) and you get to
x = imgPos.left + box.left + box.width/2 - 65; // 65 is the info width/2
y = imgPos.top + box.top -20 -160 -1; // 20 is the animation, 160 is the info height, 1 is a safe distance from the top
demo: http://www.jsfiddle.net/XBjwN/
Edit for updated question: Since you're using <area> it's a different story, and fetching from the coords attribute is much easier, like this:
var position = $(this).attr('coords').split(',');
x = +position[0] - 50;
y = +position[1] - 170;
The offsets are just to account for the hard-coded width/height of the tooltip itself. In addition to the above, you want to use top and left rather than margin-top and margin-left. Also to account for the #content <div>'s position in the page, give it a relative position for the tooltip to sit in, like this:
#content { position: relative; }
Then...instead of .after(), use .append() so it gets added inside that parent.
You can test the result here.
For original question:
The object .position() returns has top and left properties...but you want .offset() here anyway (it's relative to the document, where .position() is relative to the offset parent), so it should look like this:
var position = $(this).offset(),
x = position.left,
y = position.top; //not right!
Or this:
var position = $(this).offset();
var x = position.left;
var y = position.top;
...but without a single var comma-separated statement, or a var on each line, you're also creating (or trying to) global variables, which will blow up in IE.
$(document).ready(function () {
$('map').imageMapResize();
$('area').hover(function () {
$('.imgpopover').css({ "display": "block", "top": $(this).attr("coords").split(',')[1]+"px", "left": $(this).attr("coords").split(',')[0]+"px" })
$('.imgpopover label').text($(this).attr("title"))
}, )
});