JQuery('body').offset().top is off when using margin-top? - javascript

So, if I understand http://api.jquery.com/offset correctly, $('body').offset() should return the position where the body is located, relative to the document. So inserting a <p>-tag at those coordinates on the page should put it at the very position of the body tag. But that is not what happens!
I tried this in both Safari 5.0.5 and Firefox 3.6 and both cases, the alert says "8" and the <p>-tag ends up 8 pixels from the top of the page, whereas the body tag starts 100 pixels further down on the page, as can be seen if inspecting using e.g firebug.
<!doctype html>
<html>
<head></head>
<body>
<div style="margin-top:100px;background:yellow;">
<p>Hello World</p>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
</script>
<script>
alert(jQuery('body').offset().top);
var myp = jQuery('<p>Top of body?</p>')
myp.appendTo(jQuery('body'));
myp.offset(jQuery('body').offset());
</script>
</body>
So the question is: how am I supposed to do this so that the <p>-tag ends up in the body, and not at the top of the page, using .offset()?

In most cases you'll find the body offset is equal to 0, that is because the body of the page is == you browsers viewport.
The reason Hello World is 100px down, is because you've applied a padding to it. Do you want your text "Top of body?" to appear below Hello World?..
If so, first give your div a class name (I've used hworld) and then append your var to it.
<div style="margin-top:100px;background:yellow;" class="hworld">
And:
myp.appendTo(jQuery('.hworld'));
Hope this helps...

There must be something else interfering with your code.
It works fine in this fiddle I created: http://jsfiddle.net/jasongennaro/7sGGq/

Related

Why is this Javascript printing my comments in the rendered HTML

I'm new to Javascript, as in just really getting started with it today. I'm testing some very basic code in the first chapter of a book and encountered a problem on the first example. I wrote the code in Notepad++, but even in that program my second line of commenting is black and not green. Why does the line right after </noscript> render?
The output to my browser is rendered as: Hello World! // Display a message dialog after the page has loaded.
<!DOCTYPE html>
<html>
<body>
<div id = "panel">
<script type = "text/javascript">
// Dynamically write a text string as the page loads.
document.write("Hello World!");
</script>
<noscript>Javascript is Not Enabled!</noscript>
// Display a message dialog after the page has loaded.
<body onload = " window.alert('Document Loaded!');">
</div>
</body>
</html>
That's because you're writing your comment not in a JavaScript part but in an HTML one.
Comments in HTML are like this :
<noscript>Javascript is Not Enabled!</noscript>
<!-- Display a message dialog after the page has loaded. -->
Note that you've put a body element inside the body, that's not good. You probably wanted this instead of the second body :
<script>
window.onload = function(){
alert('document loaded!');
};
</script>
<!-- This is a comment in HTML -->
/* This is a comment in Javascript */
Your comment are not between script tag. You can move it into an script tag or use the HTML comment just like #22kar said.
Also you need to put the parameter "onload" in the first body tag and remove the other one.
The reason the line you tried to comment out is rendered is because you have attempted to comment out the text with JavaScript comments.
The browser rendering html sees the two slashes (//) as part of the text, not as markup designating a comment.
The correct way to comment out something in html is with <!-- and -->.

How to get visible element using jquery

Hi I have one hidden div and inside it i have visible span. I want to alert some text if span does not have display none property.
<head>
<script type="text/javascript">
$(function() {
if($('span').is(':visible')){
alert(0)
}
})
</script>
</head>
<body>
<div class="fa" style="display:none">
<span>sdf</span>
</div>
</body>
According to jQuery API
Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.
Your <span> is a child of a <div> that's hidden with display: none - that means neither the <div>, nor the <span> consume any space in the document.
Which means that your <span> is hidden and your script has no errors - it does exactly what it suppose to do.
The reason your alert doesn't fire is that your span isn't visible. The fact that it is contained within an element that has display: none means that it will not be shown. If you specifically want to check if it is display: none itself, use css.
if($('span').css('display') != "none"){
alert(0)
}
You don't import jQuery.
Add this in your head element :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Note that an HTML file must also have HTML opening and closing elements, and preferably a doctype. The following file works :
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
if($('span').is(':visible')){
alert(0)
}})
</script>
</head>
<body>
<div class="fa" style="display:none">
<span>sdf</span>
</div>
</body>
</html>
And it does nothing, as your span is in a not displayed div.
Now, if you want to precisely know if your element does't have the style display=none set directly on it, test it like this :
if ($('span').get(0).style.display!='none') {
Demonstration
Your problem is that the div containing the span element has display:none as property, try this Fiddle, you just put display:hidden instead of none and the JS works.
<div class="fa" style="display:hidden"><span>sdf</span></div>

blank div on ie but not blank

for example have a div,html code below
<div id="testDiv"></div>
but when i set the innerHTML property of the div(id=testDiv) on ie ,see the code below:
document.getElementById('testDiv').innerHTML= '';
and the div will have a height and width,not a blank div any more
so that is why??
if i want the div is a blank div when set the innerHTML=''(if do not set the display:none),how should i do?
now show the test code(different results runing on ie7 and chrome)
<!DOCTYPE>
<html>
<head>
<style>
#bl{background:red;}
</style>
<script type="text/javascript">
function f(a){
var t=document.getElementById("bl");
t.innerHTML=a;
}
</script>
</head>
<body>
<button type="button" onclick="f('')">test</button>
<div id="bl"></div>
</body>
</html>
In your function, check if the text is '', and if so, remove the child node from the div. instead of setting its value.
if (a=='') t.removeChild(t.childNodes[0]);
else t.innerHTML=a;
Checked in IE8 and in IE8's compatibility mode (so it should work in IE7 too).
For more stability, you can remove all child nodes from t, like so...
if (a=='') {while (t.hasChildNodes() t.removeChild(t.childNodes[0]);}
else t.innerHTML=a;
I think this is a known IE behaviour.
In addition to setting innerHTML to empty string you can also set font-size to 0.

jQuery $("*").fadeTo() moves content before fading

Why does all content get jerked downwards before fading in the following, and how can i fix it?
Using FireFox 3.6.3, thanks in advance.
<html>
<head>
<script type="text/javascript" language="javascript" src="http://localhost/javascript/jquery-1.4.2.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#button").click(function(){
$("*").fadeTo("slow",0.0);
});
});
</script>
</head>
<body>
<p>Just a normal paragraph doing my job!</p>
<p>Me too!</p>
<input type="button" id="button">
</body>
</html>
It has something to do with trying to fade all elements, including those outside the <body>. Try:
$("body > *").fadeTo(..)
But why would you want to fade every single element, when you can simply do a fade on the body itself.
$("body").fadeTo(..)
Edit: Some more research shows that when trying to fade the <style> and <head> elements, in no particular order, causes everything to move down. Don't know why yet, but you can see an example here - http://jsfiddle.net/UKn8r/2/
Edit 2: Ok, I think I may have a reason here. The <head> and its children elements such as <style>, <script>, etc. are by default set to display: none in the user agent's stylesheet. When fading them out, jQuery ends up setting their display property to display: block. Now the contents of these child elements are not meant to be displayed on the screen, but by setting them to display: block, it gets displayed as a horizontal block about 20px high with no content, which shifts everything else downwards. Note that if you were to empty out the <script> element and make the onclick inline, then you wouldn't see the jump on Firefox since the element will be empty and not consume any space on screen even when displayed as a block. So changing it to:
<html>
<head>
<script src="http://localhost/javascript/jquery-1.4.2.js"></script>
</head>
<body>
<p>Just a normal paragraph doing my job!</p>
<p>Me too!</p>
<input type="button" id="button" onclick='$("*").fadeTo("slow",0.0);'>
</body>
</html>
will not cause any jumps.
Also, your original code verbatim, will work properly on Webkit browsers (Chrome, Safari) as the display style property for <script> elements does not get overridden as block. For these browsers, however, if you were to have a style element with some content inside it, then you would see the same behavior as <style> will have an inline style attribute having display: block. Now it may seem utterly useless to have something like, <style style="display: block; opacity: 0">..</style>, but this is just an explanation for why you're seeing the behavior that you're seeing. So to reproduce the same problem on these browsers, try this code:
<html>
<head>
<script src="http://localhost/javascript/jquery-1.4.2.js"></script>
<style>p {}</style>
</head>
<body>
<p>Just a normal paragraph doing my job!</p>
<p>Me too!</p>
<input type="button" id="button" onclick='$("*").fadeTo("slow",0.0);'>
</body>
</html>
The <style> property must have some content, and not pure whitespace, so I put the junk p {} there.
This concludes my wasteful search for something that shouldn't be done in the first place :)
Try to fade out your main container, or all elements at body level. For example:
$('body > *').fadeTo('slow', 0.3)
Fading out * doesn't look like a good idea. When you have nested elements (and you probably do), they will both be fade out, having odd effects and exceptionally poor performances.

