Select parent div from inside the containing JavaScript - javascript

I've a lot of old cached html file which uses document.write.
There are multiple element like this in every html file
<div class="time"><script>timeago('2008-06-07 17:40:53')</script></div>
timeago function writes time using document.write and the function is defined in a separate js file. So It is easy to alter the function to some thing else without changing some 200K documents.
But the issue is, how can I rewrite that timeago function to select the containing div and print the time. Is it possible to select the div from that script which is contained in that div may be using jQuery or native JavaScript?
Any advice please

How about something like this?
<script>
function timeago(d) {
document.currentScript.parentElement.innerText = 'output = ' + d;
}
</script>
<div class="time"><script>timeago('2008-06-07 17:40:53')</script></div>

Related

How to pass element ID variable to jQuery load function

I am fairly new to Jquery and HTML so please bear with me. I have my index.html with a call to jquery-1.9.1.min.js and I want to create a script that would load an outside html file. Index.html is a fairly long file so I want to break up the section for cleaner code and make it easier to modify.
<html class="no-js">
<main>
<section id="testLoad"></section>
</main>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script>$("#testLoad").load("test.html #part-1"); </script>
</body>
</html>
As you can see from the code above it loads the html file fine. What I want to do is set "#part-1" as a variable so that I can call the load script again but call a different ID from another part of the file.
I would also be open to different methods aside from this load function. All I need is to call an external html file (there are about 30 different sections) so it can display that sections data. If I do it this way is there a way to create a header file so that all of these section can have access to the same style sheet?
You'd put your load function inside a named function and pass in an argument:
function loadStuff(divId) {
$("#testLoad").load("test.html #" + divId + '');
}
In your event handler you'd call it:
$(document).ready(function() {
loadStuff('someId');
});
You could also pass in the target ID in a similar manner.
As others have pointed out, this isn't the ideal way to do what's essentially client-side templating.
It seems like you want to be able to combine multiple different "partial" html files, and for this I would recommend you look into Angular which excels at exactly this.
Not sure why you are loading the JQuery js file the way you are. That really doesn't look safe.
Another thing you can do is create an "iffy" as some people call it where it is a script that is automatically called when the page is loaded.
<script>
(function (){
//code goes here
}())
</script>
This code will run when that page is loaded.

interchange html content using javascript

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

How to document.write() within an image src string? Doesn't get parsed

