Applying a CSS class to a javascript popup window - javascript

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.

Related

jQuery finds no elements with specified id

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>

How to re-apply prettyPrint AFTER run_prettify.js has been loaded

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');

Dynamically change page title from h1 tag using Javascript

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.

How to make images clickable in javascript?

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 &quot 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>

Manipulating <body> with jQuery? (Or figuring a better solution)

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

Categories

Resources