I'm trying to create a JS-script to make modifications to add a footer to HTML -documents on the fly. The idea is to append a div-element at the end of the document to contain the footer, and to provide a floating fixed footer, I also need to have all of the other content wrapped in a div, basically I need something like this:
<html>
<head>
<title>Foobar</title>
</head>
<body>
<div id="contentWrapper">
<!-- Content is here -->
</div>
<div id="footerWrapper">
<!-- Footer goes here -->
</div>
</body>
</html>
The problem is, that the HTML is generated from a system where the end user's have had a little too much control over the structure (it's a blogging platform), and there's no guarantee of a certain sturcture hence I need to wrap the content in a div to ensure the footer works ok.
What I tried, and realized that doesn't work is:
$(document.body).wrap($('<div/>').attr('id','footerWrapper'));
The problem with this is that due to the fact that the HTML structure is generated by the user, I have been forced to inject links to the JS-file inside the <body>-tag. So now when I call wrap(), it seems that everything is first removed from $(document.body) and then appended in the new div. Since the JS-files are linked from inside , calling wrap() seems to remove them momentarily, and it seems that the scripts are unloaded by the browser and everything stops working and I'm left with a blank page. Not exactly what I had in mind.
Next idea was to first copy the JS-tags to the head-element to preserve them, so I wrapped them in a div (yeah, ugly, I know), and tried to copy them to the :
$(document.head).append($('#copyToHead').html());
That didn't do anything, and seems that $(document.head) isn't usable with functions such as .html() and .append().
So, now I'm out of ideas. Anyone have any ideas?
$(document.head) isn't usable with functions such as .html() and .append().
That would be because document.head is undefined
Use $("head")[0]
not clear on what your are trying to add to the head part. if you are simply trying to add a div to the end here is a solution:
$(document).ready(function(){
$(document.body).append($('<div></div>').attr('id','mydiv').html('This is footer'));
});
idea
If leave fact, that $(document.body) doesn't exist, wrapping everything into div and then setting id through attr might be problematic (don't ask me why—it just happens). So I played with it and created this little snippet (with preview, 100% working).
Since you can't play with html, but can "append" script I did whole document manipulation through inline script.
code
<script type="text/javascript">
$(document).ready(function(){
$("body")
.wrapInner('<div id="wrapper"/>')
.append('<div id="footer">footer text</div>');
});
</script>
preview
http://jsbin.com/ezoqo4/3
edits:
further simplification and proper markup generation
I believe this should serve you better:
$('body')
.children ().wrapAll ($('<div/>').attr('id','contentWrapper'))
.end ()
.append ($('<div/>').attr('id','footerWrapper'))
;
Ref: wrapAll
Related
Good day! Newbie here. I just want to know if it's possible to change the whole content of an html using javascript? I got some codes here. (not mine but whoever did this, thank you so much!) I don't know where to put/insert all the codes of the new layout like when you click a button then the whole content will change. Thank you very much for helping me.
<script language="Javascript">
<!--
var newContent='<html><head><script language="Javascript">function Hi()</script></head><body onload="Hi();"><p id="p">hello</p></body></html>';
function ReplaceContent(NC) {
document.write(NC);
document.close();
}
function Hi() {
ReplaceContent(newContent);
}
-->
</script>
The easiest way to do this is with jQuery.
function insertHtml()
{
var newHtml = '<div><span>Hello World</span></div>';
$('body').html(newHtml);
}
Something like that will replace the entire contents of body with newHtml. You can also do this with pure javascript using the .innerHtml property but jQuery has many advantages.
EDIT: If you want to add something to the DOM rather than replacing the entire thing, use
$('body').append(newHtml)
instead. This will add the content to the end of the body. This is very often used for things like adding rows to a table.
Yes it is possible but this code is not valid unless you remove the comment tags however don't use the document.write() after page load unless you want to overwrite everything in page including the script
Layout of the code:
An .html file & I link to an external .js and .css in head. Various table cells onclick make a "popup" div change its position and become visible. To do this, I made the JS functions reference a global variable which I set by adding
<script>var popup = document.getElementById('popdiv');</script>
just above the end of /body.
popdiv has 3 child elements:
<div id='popdiv'>
<div class='header'>Time Slot</div>
<div class='xout' onclick='hide(event)'>X</div>
<div class='showtag'>tag1, tag2, tag3, tag4, tag5, tag6, tag7, tag8, tag9, tag10, tag11</div>
</div>
Anything I do with popup works fine, except when I try to call popup.firstChild, which screws everything up. popup.firstChild.type returns undefined, and popup.childNodes.length returns 7. I gave the nested div an id so I could grab it; [getheader].parentNode.type is also undefined.
And I replaced the .header selector in my .css file with a first-child of popdiv selector (#popdiv >:first-child) and its style was still correctly applied; all 3 children will also inherit style attributes like color:red--if I set them in the CSS file. Not so if I set them with JavaScript.
In this case there are other ways I can access the divs, but I want to know for the sake of understanding JavaScript what the heck happened--or if I misunderstand something fundamental about parent-child HTML elements. Did I do something awful that could break other things? (Having the extra script at the end of the file feels wrong, but I don't know the actual reason it doesn't work out fine.)
Thank you in advance
Try document.getElementById('popdiv').children[0] as described here - for getting first child. Also you can use popup.firstElementChild that give you the same result.
And you can use document.getElementById('popdiv').childrento get all children.
Here is my code.
$(function(){
$("body").prepend('<div id="loading"><span id="pagename"></span></div><div id="fade_wrapper">');
$("body").append('</div> <!-- closing #fade_wrapper -->');
});
The problem is that chrome auto closes the open <div id="fade_wrapper"> so that the HTML looks like this:
<div id="loading"><span id="pagename"></span></div><div id="fade_wrapper"></div>
That closing DIV in the second code shouldn't be there. How can I wrap the entire page contents in a div using jquery?
Use .wrapInner:
$("body").wrapInner('<div id="loading"...');
append and prepend don't work that way. You prepend/append nodes, not tags.
It seems like you want to prepend some separate HTML as well. No matter:
$("body").wrapInner('<div id="fade_wrapper">');
$("body").prepend('<div id="loading"><span id="pagename"></span></div>');
The .prepend is done second so that it will be outside of the wrapping.
I recently setup custom rotational banners on my blogger using this code I come across but I can't seem to figure out how to make the images clickable to link to the homepage.
Any help would be much appreciated.
Heres the code:
<script type='text/javascript'>
var HeaderImage= new Array()
HeaderImage[0]="http://Example1.png"
HeaderImage[1]="http://Example2.png"
HeaderImage[2]="http://Example3.png"
HeaderImage[3]="http://Example4.png"
HeaderImage[4]="http://Example5.gif"
HeaderImage[5]="http://Example6.png"
HeaderImage[6]="http://Example7.png"
var random=Math.round(6*Math.random());
document.write("<style>");
document.write("#header {");
document.write(' background:url("' + HeaderImage[random] + '") no-repeat left TOP;');
document.write(" }");
document.write("</style>");
</script>
Its working now guys.
I just wasn't sure exactly where to put the tags everyone was teling me.
Thanks very much for all your help.
This code has issues with " instead of ". But aside from that, what this code is doing is setting the background image for an object with id="header". To make that object clickable, you can surround the header object with an <a> tag. For example, if the header object was a div, then you would use something like this:
<div id="header"></a>
If there's some reason why you don't want to use a link to make the area clickable (which is the simplest way to do it), then you could also use javascript like this:
document.getElementById("header").onclick = function() {
window.location = "http://my.example.com";
}
This would either be placed after the page HTML (so the object in question is already loaded when this code runs).
If you show us the actual HTML that includes the header object, we could be more specific about how to make it clickable.
From reviewing your HTML, if you want to make it clickable with just your HTML, you can change this part of your HTML:
<b:section class='header' id='header' maxwidgets='2' showaddelement='yes'>
<b:widget id='Header1' locked='true' title='Mum4d.com (Header)' type='Header'/>
</b:section>
to this (which just surrounds it with an <a> tag:
<a href="http://my.example.com">
<b:section class='header' id='header' maxwidgets='2' showaddelement='yes'>
<b:widget id='Header1' locked='true' title='Mum4d.com (Header)' type='Header'/>
</b:section>
</a>
Well, you don't actually have any image elements, so that's your first problem.
The simplest solution (to make images clickable) is to wrap images in anchor tags with the href attribute set to your index. What it seems like you're actually doing is dynamically writing some css for an element with id #header and setting its background to the image. When you do this, there are no actual img elements, so there's nothing for a user to click on other than the element itself.
Without seeing any more of your markup, I'd suggest just wrapping your #header element in an anchor like this <a href='/'><some_element id='header'></some_element></a>
Idk how Blogger works, so I'll just tell you the quick and dirty way to get it working with javascript.
Put this after the code you showed us, even after the closing script tag
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(function() {
$('#header').click(function() {
window.location = '/';
});
});
</script>
I'm wanting to add a class to the body tag without waiting for the DOM to load, but I'm wanting to know if the following approach would be valid. I'm more concerned with validity than whether the browsers support it for now.
<body>
$("body").addClass("active");
...
</body>
Thanks,
Steve
The .elementReady() plugin seems to be pretty close to what you're looking for.
It operates by using a setInterval loop, that exits as soon as document.getElementById() returns an element for a given id.
You could probably do a slight modification of that plugin (or commit an update/patch) to allow for generic selectors (at least for "tagNames") instead of just ids.
I don't believe there is any truly reliable cross-browser compatible way to address an element before it's loaded - other than this sort of setInterval hacking
Unless you are able to place your javascript command inside the target element like #JasonBunting suggests.
If the element doesn't exist in the DOM, the search will fail to find it and the action won't be applied. If you can't do it in the $(document).ready() function, you might want to try putting the code after the element being referenced. I believe this will work.
<body>
<div id='topStories'></div>
<script type='text/javascript'>
$('div#topStories').addClass('active');
</script>
</body>
If you need to add the class to the body, I would definitely use $(document).ready().
Short answer: it depends. Apparently, according to my tests, the answer seems to be yes, depending on what you want. I just tested this:
<html>
<head>
<style type="text/css">
.foobar { background-color: #CCC; }
</style>
</head>
<body>
<script type="text/javascript">
window.document.body.className = "foobar";
</script>
<div style="border: solid 1px"><br /></div>
<script type="text/javascript">
// happens before DOM is fully loaded:
alert(window.document.body.className);
</script>
<span>Appears after the alert() call.</span>
</body>
</html>
In IE 7, when the alert() takes place, the value is set correctly, but the style hasn't yet been applied (it is quickly applied as soon as the DOM is finished loading).
In Firefox, the style has been applied by the time the alert() takes place.
Anyway, hope this is helpful to you.
Basically, the answer is no. In IE6 and Firefox 2 (the browsers I have the most experience in), the element isn't in the DOM until after the close tag (or the page is done rendering, for invalid XHTML). I know that jQuery provides a convenience methods that seems to react quickly enough to avoid "flicker" in most cases. You would use it like so:
<script>
$(document).ready(function() {
$("body").addClass("active");
});
</script>
<body>
..
..
..
</body>
But that's about it for javascript.
Of course, in the example you provided, you could easily just accomplish the same effect with:
<body class="active">
</body>
That was VERY helpful.
To put a little real world to the question.
I build with the assumption that JavaScript isn't supported and then override with the JavaScript. The problem is, that when I have to wait for the DOM to load before my overrides kick in the site goes through the flicker stage as it's built. I'm hoping that if I can add a class of "active" to the body element before the rest of the site's loaded I'll be able to apply JavaScript assumed styles before the page renders.
What I don't want to do is to add this and then get a call when Firefox4 comes out that I shouldn't have done it.
If you take a look at a site I built, you'll see that it degrades gracefully, but that ficker bugs me (especially if an ad hangs the site up). I could take the other guys approach and just build it with JS assumed, but come on - that's just lazy...
Rather than adding a class to your <body> tag you might find it easier to add a class to the <html> tag by doing:
<script type="text/javascript">
document.documentElement.className = 'active';
</script>