Open image using Java Script and call the function in html - javascript

I have two separate files one with my html code and with my javaScript. What I am trying to do is create a function in javascript then call that function in the html. Both files are in the same folder along with the image. I'm new to both languages and to this site so please go easy;
I would really appreciate it if someone could help me please.`
JavaScript to load image below:
var menu = new image();
menu.src = "Fitness App Entry Scrren.jpg"
function menuScreen(){
document.getElementById("menu").getAttribute("src");
}
Html code to call function:
<!DOCTYPE html>
<html>
<head>
<body src="Functions.js">
<script onload="menuScreen()"></script>
</body>
<head>
</html>

What you are doing is against the rules of HTML. First of all, <body></body> should be outside of <head></head>. You should have <script></script> in either <head></head> or <body></body>. The <body> tag should have the onload attribute set to menuScreen(), and the <script> tag's src attribute should be set to Functions.js (as John Hascall said). By the way, John Hascall is right, there is no element with the ID of "menu" so it won't work unless you create a <div> or <iframe> with the specific ID and append the image to it in your Functions.js file.
So, your JavaScript code should look like this:
var menu = new Image(); // note that the constructor is capitalized
menu.src = "Fitness App Entry Screen.jpg";
// Create a <div> with the image within it.
var division = document.createElement("div");
division.setAttribute("id", "menu");
division.appendChild(menu);
document.body.appendChild(division);
function menuScreen() {
division.getAttribute("src"); // you can use division because it has the id of menu
}
And here is your HTML code to run the page (according to the HTML5 specifications, note that):
<!DOCTYPE html>
<html>
<head>
<script src="Functions.js"></script>
</head>
<body onload="menuScreen()">
<!-- Left intentionally blank -->
</body>
</html>
Hopefully this will help you!

Related

How to include a html file inside another html file with Vanilla Javascript?

I want to create a single page web application with pure Vanilla Js, not React Js or another. What I want is when I click on a menu link, I want it to include another html file and show up the result without reloading. I did it with include(), get(), load() in jQuery. But I want to do it with pure vanilla Js, if possible, even though with some tricks.
Here is the one of the things I did with jQuery:
$('.link-about').click(function(){
$('.my-div').load('about-page.html');
});
As shown above, how it should work is that I click a link and another html file loads.
Try this
<!DOCTYPE html>
<html>
<head lang="en" dir="ltr">
<script type="text/javascript">
async function load_home()
{
var content = document.getElementById("content");
content.innerHTML = await (await fetch('next.html')).text();
}
</script>
</head>
<body>
<div id="content"></div>
<button onclick="load_home()"> load</button>
</body>
</html>
You can try this. I am considering elements has id
<script>
document.getElementById('link-about').onclick = function() {
document.getElementById('my-div').innerHTML = '<object data="about.html" >'
}
</script>

How do I make the querySelector look in a specific included document only?

On my index page I have a number of includes.
<section><?php include('content/content1.php') ?></section>
<section><?php include('content/content2.php') ?></section>
<section><?php include('content/content3.php') ?></section>
In each of them I have a unique script (and some other things which is not shown here).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Content1</title>
<link rel="stylesheet" href="content/sketch.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.10/p5.js"></script>
</head>
<body>
<div class="frame">
<canvas></canvas>
</div>
<script src="content/content1.js"></script>
</body>
The <canvas> tag is what the querySelector in the javascript calls to.
var canvas = document.querySelector('canvas');
This works, but only for the first content file. It seems the querySelector looks at the whole loaded page, instead of just inside the body of the document where the script is placed. Google console says: "Indentifier 'canvas' has already been declared".
I have tried setting an id on the canvas-element:
<canvas id="canvas1"></canvas>
var canvas = document.querySelector('#canvas1');
But it's not working. How do I get around this?
You can use document.currentScript to get the tag of the currently running script tag. From there, you can navigate to its containing section, and from there, get to the canvas descendant.
You should also put everything into an IIFE to avoid global variable collisions.
(() => {
const canvas = document.currentScript.closest('section').querySelector('canvas');
// ...
})();

HTML and JavaScript in separate files - newbie alert

OK. I feel dumb! I've been trying to do something very simple and yet finding it very difficult to do or to find. All I want to do is:
have the index.html file display.
I want a separate JavaScript file that contains all of my JavaScript code. Completely separated, so I don't have any JavaScript code in my HTML file. I don't want a click event or anything fancy.
I just want the page to display Hello World! onLoad by getting it from a JavaScript function.
BTW: Seems all tutorials either put the JavaScript code in with the HTML or they want to show you how to do something fancy. I've been all over SO to no avail.
The closest I've gotten is listed below. I give up! A little help would be so appreciated.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js"></script>
</head>
<body>
<script type="text/javascript"></script>
</body>
</html>
script.js:
window.onload = function() {
var result="Hello World!";
return result;
};
if you want to append to body, you can create a text node ( createTextNode() ) and then directly append that to body:
window.onload = function() {
var result = document.createTextNode("Hello World!");
document.querySelector('body').appendChild(result);
};
What you can do is print the text you want to the <body> element when the page loads. Something like this should do the trick:
window.onload = function() {
var result="Hello World!";
document.querySelector('body').innerHTML(result);
};
Or if you had a particular place on your webpage that you wanted to load this text into, you can create an element in your HTML, give it a unique id and reference it in your JavaScript:
<body>
...
<div id="myAwesomeElement"></div>
...
</body>
and in the JavaScript:
window.onload = function() {
var result="Hello World!";
document.querySelector('#myAwesomeElement').innerHTML(result);
};
In your javascript function, you can do something like this:
document.getElementById("divID").innerHTML="Hello World!";
and in your html file create a div or span or something that you want modify(in this case, the inner html content):
<body>
<div id="divID"></div>
</body>
When the function is called, it will find the dom element with the Id of "divID", and the innerHTML will be what you assign the Hello World to. You could modify other properties like css style stuff too.
If you want to grab a hold of a place where to put your file, you need to address it.
Eg.
<body>
<div id="place-for-text"></div>
</body>
And then in your script:
var elem = document.getElementById('place-for-text');
elem.innerHTML = 'Hello world.';
That is about the simplest way to do it in a way you could control some of it.
You could go more fancy and add a DOM element instead:
var elem = document.getElementById('place-for-text');
var text = document.createTextNode('Hello world');
elem.appendChild(text);
Here's a way that hasn't been shown yet.
You can remove the script tag from the head of the file since we want the js file to load up after the rest of the page. Add the script tag with the script.js source to the body.
//index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
The script.js file looks like this:
//script. js file
!function () { document.querySelector("body").innerHTML = "hello world"; } ();
The exclamation point and the following () causes the function to run automatically upon load. For more info take a look at this question: What does the exclamation mark do before the function?
EDIT
I should also point out that document.write and .innerHTML are not considered best practice. The simplest reasons are that document.write will rewrite the page and .innerHTML causes the DOM to be parsed again(performance takes a hit) - obviously with this example it doesn't really matter since it's a simple hello world page.
An alternative to document.write and .innerHTML
!function () {
var text = document.createTextNode("Hello World");
document.querySelector("body").appendChild(text);
} ();
It's a bit of a pain, but you can write a function for the process and it's no big deal! The good news is that, with the new ecmascript 6(new JavaScript) you can turn this into a quickly written arrow function like the following:
//script.js
! function() {
var addTextNode = (ele, text) => { //create function addTextNode with 2 arguments
document.querySelector(`${ele}`).appendChild(document.createTextNode(`${text}`));
// ^ Tell the function to add a text node to the specified dom element.
}
addTextNode("body", "Hello World");
}();
Here's a JS Fiddle that also shows you how to append to other elements using the same function.
Hope this helps!
There are multiple ways to ways to solve your problem. The first way only changes your javascript. It uses the document.write() function to write the text to the document.
Here is the new javascript:
window.onload = function() {
document.write("Hello World!");
};
The second way also only changes your javascript. It uses the document.createElement() function to create a p tag and then changes the content inside it then appends it to the body.
Here is the new javascript:
window.onload = function() {
var p=document.createElement("p");
p.innerHTML="Hello World!";
document.body.appendChild(p);
};
window.onload = function() {
document.write('Hello World')
};
Returning from window.onload doesn't do anything productive. You need to call methods on the document to manipulate the page.

Is it possible to retrieve the *full* HTML page source of an iframe with Javascript?

I am trying to figure out how to retrieve the full (that means all data) HTML page source from an <iframe> whose src is from the same originating domain as the page that it is embedded on. I want the exact source code at any given time, which could be dynamic due to Javascript or php generating the <iframe> html output. This means AJAX calls like $.get() will not work for me as the page could have been modified via Javascript or generated uniquely based on the request time or mt_rand() in php. I have not been able to retrieve the exact <!DOCTYPE> declaration from my <iframe>.
I have been experimenting around and searching through Stack Overflow and have not found a solution that retrieves all of the page source including the <!DOCTYPE> declaration.
One of the answers in How do I get the entire page's HTML with jQuery? suggests that in order to retrieve the <!DOCTYPE> information, you need to construct this declaration manually, by retrieving the <iframe>'s document.doctype property and then adding all of the attributes to the <!DOCTYPE> declaration yourself. Is this really the only way to retrieve this information from the <iframe>'s HTML page source?
Here are some notable Stack Overflow posts that I have looked through and that this is not a duplicate of:
Javascript: Get current page CURRENT source
Get selected element's outer HTML
https://stackoverflow.com/questions/4612143/how-to-get-page-source-using-jquery
How do I get the entire page's HTML with jQuery?
Jquery: get all html source of a page but excluding some #ids
jQuery: Get HTML including the selector?
Here is some of my local test code that illustrates my best attempt so far, which only retrieves the data within and including the <iframe>'s <html> tag:
main.html
<html>
<head>
<title>Testing with iframe</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function test() {
var doc = document.getElementById('iframe-source').contentWindow.document;
var html = $('html', doc).clone().wrap('<p>').parent().html();
$('#output').val(html);
}
</script>
</head>
<body>
<textarea id="output"></textarea>
<iframe id="iframe-source" src="iframe.html" onload="javascript:test()"></iframe>
</body>
</html>
iframe.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html class="html-tag-class">
<head class="head-tag-class">
<title>iframe Testing</title>
</head>
<body class="body-tag-class">
<h2>Testing header tag</h2>
<p>This is <strong>very</strong> exciting</p>
</body>
</html>
And here is a screenshot of these files run together in Google Chrome version 27.0.1453.110 m:
Summary
As you can see, Google Chrome's Inspect element shows that within the <iframe> the <!DOCTYPE> declaration is present, so how can I retrieve this data with the page source? This question also applies to any other declarations or other tags that are not contained within the <html> tags.
Any help or advice on retrieving this full page source code via Javascript would be greatly appreciated.
Here is a way to build it from the doctype, seems to work for html 4 and 5, I didn't test for stuff like svg.
<html>
<head>
<title>Testing with iframe</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function test() {
var d = document.getElementById('iframe-source').contentWindow.document;
var t = d.docType;
$('#output').val(
"<!DOCTYPE "+t.name+
(t.publicId? (" PUBLIC "+JSON.stringify(t.publicId)+" ") : "")+
(t.systemId? JSON.stringify(t.systemId) :"")+
">\n" + d.documentElement.outerHTML );
}
</script>
</head>
<body>
<textarea id="output"></textarea>
<iframe id="iframe-source" src="iframe.html" onload="test()"></iframe>
</body>
</html>
this also uses HTML.outerHTML to make sure you get any attribs on the documentElement.

How to replace Current script tag with HTML contents generated by the same script

I want to replace the current script tag with the HTML contents generated by the same script.
That is, my Page is
<html>
<body>
<div>
<script src="myfile1.js"></script>
</div>
<div>
<script src="myfile1.js"></script>
</div>
</body>
</html>
Inside each .js file corresponding html contents are generated. I want to put the contents as the innerHTML of the parent div. But can't set id for the parent div because the page is not static. So the current script tag must be replaced with the HTML content. How can I do this?
For each script tag src is the same. So can't identify with src. These scripts displays
some images with text randomly. Scripts are the same but displays different contents in divs on loading
Please help me
try inside of myfile1.js:
var scripts = document.getElementsByTagName( "script" );
for ( var i = 0; i < scripts.length; ++ i )
{
if ( scripts[i].src == "myfile1.js" )
{
scripts[i].parentNode.innerHTML = "new content";
}
}
This is a great question for those trying to implement a JSONP widget. The objective is to give the user the shortest possible amount of code.
The user prefers:
<script type="text/javscript" src="widget.js"></script>
Over:
<script type="text/javscript" src="widget.js"></script>
<div id="widget"></div>
Here's an example of how to achieve the first snippet:
TOP OF DOCUMENT<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
// inside of widget.js
document.write('<div id="widget"></div>');
$(document).ready(function() {
$.getJSON('http://test.com?remote_call=1', function(data) {
$('#widget').html(data);
});
});
<br />BOTTOM OF DOCUMENT
Have a look at: http://alexmarandon.com/articles/web_widget_jquery/ for the correct way to include a library inside of a script.
document.currentScript has been available since 2011 on Firefox and 2013 on Chrome.
document.currentScript documentation at MDN
<!DOCTYPE html>
<meta charset="UTF-8">
<title>currentScript test</title>
<h1>Test Begin</h1>
<script>
document.currentScript.outerHTML = "blah blah";
</script>
<h1>Test End</h1>
Unfortunately a running JavaScript file is not aware of where it is running. If you use document.write() in the script, the write function will take place wherever the script runs, which would be one way to accomplish what you want, but without replacing the contents or being able to perform any actions on the enclosing DIV.
I can't really envisage a situation where you'd have such stringent restrictions on building a page - surely if the page is dynamic you could generate identifiers for your DIV elements, or load content in a more traditional manner?
Why not use Smarty?
http://www.smarty.net/
You can use javascript in Smarty templates, or just use built-in functions.
Just take a look at http://www.smarty.net/crash_course
poof -- old answer gone.
Based on your last edit, here's what you want to do:
<html>
<head>
<!-- I recommend getting this from Google Ajax Libraries
You don't need this, but it makes my answer way shorter -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function getRandomContent(){
// I expect this is the contents of your current script file.
// just package it into a function.
var rnd = Math.random();
return "[SomeHtml]";
}
$('.random').each(idx, el){
$(this).html(getRandomHtmlContent());
});
});
</script>
</head>
<body>
<div class="random">
</div>
<div class="random">
</div>
</body>
</html>
If you don't mind the script tag remaining in place you can use something as simple as document.write().
myfile1.js:
document.write("<p>some html generated inline by script</p>");
It will do exactly what you need.

Categories