DOM when not an actual document

Ok, lets say I go to http://www.google.com/intl/en_ALL/images/logo.gif , which is not really a document, but an image, iin my browser. Does it still have a document object? Can I use javascript: in my location bar? Wha'ts the deal with this? Thanks.
A quick look with Firebug reveals that yes indeed, there is a DOM and a document object. For example, javascript:alert(document.title) in the location bar gives "logo.gif (GIF Image, 276x110 pixels)". This results from the construction of the following document by the browser:
<html>
<head>
<title>logo.gif (GIF Image, 276x110 pixels)</title>
</head>
<body>
<img src="http://www.google.com/intl/en_ALL/images/logo.gif" alt="http://www.google.com/intl/en_ALL/images/logo.gif"/>
</body>
</html>
This is also true in Chrome (with a slightly different string for the title); the HTML is
<html>
<body style="margin: 0px;">
<img style="-webkit-user-select: none" src="http://www.google.com/intl/en_ALL/images/logo.gif">
</body>
</html>
In IE, it appears that document.title is empty, but javascript:alert(document.body.clientWidth) gives a result equal to the client area of the browser, so it looks like there's a DOM there as well. The HTML is as follows:
<html>
<head>
<title></title>
</head>
<body>
<img src="http://www.google.com/intl/en_ALL/images/logo.gif" complete="complete"/>
</body>
</html>
It depends on the browser. If you go to that URL in firefox, for example, and open the DOM Inspector, you will see an html, body and img tag; also, typing javascript:alert(document) in the location bar will alert [object ImageDocument]. IE8 exhibits similar behaviour (but alerts just [object]).
no... the browser simply acts as a picture viewer

Categories

Resources