Solved

jquery's answer for document.write

Posted on 2011-03-10
11
1,280 Views
Last Modified: 2012-05-11
Hello there,

I am fairly new to jquery not to webdevelopment but am trying now to avoid the use of document.write as I have read in loads of places how problematic this is especially in the modern world of jquery and xhtml compliancy.

I was researching a bit on the net to try to find a jquery alternative to the use of document.write and while I found plenty I could not see how it answered my issue so here it is.

I have a client that I am using a web service from to dynamically generate a verse of the day text to my website.  The way they are going about this is pretty much having you put a script tag into your document that basically loads their .js file that I guess they somehow update on a daily basis or their software does or something.

Anyway the way they told me I need to allow their verse of the day to work on my site is the use of the following script:


-----------------------------------------------------------------------------------------------
<script Language="JavaScript1.2">
<!--
var votdtext;
votdtext = null;
// -->
</script>
<script Language="JavaScript1.2" src="http://votd.Christ.com/biblevotd/votd-kjv.js">
</script>

<script Language="JavaScript1.2">
<!--
if (votdtext != null) {
document.write(votdtext);
}
// -->
</script>
-------------------------------------------------------------------------------------------------------

Now upon looking into their js file that I had to reference in my html I noted that what is being written via the document.write routine is in fact a variable that contains two variables plus some inline text take a look at the actually js file below

---------------------------------------------------------------------------------------------------
<!--
now = new Date();
if (!window.christcombiblevotdimgurl) window.christcombiblevotdimgurl = "biblevotd.gif";
votd0 = '<center><a href="http://www.Christ.com/biblevotd/biblevotd.html" target="_blank"><img class="christcombiblevotdimg"  src='+christcombiblevotdimgurl+' border="0" alt="Bible Verse of the Day" height="65" width="200"></a><BR><BR></center>';
if (now.getDay() == 0) {votd1 = "Set your affection on things above, not on things on the earth. <BR><br><div align=left><I>Colossians 3:2</I> (KJV)</div>";}
if (now.getDay() == 1) {votd1 = "&nbsp;&nbsp;&nbsp;<sup>4</sup>And my speech and my preaching was not with enticing words of man\'s wisdom, but in demonstration of the Spirit and of power: <BR>  &nbsp;&nbsp;&nbsp;<sup>5</sup>That your faith should not stand in the wisdom of men, but in the power of God. <BR><br><div align=left><I>1 Corinthians 2:4-5</I> (KJV)</div>";}
if (now.getDay() == 2) {votd1 = "&nbsp;&nbsp;&nbsp;<sup>11</sup>It is a faithful saying: For if we be dead with him, we shall also live with him: <BR>  &nbsp;&nbsp;&nbsp;<sup>12</sup>If we suffer, we shall also reign with him: if we deny him, he also will deny us: <BR>  &nbsp;&nbsp;&nbsp;<sup>13</sup>If we believe not, yet he abideth faithful: he cannot deny himself. <BR><br><div align=left><I>2 Timothy 2:11-13</I> (KJV)</div>";}
if (now.getDay() == 3) {votd1 = "Jesus Christ the same yesterday, and to day, and for ever. <BR><br><div align=left><I>Hebrews 13:8</I> (KJV)</div>";}
if (now.getDay() == 4) {votd1 = "&nbsp;&nbsp;&nbsp;<sup>1</sup>I love the LORD, because he hath heard my voice and my supplications. <BR>  &nbsp;&nbsp;&nbsp;<sup>2</sup>Because he hath inclined his ear unto me, therefore will I call upon him as long as I live. <BR><br><div align=left><I>psalms 116:1-2</I> (KJV)</div>";}
if (now.getDay() == 5) {votd1 = "Let love be without dissimulation. Abhor that which is evil; cleave to that which is good. <BR><br><div align=left><I>Romans 12:9</I> (KJV)</div>";}
if (now.getDay() == 6) {votd1 = "Where there is no vision, the people perish: but he that keepeth the law, happy is he. <BR><br><div align=left><I>Proverbs 29:18</I> (KJV)</div>";}
votdtext = votd0 + votd1 + '<center><BR><font size="-1"><a href="http://www.Christ.com" target="_blank">www.Christ.com</a></font></center><BR>';
// -->
------------------------------------------------------------------------------------------------------------

Notice that the thing I am suppose to write via the document.write routine is this votdtext variable.

Now having said this I have found in jquery that it seems as though the alternative to document.write would be something like the following:

