Manipulating html page by .js file - javascript

I have successfully called the following JavaScript code to populate an image and description using parameters.
The image and description are in tags and are called imagePlaceHolder and descriptionPlaceHolder. As I say, this works perfectly.
function changeImage(imgName,descriptiveText)
{
image = document.getElementById('imagePlaceHolder');
image.src = imgName;
text = document.getElementById('descriptionPlaceHolder');
PlaceHolder.innerHTML=descriptiveText;
}
What I now require is to place the javascript in its own file and call it from the HTML page using <script src="xxxx.js"></script>
The problem is that the object in the <div> is not recognized. I need to amend the line
document.getElementById('imagePlaceHolder');
to point to the HTML file containing object to manipulate.
Can anyone advise me of the correct syntax please?

In the HTML file you need to link the javascript file in the header
E.g.
<head>
<script src="/scripts/yourjavascript.js" type="text/javascript"></script>
</head>
then do a onload function at the top of your javascript file
window.onload = function(){
changeImage("imgName", "descriptiveText");
}
function changeImage(imgName,descriptiveText)
{
image = document.getElementById('imagePlaceHolder');
image.src = imgName;
text = document.getElementById('descriptionPlaceHolder');
text.innerHTML=descriptiveText;
}
any javascript using document should reference the html document

Related

How to dynamically add scripts to new webpages in javascript?

I'm currently learning javascript without any frameworks. How do you guys redirect to another html file, then assign a script to it dynamically?
So far, what I have done is:
onClick()
{
window.location = newpage.html;
var script = createElement('script');
script.src = dynamic + 'script.js';
var body = document.findbyID('body');
body.appendChild(src);
}
One of the examples of the dynamic script goes like this:
function addText()
{
var text = createElement('p');
text.innerhtml = sometext;
var textHolder = findbyid('div_somewhere_in_html');
body.appendChild(text);
}
The above code doesn't show the text inside the new webpage. The window.location command works. But after dynamically adding a text, it will not show up inside the new webpage. If I would console.log(window.location), it would only show my localhost:3000.
EDIT:
All files are hosted locally.
Since you own the target page, you can load (instead of pushing) a script based on a query string parameter. For example:
newpage.html
<!DOCTYPE html>
<html>
<body>
<script>
const dynamic = new URL(location).searchParams.get('script-prefix');
const script = document.createElement('script');
script.src = dynamic + 'script.js';
document.body.appendChild(script);
</script>
</body>
</html>
anotherpage.html
When clicking the following link, newpage.html will load and execute a script called MyPrefixscript.js.
<html>
<body>
My Link
</body>
</html>
BTW, I used an anchor, but window.location = '/newpage.html?script-prefix=MyPrefix' would work as well.

Grab images from JSON file with NodeJS

