I've started using .NET Core to develop ASP sites and so I wanted to try something I haven't tried before. I am going to make a global object that I can call functions on from any page since I have a setup in which all pages use a specific layout file.
So I got this setup here:
<html>
<header>
<css and meta stuff>
</header>
<body>
<navbar....>
<sidebar...>
<div id="render-body">#RenderBody</div>
<layout-footer....>
<script inclusions>
</body>
</html>
When #RenderBody() is called, an HTML page is served as the actual page that the browser receives, in-between the two div tags.
What I'm trying to then do, is to make a function which can hide the sidebar because you might not always need it and as such it should be possible to simply hide it.
So I wrote the following piece of code:
var UniHub = {
ToggleContextSidebar: function () {
var $sidebarAndBody = $("#render-body", "#context-sidebar");
$sidebarAndBody.toggleClass("hide-context-sidebar");
}
};
Which in theory should work right? But it doesn't. The code is called just fine, but #render-body and #context-sidebar are not found. When I debug I find that the $sidebarAndBody element has a length of 0. So toggleClass() doesn't actually apply a class to any of the two divs.
They are present at the time I press my test button:
So why could this be?
You're closing #context-sidebar then opening #render-body, so #render-body is not in the context (inside) of #context-sidebar. Hence no matching element.
EDIT: if you want both elements you could do:
$sidebarAndBody = $("#render-body, #context-sidebar");
If you only want to target the sidebar just use $("#context-sidebar");
EDIT: showing jQuery context:
console.log("# of body elems inside html:", $("body", "html").length);
console.log("# of body elems inside head:", $("body", "head").length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
I have a popup window working with the following code, but I need to amend it to apply a CSS class to either the HTML tag or the Body tag, so I can style the popup window differently than the normal site.
Here's the code I'm currently using:
<script language="javascript" type="text/javascript">
<!--
/****************************************************
Author: Eric King
Url: http://redrival.com/eak/index.shtml
This script is free to use as long as this info is left in
Featured on Dynamic Drive script library (http://www.dynamicdrive.com)
****************************************************/
var win=null;
function NewWindow(mypage,myname,w,h,scroll,pos){
if(pos=="random"){LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
if(pos=="center"){LeftPosition=(screen.width)?(screen.width-w)/2:100;TopPosition=(screen.height)?(screen.height-h)/2:100;}
else if((pos!="center" && pos!="random") || pos==null){LeftPosition=0;TopPosition=20}
settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
win=window.open(mypage,myname,settings);
}
// -->
</script>
I tried to add a line right after the win=window.open line that looked like this:
win.document.getElementById('body').className += " popup";
Unfortunately it didn't work. Any ideas on how I can make it so if a window is popped up using this javascript function it'll apply a CSS class to the window?
The HTML call to the function was with this code, if it matters.
<li>Play in pop up | </li>
Alternatively I've tried using this jquery version of a popup window (http://swip.codylindley.com/popupWindowDemo.html), but haven't figured out how to do it this way either. Thank you so much for your help, this has been killing me all day!
As you can see u are trying to reach object with id='body'.
However i think that your markup looks like
<body> ... </body>. If that's true then You can't use JS function getElementById because You have no ID on body element :)
The solution would be <body id='body'> ... </body>
Also You can use different JS function to select the body.
var body = document.getElementsByTagName( "body" );
win.document.getElementById('body')
will look for DOM element which matches the provided ID and in this case there is no element whose ID is body.
try to replace this with win.document.getElementsByTagName('body'). this should give you the body tag then you can apply the CSS class to it.
Since you will only have one body in your document you can directly assign the class to body tag in popup HTML itself.
I'm trying with Javascript code prettifier, and come up with a question.
If I do not assign class="prettyprint" to <pre> in static html, but wish to apply prettyprint later(e.g, when user click on a "colorize" button on my webpage), how can I achieve this?
Slightly modifying original run_prettify.js or prettify.js is acceptable, because I'm going to put this to offline use.
My experiment:
Writing try-delay-class.html:
<html>
<head>
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>
</head>
See it:
<pre>
class Voila {
public:
// Voila
static const string VOILA = "Voila";
// will not interfere with embedded tags.
}
</pre>
</html>
Open in Chrome v26, bring up the console, execute:
pres=document.getElementsByTagName('pre')
pres[0].className+=" prettyprint"
Syntax color does not come up.
According to a comment found here, How to get prettyprint to work on dynamically generated dom element , I find the way out. Just call:
PR.prettyPrint()
BTW: If you want to remove code color highlight, you cannot simply set pre's class to empty followed by PR.prettyPrint() again. PR.prettyPrint() can only attach color tags but not remove them. A feasible way to do that is saving your original <pre> content before applying prettyprint, then restore <pre>s content later. Verified in my post jQuery, how to clone back saved elements? .
You can find three examples here
I did it as follows in js:
document.getElementById('outputa').innerHTML =
PR.prettyPrintOne("your code in brackets or your variable (without these brackets)",
'java');
First off, thanks for taking the time to read this question. What a great community Stack Overflow has :)
I need to change the title tag of a page based on the text contained in the h1 element on that page.
I've been searching around, and I have found the "document.title" Javascript function. I've been playing around with it, trying to pull the text from my h1 element that has the class of "Category-H1".
<script type="text/javascript">
document.title = document.getElementsByClassName("Category-H1");
</script>
However, it is just setting the page title to "[object HTMLCollection]", which as I understand is a null value. Is JS the best was to do this? I know my code is jacked, any tips?
Thanks in advance! - Alex
Edit
I have been informed that line of code returns a collection object and not a string. It was pointed to a code example of:
setTimeout(function () { document.title = "iFinity User Profile - " + document.getElementById("test").outerText; }, 1000);
However, this code produces a page title of "iFinity User Profile - undefined". I have the h1 element on that page set to the id of "test".
You're almost there.
[object HTMLCollection] is not a null value--it is the string representation of a collection of html elements. You want to choose the first one and then get the inner html from it.
document.getElementsByClassName("Category-H1")[0].innerHTML
Also, make sure you do this after the document has loaded. You can either do this by adding the script at the end of your document, or have it run on the onload event of the body.
This should work:
document.title = document.getElementsByClassName("Category-H1")[0].innerHTML;
The getElementsByClassName() function returns a collections of elements ( [object HTMLCollection], so you need to get an element out of it, I'm assuming the first one.
A better solution may be the following:
<script type="text/javascript">
document.title = document.getElementsByTagName("H1")[0].innerHTML
</script>
This would save from setting a h1 class.
This is very close, but I found that - working with Firefox anyway, when you use the getElementsByTagName("H1") it gives you an array as you have recognized. However, it works better using:
<script type="text/javascript">
document.title = document.getElementsByTagName("H1").item(0).innerHTML;
</script>
Note the addition of the .item(0).innerHTML after getting the element rather than the [0].innerHTML.
I don’t know if you have any experience in it or not, but another alternative that seems to be very popular these days is the use of jQuery. As in the earlier discussions, the code below assumes that you are interested in grabbing the first instance of the “H1” tag or the “Category-H1” class. This is an important point because unless you target an “ID” attribute, you will get a collection of items.
This code also assumes that you have already implemented the inclusion of the jQuery library either directly from your website or by referencing a CDN.
<script type="text/javascript">
$(document).ready(function () {
document.title = $("H1")[0].innerText;
});
</script>
The $(document).ready will call it’s enclosed function only after the Document Object Model (DOM) has finished loading, and before the browser’s rendering engine displays the page.
The content inside the function will grab the inner text of the first instance of the “H1” tag and assign that text value to the document’s title tag in the head section.
I hope this adds another layer of help.
Is it possible to get in some way the original HTML source without the changes made by the processed Javascript? For example, if I do:
<div id="test">
<script type="text/javascript">document.write("hello");</script>
</div>
If I do:
alert(document.getElementById('test').innerHTML);
it shows:
<script type="text/javascript">document.write("hello");</script>hello
In simple terms, I would like the alert to show only:
<script type="text/javascript">document.write("hello");</script>
without the final hello (the result of the processed script).
I don't think there's a simple solution to just "grab original source" as it'll have to be something that's supplied by the browser. But, if you are only interested in doing this for a section of the page, then I have a workaround for you.
You can wrap the section of interest inside a "frozen" script:
<script id="frozen" type="text/x-frozen-html">
The type attribute I just made up, but it will force the browser to ignore everything inside it. You then add another script tag (proper javascript this time) immediately after this one - the "thawing" script. This thawing script will get the frozen script by ID, grab the text inside it, and do a document.write to add the actual contents to the page. Whenever you need the original source, it's still captured as text inside the frozen script.
And there you have it. The downside is that I wouldn't use this for the whole page... (SEO, syntax highlighting, performance...) but it's quite acceptable if you have a special requirement on part of a page.
Edit: Here is some sample code. Also, as #FlashXSFX correctly pointed out, any script tags within the frozen script will need to be escaped. So in this simple example, I'll make up a <x-script> tag for this purpose.
<script id="frozen" type="text/x-frozen-html">
<div id="test">
<x-script type="text/javascript">document.write("hello");</x-script>
</div>
</script>
<script type="text/javascript">
// Grab contents of frozen script and replace `x-script` with `script`
function getSource() {
return document.getElementById("frozen")
.innerHTML.replace(/x-script/gi, "script");
}
// Write it to the document so it actually executes
document.write(getSource());
</script>
Now whenever you need the source:
alert(getSource());
See the demo: http://jsbin.com/uyica3/edit
A simple way is to fetch it form the server again. It will be in the cache most probably. Here is my solution using jQuery.get(). It takes the original uri of the page and loads the data with an ajax call:
$.get(document.location.href, function(data,status,jq) {console.log(data);})
This will print the original code without any javascript. It does not do any error handling!
If don't want to use jQuery to fetch the source, consult the answer to this question: How to make an ajax call without jquery?
Could you send an Ajax request to the same page you're currently on and use the result as your original HTML? This is foolproof given the right conditions, since you are literally getting the original HTML document. However, this won't work if the page changes on every request (with dynamic content), or if, for whatever reason, you cannot make a request to that specific page.
Brute force approach
var orig = document.getElementById("test").innerHTML;
alert(orig.replace(/<\/script>[.\n\r]*.*/i,"</script>"));
EDIT:
This could be better
var orig = document.getElementById("test").innerHTML + "<<>>";
alert(orig.replace( /<\/script>[^(<<>>)]+<<>>/i, "<\/script>"));
If you override document.write to add some identifiers at the beginning and end of everything written to the document by the script, you will be able to remove those writes with a regular expression.
Here's what I came up with:
<script type="text/javascript" language="javascript">
var docWrite = document.write;
document.write = myDocWrite;
function myDocWrite(wrt) {
docWrite.apply(document, ['<!--docwrite-->' + wrt + '<!--/docwrite-->']);
}
</script>
Added your example somewhere in the page after the initial script:
<div id="test">
<script type="text/javascript"> document.write("hello");</script>
</div>
Then I used this to alert what was inside:
var regEx = /<!--docwrite-->(.*?)<!--\/docwrite-->/gm;
alert(document.getElementById('test').innerHTML.replace(regEx, ''));
If you want the pristine document, you'll need to fetch it again. There's no way around that. If it weren't for the document.write() (or similar code that would run during the load process) you could load the original document's innerHTML into memory on load/domready, before you modify it.
I can't think of a solution that would work the way you're asking. The only code that Javascript has access to is via the DOM, which only contains the result after the page has been processed.
The closest I can think of to achieve what you want is to use Ajax to download a fresh copy of the raw HTML for your page into a Javascript string, at which point since it's a string you can do whatever you like with it, including displaying it in an alert box.
A tricky way is using <style> tag for template. So that you do not need rename x-script any more.
console.log(document.getElementById('test').innerHTML);
<style id="test" type="text/html+template">
<script type="text/javascript">document.write("hello");</script>
</style>
But I do not like this ugly solution.
I think you want to traverse the DOM nodes:
var childNodes = document.getElementById('test').childNodes, i, output = [];
for (i = 0; i < childNodes.length; i++)
if (childNodes[i].nodeName == "SCRIPT")
output.push(childNodes[i].innerHTML);
return output.join('');
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