----------------------------------------------------------------------------------
<script language="JavaScript1.2">
<!--
if (votdtext != null) {
$(document).ready(function(){
     $("div.verseoftheday").append(votdtext);


});
}

// -->
<div class="verseoftheday"></div>
</script></div>
------------------------------------------------------------------------------

Of course as you can imagine I couldn't get this code to real in that variable named votdtext and so I know I am missing something.

In reality I am looking for an alternative to document.write that gives the same outcome of dynamically writing out something stored in a javascript variable to your website.  The answer may not be in jquery it may well be in the use of a non depreciated javascript attribute with in its DOM but I hear that everyone seems to be saying to opt to use a jquery routine to accomplish what document.write use to do but now is very inefficient not to mention causes multiple errors in web application scenarios like I have such as DNN.

Also as a note could you give me the full example including the document.ready part if using jquery to do it or the full example if simply using a different attribute of javascript that wouldn't cause unnecessary javascript errors on my website.

Lastly I noted in one example someone gave about how to use document.write and work around the not closing script properly for xhtml problem they gave this snippet which I think used jquery

---------------------------------------------------------------------------
var phbRequirement = "";

$(function() {
  document.write = function(evil) {
    phbRequirement += evil;
  }
  document.write("Haha, you can't change my code!");
  $('body').append(phbRequirement);

});
---------------------------------------------------------------------------------
my question here is I notice instead of using the following to start their jquery:

$(document).ready(function(){

they rather used what I think is a short cut for the document.ready statement which was

$(function() {

am I correct here.  can $(function() { be used in place of the longer version to write jquery code.

Also if you are at all familiar with DNN you would know they use the jquery that is hosted on google's CDN allowing you to src into them to load your jquery library. The reason i bring this up is because I am curious if you opt to take advantage of this route is their still a need to have a

<script type="text/javascript">
your jquery information
</script>

or could I simply just through into something like a dotnetnuke html module stuff like

$(function() {

jquery effects

});

without having to encapsulate this in actual script tags since I am piping the library in via google's CDN or rather I am using google's hosted jquery via dotnetnuke configuration in the host settings area.

Anyway let me know what you can with examples of a work around to implement my need to write a variable from another server into my website without the use of document.write as I know it is out their but since I am still wet behind the ears in regards to all that jquery can do I would appreciate any assistance you could give in this regard.

Thanks,

Bo
0
Comment
Question by:cyborama
  • 5
  • 4
  • 2
11 Comments
 
LVL 19

Assisted Solution

by:Bardobrave
Bardobrave earned 500 total points
ID: 35096536
Well... the example you put:

$(document).ready(function(){
     $("div.verseoftheday").append(votdtext);
});

should work. Probably your trouble here is related to the variable, that is loaded into your page from an external js and is not in the scope of your jquery code.

What I suggest is that you use something inside the page to temporary store the data of the variable, and retrieve it in jquery.

So, in your main page you have:

<script Language="JavaScript1.2">
<!--
var votdtext;
votdtext = null;
// -->
</script>
<script Language="JavaScript1.2" src="http://votd.Christ.com/biblevotd/votd-kjv.js">
</script>

<script Language="JavaScript1.2">
<!--
if (votdtext != null) {
document.getElementsById("myHiddenInput").value = votdtext;
}
// -->
</script>
<script language="Javascript" src="pathToYourJqueryScript" ></script>

And your file with jquery will state:

$(document).ready(function(){
     $("div.verseoftheday").append($("#myHiddenInput").val());
     //you can try also $("div.verseoftheday").html($("#myHiddenInput").val());
});

However... this is a bit of a nuthouse, as you can insert your data into the target div when you're passing it to the input with:

document.getElementById("verseofthedayDivId").innerHTML = votdtext;

The real problem in mixing outside values and Jquery is in the fact that jquery doesn't start to execute until whole file (and it's external references) is loaded, so data get from external sources will not be reachable within Jquery.
0
 
LVL 38

Expert Comment

by:Aaron Tomosky
ID: 35096626
I like innerhtml. That way the page loads and then your js fills it in whenever it gets around to it
0
 

Author Comment

by:cyborama
ID: 35096789
aarontomosky,

how would this work when using external variables from an external js file.  Could you put example of how to write an external variable via the use of innerhtml.  I like this approach to when mixed with a javascript function but than again the javascript function I have used contained document.write in it since I created the function and could not think of another work around for document.write to spit out some text for me within the js file.

But in regards to a variable call opposed to a function call how would I achieve this via innerhtml when the variable I am wanting to write via this method is from a js file being piped in through a script tag.

Also what are the advantages or disadvantages of using your approach opposed to  bardobrave's approach via jquery.

It looks like your code might be much more simplistic but than again is it really when I see the full example and if so at what cost if any is it.

Thanks,

Bo

NOTE TO BARDOBRAVE COMMENT: Hello Bardobrave I am thinking of trying your approach as well as possibly aarontomosky's approach just to see them both at work but I have a question in regards to one of your syntactical lines which was the following:

<script language="Javascript" src="pathToYourJqueryScript" ></script>

In the event that my CMS pipeline's the jquery library (I think it is 1.4.2) right into the CMS engine (I am using DNN to do this) is it necessary to use this bit of code and if it what should the file look like that I point it to.  I am guessing it is not the jquery library file, correct as hosted on googles CDN.  If it is, than shouldn't my web application that includes this library in the core of every dynamic page it generates have already dynamically included the above script so I wouldn't need to type it in again?

Thanks for all your help in helping me get around having to use document.write to do stuff that tends to throw javascript errors in web applications and elsewhere in my case this old school routine seems to effect the CMS's API and that is when I really woke up to the fact I needed to quit coding with this as part of my DOM toolkit.

Thanks,

Bo
0
 
LVL 19

Expert Comment

by:Bardobrave
ID: 35096915
This line

<script language="Javascript" src="pathToYourJqueryScript" ></script>

makes reference to the file where you have inserted your jquery code, not to the jquery library. I usually get jquery code apart from plain javascript to avoid mergin both syntaxes.

If you take a look to my comment, I already suggested the possibility of using .innerHTML to insert the code into the DIV. In your situation I think it'll be probably easier than Jquery, as your variable will be available on the plain javascriptl code.

I'm not very sure of being understanding your question about the CMS jquery ilbrary included. May you explain it a bit further to see if we can clarify it?
0
 
LVL 38

Expert Comment

by:Aaron Tomosky
ID: 35097400
Bardo did already mention innerhtml in his solution. I was just emphasizing that part as a generic way to avoid document.write.
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:cyborama
ID: 35097612
thanks arrontomosky I guess I missed that part of the comment when reading the jquery solution.

Thanks Bardobrave for pointing me back to your comment.

by the way Bardobrave in regards to the CMS Jquery library what I was referring to is that in DNN in their host settings they have a category called jquery where it tells you what jquery is installed if you opt to use the installed jquery or gives the option to utilize the hosted jquery from google located in the following place:

http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

Take a look at the jpg I included in this comment so you can see the the section in the host interface that I am referring to in regards to what is going on here.

I was trying to put the jquery code into a text/html module which in simple terms is just a way in which DNN stores html in a table via this module so it can be accessed dynamically that is why I was confused about your line of code that read the following:

<script language="Javascript" src="pathToYourJqueryScript" ></script>

This may sound like a silly question but when you say "pathToYourJqueryScript" would this be the path to a js file that had jquery script in it which wasn't the libary that builds the jquery framework such as

$(document).ready(function(){
     
your jquery code

});

If this is the case I didn't realize you could incorporate jquery commands within a js file.  I of course knew that you could put any javascript code you wanted into a js file but wasn't sure if by "PathToJquery code  you were referring to a path to some js file or some other file type.  I am assuming it would have to be a js file though since jquery is just a project shoot off of javascript I just had never heard of being able to just through some jquery code in say a .js file and have it executed in this manner.

if I did do this would I include the

$(document).ready(function(){
     
your jquery code

});

inside the js file or would I not need the $ before the (document.ready(function(){ thing if strictly encapsulated inside a js file.

Lastly instead of using

$(document).ready(function(){
     
your jquery code

});

could I instead use the following as a shorthand for $(document).ready(function(){

$(function() {

jquery effects

});

I saw someone trying to illustrate something about jquery using this other syntax and just wanted to make sure this was equivalent to the document.ready thing because it is a quicker method for invoking the jquery code when document is ready.

Thanks,

Bo


dnnjquery.jpg
0
 
LVL 19

Accepted Solution

by:
Bardobrave earned 500 total points
ID: 35098091
Ok, let's see if I can answer all your doubts without missing nothing.

The JQuery settings of the CMS you're using probably allow you to select between different versions of the JQuery framework. You can use any compatible version, the main difference between installed one and the one you link in googleapis server probably is that this last is a min version, which means that's compressed to the max (without tabulations or blankspaces to save max memory usage), and the 1.4.2 installed on the server could or could not be a min version. For production environments I always recommend minimal versions, while on development they are too hard to examine.

In selecting between both also you have to take in consideration that external resources to your domain server are dependents of it's own host. So... if you use a JQuery library inside googleapis server and this server suffers a takedown while your project's one is up, all of your JQuery code will start to fail. I've never seen google servers down... but... hey... it can happen.

The file I referred to with the <script language="Javascript" src="pathToYourJqueryScript" ></script> line is indeed the file in wich you get your JQuery code, not the main library of JQuery.

JQuery IS javascript code, so you can include inside any .js file, even you can mix normal javascript syntax and JQuery syntax (although I encourage to separate things). Just have in mind that JQuery library recognizes "$" in your javascript code as a delimiter and parses what it founds after the "$" if it's something that fits to the JQuery syntax. JQuery is something like an intermediate layer between you and javascript that makes things a lot easier, but from the beginning to the end it's all javascript.

I usually generate separated .js files for my different pages, loading them on demand to avoid that pages that doesn't use any client code interaction has to load somewhat heavy code files. This is why I recommended the use of a .js in my previous example, you can mix your JQuery code directly inside the same page where you load the result of the webservice call, but I discourage this mixtures.

The correct way to use JQuery code is with this syntax:

$(document).ready(function(){
     
your jquery code

});

And you will need to use "$" delimiter also if it's in your main page code or if you load it from within a .js file, as "$" is the thing that tells JQuery library "hey, from here you take control of the code".

I've seen sometimes the $(function() {}); syntax, but I'm not quite comfortable with it as code starter. I mean: $(document).ready is a JQuery structure that only starts to execute after the whole page is loaded. Many internal things inside the library are thinked with this simple idea in mind, when you start executing JQuery, all elements on page MUST be loaded.

If you use $(function() { anything } ); inside your code, JQuery library will recognize it and try to parse and execute, but, depending on what are you doing inside that "anything", maybe it doesn't work, or doesn't work as you expect it to do.

Let's try to explain it a bit better graphically:

$   --> Dude... this is Jquery, wake up JQuery library to parse
(document).ready(  --> uh oh... wait until whole page is loaded
        function ()  { anything }  --> execute anything
); --> finish your document.ready

$ --> Dude... this is JQuery, wake up JQuery library to parse
(function () { anything } --> Execute anything... -what? without awaiting for the whole page? -yup
); --> finish your JQuery execution.

I hope this clarifies a bit your doubts. Feel free to ask further questions if something is not completely clear... sometimes I get clumsy when trying to explain complex ideas on english.
0
 

Author Comment

by:cyborama
ID: 35099561
That seems to make perfect sense.

I appreciate the fact you emphasized the use of the $ in the js file as that was one of the things I really wasn't sure about.  I think this does make a lot better sense than to throw it onto some module inline as I could put it into the header section of that given page so only when that page loads will the contents of the js file load that utilizes whatever is needed for a given page.

I think for my specific scenario it will make more sense to use the innerhtml approach you highlighted but I will say that for more complex things such as the use of certain jquery plugins, etc... I would need to know some of these things.

All i knew is I had to get rid of the document.write syndrome and I think this will be enough for me to get the idea of why I should you one type of jquery format over another.

Thanks so much for your help in this matter I will leave this open for a bit in case their is something else you might want to add to it if not I will close it in your favor thank you for your help as you have been extremely helpful

Bo
0
 

Author Comment

by:cyborama
ID: 35103177
Hello there,

I have accepted the wrong thing as the solution.

I am not the one that came up with this solution but rather it was bardobrave.  I was wondering if you could cancel this request so I could give points to proper person who was so willing to give this answer I definitely should not get the credit for the answer as the comments I put for the grade was aimed for Bardobrave not me.

Thank You,

Bo
0
 

Author Closing Comment

by:cyborama
ID: 35103210
Bardobrave gave excellent advise,

I could tell he knew what he was doing in regards to this jquery and javascript stuff.  Thank you for such a complete explination of what I should do even went the extra mile to simplify things with a graphical text approach as it might look in code so I will say I can't thank you enough for your reply.

Bo
0
 
LVL 19

Expert Comment

by:Bardobrave
ID: 35106127
I'm glad to be helpful. Good luck with your work ahead.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Although it can be difficult to imagine, someday your child will have a career of his or her own. He or she will likely start a family, buy a home and start having their own children. So, while being a kid is still extremely important, it’s also …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now