This is for a Javascript application that is only intended to run on a local machine, accessing many large image files from local disk.
Original code like this:
<script>
// Constants, var inits, etc.
</script>
<-- Then html stuff including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()" src="buttons/but_run.png">
<--then a chunk of javascript related to the buttons -->
The thing works OK, see http://everist.org/NobLog/20150424_js_animated_gallery.htm
Now I want to extend it, so all image pathnames are defined as js constants and vars.
Some will remain fixed during lifetime of the browser page, others will change by
user actions.
I'm stuck with one part of this.
How to get the html parser to pay attention to script blocks WITHIN <img .... > statements?
Specifically, I want to do a document.write() within the image src string.
Like: <img src="<script>document.write(B_PATH)</script>something.png">
This is for the initial page display. The images later get changed by scripts, and that's working OK.
But the html parser doesn't seem to notice scripts inside html elements.
I'm a javascript nubie, so I may have some stupid misconception of how it all works.
Am I just doing it wrong, or is this fundamentally impossible due to reasons?
Here's an example:
<script>
// Constants
PGL_BUT_PATH = "buttons/" // where the button images etc are.
</script>
<-- some html stuff -->
<-- including some control buttons, each one like this -->
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png">
<--then a chunk of javascript related to the buttons -->
In debugger, the img element appears as:
<img id="pgb_runStop" onclick="click_runStop()"
src="<script>document.write(PGL_BUT_PATH);</script>but_run.png"/>
The intent was to get this:
<img id="pgb_runStop" onclick="click_runStop()"
src="buttons/but_run.png"/>
I could just give up with trying to have the page initially render with the correct buttons, and have js correct them afterwards. I'm just surprised... Isn't it possible to evaluate js constants during initial html parsing to construct the DOM, in this way?
Edit to add:
Sorry, I wasn't clear enough in the question. What I want is a way for js to make the html content/DOM correct (per js config values that get defined very early on) BEFORE the page first renders. To avoid any flicker or resizings after first render.
So another solution would be to delay the first page render till after some scripts have run, so they can make initial DOM adjustments before the user sees anything. Any way to do that?
Hmmm... actually that would solve another problem I have. I'll try searching for that.
The semantic templating tools suggest are interesting (had never heard of it. http://www.martin-brennan.com/semantic-templates-with-mustache-js-and-handlebars-js/ ) but am I correct that all such scripting add-ons will execute after the page first renders?
You cannot embed a tag within another tag's attribute. So you cannot embed a <script> inside the src of an <img>. That's just invalid won't-be-parsed HTML.
What you can do, though, is write the attribute after the fact:
<img id="uniqueId">
<script>
var img = document.getElementById('uniqueId')
img.setAttribute('src', PGL_BUT_PATH)
</script>
The <img> tag without a src attribute in that is invalid HTML technically, although it will probably work in any browser anyway. But if you want to stay totally legit, create the <img> with JavaScript too.
<div id="uniqueId"></div>
<script>
var elem = document.getElementById('uniqueId');
var img = document.createElement('img');
img.setAttribute('src', PGL_BUT_PATH);
elem.appendChild(img);
</script>
Tthough I really have no idea why would you like to do this.
This one works for me
<img id="pgb_runStop" onclick="click_runStop()"
src = "about:blank"
onerror="javascript:this.src = PGL_BUT_PATH + 'but_run.png'; this.onerror = null;>
or Another way
<script>
function createImg(src) {
document.write("<img src='" + src + "'>");
}
</script>
<script>createImg(PGL_BUT_PATH + 'but_run.png')</script>
Another more generic approach
<script>
function templete(temp, src) {
document.write(temp.replace("$STR", src));
}
</script>
<script>templete('<img id="pgb_runStop" onclick="click_runStop()" src="$STR"/>', PGL_BUT_PATH + 'but_run.png')</script>
Javascript isn't a templating engine in and of itself, and it looks like that's what you're trying to achieve here. Look into a javascript template library such as Handlebars and you'll have more luck.
Unfortunately, JavaScript doesn't work that way you are setting the src to <script></script> which all the browser thinks of it is just a weird URL. Try:
document.getElementById('pgb_runStop').src = PGL_BUT_PATH + 'but_run.png';
You can change pgb_runStop to whatever is the id of the element.
You can use a Framework like Angular.js to do things like that. I don't use angular.js myself but you can of some pretty incredible stuff with it.
Here's a list of even more engines that you can use
You can also use:
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
Basically, you can do:
(function(){window.onload=function(){
document.getElementById('pgb_runStop')setAttribute('src', PGL_BUT_PATH + 'but_run.png');
};}());
Which should function the exact same
Why not write the whole image in:
document.write('<img src="' + PGL_BUT_PATH + 'but_run.png"/>');
Fiddle

Generating and inserting html with javascript function

I have the following function:
<script>
function generateHtml(index)
{
document.write('Hello ' + index);
}
</script>
and I have a server side script generating the following html
<div><script>generateHtml(3)</script></div>
<div><script>generateHtml(4)</script></div>
in the hopes that Hello 3 and Hello 4 would be written in the page. However, this does not occur. Instead nothing is displayed. What is wrong with this approach?
Is it better to wrap the <div>'s is a id that can be selected and then change the html instead of writing to the DOM?
Most probably the <script> containing function generateHtml is added after the other <script>blocks, causing
Uncaught ReferenceError: generateHtml is not defined
Make sure it's added beforehand so that it works as expected.
For your code to work you must ensure that the html is present on the page after the javascript function
<body>
<script>
function generateHtml(index)
{
document.write('Hello ' + index);
}
</script>
<div><script>generateHtml(3)</script></div>
<div><script>generateHtml(4)</script></div>
</body>
To answer your question, using id's to select the DOM elements is certainly a better option.
Maybe a suggestion, use an MVVM framework such as knockout/ember/backbone/angular to do any dynamic DOM manipulation.
Example in knockout here ---> http://jsfiddle.net/x0t8dxzw/

Javascript execution order

I want to give a static javascript block of code to a html template designer, which can be:
either inline or external or both
used once or more in the html template
and each block can determine its position in the template relative to the other javascript code blocks.
An example could be image banners served using javascript. I give code to template designer who places it in two places, once for a horizontal banner in the header and once for a vertical banner. The same code runs in both blocks but knowing their positions can determine if to serve a horizontal or a vertical image banner.
Make sense?
Another example: Say you have the same 2 javascript tags in a web page calling an external script on a server. Can the server and/or scripts determine which javascript tag it belongs to?
NOTE: Can we say this is a challenge? I know that I can avoid this puzzle very easily but I come across this on a regular basis.
JavaScript code can locate all <script> elements on the page and it can probably examine the attributes and the content to check from which element it came from. But that's probably not what you want.
What you want is a piece of JavaScript which replaces tags on the page with ad banners. The usual solution is to add a special element, say a IMG, for this and give that IMG an id or a class or maybe even a custom attribute (like adtype="vertical") and then use JavaScript to locate these elements and replace the content by changing the src attribute.
For example, using jQuery, you can should your images like so:
<img src="empty.gif" width="..." height="..." class="ad" adtype="..." />
Then you can locate each image with
$('img.ad')
[EDIT] Well, the server obviously knows which script belongs into which script tag because it inserts the script. So this is a no-brainer.
If the script wants to find out where it is in the DOM, add something which it can use to identify itself, say:
<script>var id= '329573485745';
Then you can walk all script tags and check which one contains the value of the variable id.
If you call an external script, then you can do the same but you must add the ID to the script tag as you emit the HTML:
<script id="329573485745" src="..." />
Then the external script can examine the DOM and lookup the element with this id. You will want to use an UUID for this, btw.
This way, a piece of JS can locate the script tag which added itself to the page.
Best thing would probably be to make an insert once function, and then have him insert only the function call where needed.
Like this:
timescalled=0
function buildad(){
var toinsert="" //Code to generate the desired piece of HTML
document.write(toinsert)
timescalled+=1 //So you can tell how many times the function have been called
}
Now a script block calling the function can simply be inserted wherever a banner is needed
<script type="text/javascript">buildad()</script>
Thanks for the tips everyone but I'll be answering my own question.
I figured out several ways of accomplishing the task and I give you the one which works nicely and is easy to understand.
The following chunk of code relies on outputting dummy divs and jQuery.
<script>
// Unique identifier for all dummy divs
var rnd1="_0xDEFEC8ED_";
// Unique identifier for this dummy div
var rnd2=Math.floor(Math.random()*999999);
// The dummy div
var d="<div class='"+rnd1+" "+rnd2+"'></div>";
// Script which :
// Calculates index of THIS dummy div
// Total dummy divs
// Outputs to dummy div for debugging
var f1="<script>$(document).ready(function(){";
var f2="var i=$('."+rnd1+"').index($('."+rnd2+"'))+1;";
var f3="var t=$('."+rnd1+"').length;";
var f4="$('."+rnd2+"').html(i+' / '+t);";
var f5="});<\/script>";
document.write(d+f1+f2+f3+f4+f5);
</script>
Why not not just place the function call on the page instead of the entire code block? This way you can pass in a parameter to tell it what type of advertisement is needed?
BuildAd('Tower');
BuildAd('Banner');
Javascript itself has no clue of it's position in a page. You have to target a control on the page to get it's location.
I don't think it is possible for JavaScript code to know where it was loaded from. It certainly doesn't run at the point it is found, since execution isn't directly tied to the loading process (code usually runs after the whole DOM is loaded). In fact, in the case of externals, it doesn't even make sense, since only one copy of the code will be loaded no matter how many times it is encountered.
It shouldn't be the same code for each banner - there will be a parameter passed to whatever is serving the image banner which will specify the intended size.
Can you give a specific example of what you need this for?
To edit for your recent example: The simple answer is no. I could help you approach the problem from a different direction if you post details of your problem
The term "static block of code" leaves a lot of room for interpretation.
Inline scripts (e.g., ones that rely on document.write and so must be parsed and executed during the HTML parsing phase) cannot tell where they are in the DOM at runtime. You have to tell them (as in one of the first answers you got).
I think you'll probably find that you need to change your approach.
A common way to keep code and markup separate (which is useful when providing tools to HTML designers who aren't coders) is to have them use a script tag like so:
<script defer async type='text/javascript' src='pagestuff.js'></script>
...which then triggers itself when the page is loaded (using window.onload if necessary, but there are several techniques for being triggered earlier than that, which you want because window.onload doesn't trigger until the images have all loaded).
That script then looks for markers in the markup and manipulates the page accordingly. For instance (this example uses Prototype, but you can do the same with raw JavaScript, jQuery, Closure, etc.):
document.observe("dom:loaded", initPage);
function initPage() {
var verticals = $$('div.vertical');
/* ...do something with the array of "vertical" divs in `verticals`,
such as: */
var index;
for (index = 0; index < verticals.length; ++index) {
vertical.update("I'm vertical #" + index);
}
}
The designers can then have blocks on the page that are filled in by code which they flag up in a way that's normal for them (classes or attributes, etc.). The code figures out what it should do based on the classes/attributes of the blocks it finds when it runs.

Categories

Resources