I am testing an Electron app. I want it to grab images from this website. That website has a JSON file that has this code.
How can I get those images and put them in an img tag?
So far I have this code:
var request = require('request');
request("http://www.pgbovine.net/photos/json-files/boston.json" , function(error, response, body) {
body = JSON.parse(body);
console.log(body);
function addImg(arr) {
myImg = arr[0]["filename"];
var theImg = document.getElementById("image");
theImg.innerHTML = myImg;
}
And this HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pics</title>
</head>
<body>
<img id="image">
<script type="text/javascript">
require("./memes.js")
</script>
</body>
</html>
The problem is, that code doesn't do anything! So how can I grab an image from the JSON file above and put it into and img tag? (Using NodeJS or vanilla JavaScript)
You are simply adding to the img tag the filename, but you need to add the entire image url not just the filename (like IMG_2914.JPG).
I tried http://www.pgbovine.net/photos/IMG_2914.JPG but got 404 error.
You should be modifying the 'src' attribute of the img html tag to point to the URL or relative path of the image in question.
You would call the 'setAttribute' method on theImgvariable to do this.
Based of the structure of that JSON response, you may also want to set the 'alt' attribtue to the 'description' string of each image object, which would provide a simple mouse-over text.
Note that the JSON that you're talking about here doesn't actually contain the image, just a string that is the filename of the image.
Based on the website you seem to be attempting to scrape, to grab things from the boston image gallery, you would need to append the filename to the following string:
http://www.pgbovine.net/new-galleries/boston/images/
Like so:
<img src="http://www.pgbovine.net/new-galleries/boston/images/IMG_2914.JPG">

How do I load a specific javascript file or javascript code into an HTML document?

Here's what I'm trying to do;
I have this HTML code:
<div id="background-color-random">
DIV CONTENT
</div>
And this javascript:
$(document).ready(function() {
var colors = ["#FFA347", "#FF5050", "#FF66FF", "#6699FF", "#00FF99"],
selectedColor = colors[Math.floor(Math.random()*colors.length)]
header = $("div#background-color-random");
header.css("background-color", selectedColor);
});
I want to impliment this on an HTML page. I know that you can load up a *.js file by using the script tags with src="..". But that doesn't seem to work.
The javascript creates a random color and then applies that to the background of a given 'div' in the HTML.
Now, I'm not good with javascript, so please be patient with me and simple answers are needed :)
I need to be able to get the javascript to load when requested from the HTML and then apply itself to the div with id="..".
You have a syntax error (missing a comma):
selectedColor = colors[Math.floor(Math.random()*colors.length)]
header = $("div#background-color-random");
Should be
selectedColor = colors[Math.floor(Math.random()*colors.length)],
header = $("div#background-color-random");
You are using jQuery, not pure javascript. That's a good thing...
but you also must add the jQuery library in your head tags, like this:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
You also need to put semi-colons (or commas, as RobM has corrected me, if between var assignments) at the end of each instruction. See line 3 in your code example.
If you want your js/jQuery code in a separate file, you can load the script code like this (again, usually done in the <head> tags):
<script src="filename.js" type="text/javascript"></script>
Or, you can include the js/jQ in the <head> tags of your document, like this:
<script type="text/javascript">
$(document).ready(function() {
var colors = ["#FFA347", "#FF5050", "#FF66FF", "#6699FF", "#00FF99"],
selectedColor = colors[Math.floor(Math.random()*colors.length)],
header = $("div#background-color-random");
header.css("background-color", selectedColor);
});
</script>
If including the script as an external file, you leave out the <script></script> wrapper from that file.

the releative path in javascript

I meet some problem when locate the resources such as css js img in the page.
For example,I want to use a javascript lib:dtree,it contain some built-in images and css.
This is its structure:
img
dtree.css
dtree.js
example.html
The exmaple.html is a live demo to show how to use dtree. It use the dtree.js as:
<script type="text/javascript" src="dtree.js"></script>
Now I create a new folder,and copy the example.html here,and modify the src of the js:
<script type="text/javascript" src="../dtree.js"></script>
Now,this is the new structure:
img
dtree.css
dtree.js
example.html
chd
--example.html
When I browser the chd/example.html,some required imgs are missing.
And in the dtree.js,there are some codes like:
this.icon = {
root:'img/base.gif',
....
}
So I think the img here are not based on the dtree.js but the current page which call the js.
If so,I think I am fxxked.
I have to put all my pages to the same directory with the img(it contains the required imgs by dtree.js) if I want to use the dtree.js?
And solutions?
you need to adjust image root path by adding slash before img like:
this.icon = {
root:'/img/base.gif',
....
}

Javascript - Dynamically load a fragment of HTML and run script

I'm building a webpage and I want to re-use some HTML I have elsewhere on my website. The page I am building (index.html) can dynamically get and insert the HTML I want (existing.html) using XMLHttpRequest. However, the HTML I want to get is populated by some Javscript. That Javascript is not being executed when I load it into my new page:
index.html:
<html>
<head>
<script type = "text/javascript">
... //use XMLHttpRequest to load existing.html
initExistingHTML(); //this is function which populates loaded HTML, is not executed
</script>
</head>
<html>
existing.html:
<div>
<script type = "text/javascript">
function initExistingHTML() {
... // do some stuff
}
</script>
</div>
How can I load existing.html and run the script which populates it?
Once the page has loaded, add in existing.html via innerHTML. Rather than calling its functions, just let existing.html's code execute, which will do the same as if it were in the onload section.
EDIT: Or, you could just correct that typo you have. initExistingHTML != initExistingHtml.
lol

Categories

Resources