I have used two div element. The below structure I have used.
<div id="firstelement" style="width:681px; height:401px">
<div id="secondelement" style="width:50%;height:50%;"></div>
</div>
I need to get the exact width("340.5px") of second div in IE8. How can I get it using JavaScript?
Tried like below
$("#getWidth").click(function(){
var ele = document.getElementById("secondelement");
var box = ele.getBoundingClientRect();
alert("Width = "+ box.right - box.left); // Integer value returned.
});
Can you please give your suggestion to resolve this issue?
Try this:
var rect = $("#secondelement")[0].getBoundingClientRect();
var width;
if (rect.width) {
// `width` is available for IE9+
width = rect.width;
alert(width)
} else {
// Calculate width for IE8 and below
width = rect.right - rect.left;
alert(width)
}
DEMO: http://jsfiddle.net/ishandemon/7s6Lta50/
Related
So my objective is to get the height of an element whith the px.
I already know my height value, but does not bring the xp.
This is what i have done to get my value :
let elemHeight = document.querySelector(".user-name").clientHeight;
console.log(elemHeight);
I need some help figuring out how to get the px.
Thank you !
Try this:
var css = document.querySelector('.user-name');
console.log(window.getComputedStyle(css).height);
The clientHeight is the px value so using concatenation you can just do the following:
let elemHeight = document.querySelector(".user-name").clientHeight;
let elemHeightPx = elemHeight + 'px';
console.log(elemHeightPx);
<div class="user-name">
Show me the px value in the box below!
</div>
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.
I'm trying to make a auto-scrolling div that go to its top when it reaches the end. But it doesn't work...
function scrollPannel()
{
var pannel = document.getElementById('pannel');
if (typeof scrollPannel.count == 'undefined')
{
scrollPannel.count = 0;
}
else
{
scrollPannel.count += 2;
}
// trouble is here
if ((scrollPannel.count - pannel.scrollHeight) > pannel.clientHeight)
{
scrollPannel.count = 0;
}
pannel.scrollTop = scrollPannel.count;
setTimeout('scrollPannel()', 500);
}
HTML:
<div id='pannel' style="height:200px;overflow:auto" onmouseover="sleepScroll()">
<p>...</p><!-- long text -->
</div>
And after, I will need to find how to stop scrolling when "onmouseover" occures.
EDIT: I did not explained the problem clearly. In fact, I have tried something like:
if (scrollPannel.count > pannel.scrollHeight)
{
scrollPannel.count = 0;
}
The problem is that scrollHeight seems greater than div inner text. So it makes a lot of time to return to the top.
So I need an element property of which I could use the value to compare with my count variable. However I don't know Javascript a lot and I could not find anything. I hope it is as well simple as I think of it.
Try:
// calculate max scroll top position (go back to top once reached)
var maxScrollPosition = element.scrollHeight - element.clientHeight;
// example
element.scrollTop = maxScrollPosition;
That should do what you need.
You could try using the scrollHeight property.
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollHeight
The solution I have involves jQuery, hope that's not a problem.
JavaScript:
var timeout;
function scrollPannel()
{
var divHeight = $("#pannel").height() / 2;
var scrollCount = $("#pannel").scrollTop();
var scrollHeight = $("#inside").height() - 20 - divHeight;
scrollCount += 2;
if ((scrollCount - scrollHeight) > 0)
{
scrollCount = 0;
}
$("#pannel").scrollTop(scrollCount);
timeout = window.setTimeout(scrollPannel(), 100);
}
function scrollStop() {
window.clearTimeout(timeout);
}
HTML:
<div id='pannel' onmouseover="scrollStop();" onmouseout="scrollPannel();">
<p id="inside"></p><!-- long text -->
</div>
Explanation:
jQuery's .height() of the inside element <p> gives us the actual height you're looking for, but it's not enough for reaching the bottom, since that happens before we reach the element's height. A little investigation shows that the "top" of scrollTop() is about half way inside the original div's height. You may need to play around with divHeight to get the exact results you're looking for.
Of course, I also included a method for stopping and continuing scrolling.
Good luck!
You should use scrollHeight property but to call it, you need to use an index like that:
$('#pannel')[0].scrollHeight;
If you set the scrollTop and scrollLeft to really high silly values they only ever get set as their maximum allowed values which I think is what you need? You can then use them to work out the scroll center if you wished.
See snippet example.
var mB = document.getElementById('myBox');
var mR = document.getElementById('myResult');
// Set the top and the left to silly values
mB.scrollTop = 99999999;
mB.scrollLeft = 99999999;
// They will only end up being set as their max
mR.innerHTML = "maxTop="+mB.scrollTop+"<br>maxLeft="+mB.scrollLeft;
// Now take the max values and divide by 2 to scroll back to middle.
mB.scrollTop = mB.scrollTop/2;
mB.scrollLeft = mB.scrollLeft/2;
#myBox{
overflow:auto;
}
#myContent{
border:1px solid black;
background-color:red;
}
<div id='myBox' style='width:300px;height:300px'>
<div id='myContent' style='width:500px;height:800px;line-height:800px;'><center>I am the center of the content</center></div>
</div>
<div id='myResult'></div>
I have got one solution....
function findMaxReach(){
let maxReach =0
document.querySelector('.YourElement').scrollLeft = 100000;
maxReach = document.querySelector('.YourElement').scrollLeft;
document.querySelector('.YourElement').scrollLeft = 0;
return maxReach
}
How can I write an if condition that will run if an element is 60% of the window's width worth off the screen?
I've tried using style.left > '40%' but that doesn't seem to work. Or be right.
You can use javascript and jQuery to do this pretty easily.
To find the right edge of your object (stored in memory as f here), use this code:
var rightEdge = f.width() + f.offset().left;
To find the screen width, you can use this code:
var screenWidth = $(window).width();
The amount of object that is "off screen" is calculated by subtracting screenWidth from rightEdge, therefore this boolean expression describes when the object is more than 60% off the screen:
rightEdge-screenWidth > f.width()*.6
Here's a working demo:
http://jsfiddle.net/YeyFj/
This isn't directly answering your question, but I created this fiddle that might make it easier to play with the math that you need to do.
http://jsfiddle.net/5ucbX/
var w = $('#container').width();
var el = $('#el');
el.draggable({
stop: function () {
var ew = el.width();
//this is your "formula"
var l = el.offset().left + (ew * .6);
if (l > w) {
el.addClass('over')
}
else {
el.removeClass('over')
}
}
});
I'm thinking of implementing a custom auto-complete feature so basically my idea now is that i will make an abs positioned div and give it the position here:
(image) http://i.stack.imgur.com/3c5BH.gif
So my question is with a variable referencing the textbox, how do i get the x and y position directly under the left bottom side of the input rectangle?
My script must work in latest versions of IE / FF / Safari / Opera / Chrome
I know i can use a library to do it, but no i'm interested in learning how do they do it (or maybe better ways)?
This question is a lot more complicated than it seems and involves getting the position of the element relative to the document. The code to do so can be pulled from the jquery source (http://code.jquery.com/jquery-1.6.1.js -- search for "jQuery.fn.offset")
in jQuery:
var node = $('#textbox'),
pos = box.offset(); // the complicated piece I'm using jQuery for
node.top += node.height(); // node.offsetHeight without jQuery
node.left += node.width(); // node.offsetWidth without jQuery
The answer can be extremely simplified if you don't care about FF2 or Safari3:
var box = document.getElementById('yourTextBox').getBoundingClientRect(),
left = box.left,
bottom = box.bottom;
x = x offset
y = y offset - ( textbox height +
padding-top + padding-bottom )
Good comments! For my scenario, there is always an offset parent (which is why I use position - http://api.jquery.com/position/). In hopes that it might help someone else wanting a quick fix, here's the code:
// I have a parent item (item) and a div (detail)
// that pops up at the bottom left corner of the parent:
var jItem = $(item);
var pos = jItem.position();
var marginTop = parseInt(jItem.css('margin-top'));
if (isNaN(marginTop)) {
marginTop = 0;
}
$(detail).css("top", pos.top + jItem.outerHeight() + marginTop)
.css("left", pos.left);
$(detail).show();
Just give the box a defined width and height. Then, get its top and left property and add it with the width and height. Simple. I am gonna give you Pseodocode.
<STYLE>
object{width: 100px; height: 20px;}
</STYLE>
<SCRIPT>
x = object.left;
y = object.top;
x = x + object.width;
y = y + object.height;
</SCRIPT>