Can i access html element Id from any from anyfiles? - javascript

I am a beginner to Java-script.
i have a concern
on mainPage.html
<div id="showDialog" style="display:none"> </div>
on mainPage.js
$('#ShowDialog').load("../xxxx.html", function (content) {
xxxxxxxxxxx
});
It is easy understand that if you want to use the id element you just call #element
So, my question is here:
if you are in Setup.js (setup.html has no id attribute like #ShowDialog)
can you still call (So, it will do something on mainPage.html ?? )
$('#ShowDialog').load("../xxxx.html", function (content) {
xxxxxxxxxxx
});
If so, is the class also do the same job? i know id is unique and class is common. So, if one file class can be accessed from other file?
like
$('.ShowDialog').load("../xxxx.html", function (content) {
xxxxxxxxxxx
});
By the way, why we call class using $(.'ShowDialog')rather than just call name like $('ShowDialog')
for class="ShowDialog"

If you want to reference an html Element from an external Javascript file it could be as follows:
myHtml.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- First Import Jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Then the module you wish to work with-->
<script src="./ReferencebyId.js"></script>
<title>referencing html Element by Id</title>
</head>
<body>
<!-- the Id you will reference on the module -->
<p id="myId">Change this text</p>
<button onclick="changeInnerHtml()">Change paragraph text</button>
</body>
</html>
ReferencebyId.js
function changeInnerHtml(){
//This is how you would reference the Id, with '#' character
$("#myId").text("changed from external js file referencing Id");
}
Remember that if you wish to use the class to reference the Html Element, you have to make sure only that element has that class, or if you wish to affect more than one element you can put them the same class, and reference them as $(".nameOfClass")

Could you please explain what is it that you are trying to do?
As I understand from your code, you are trying to load content from an external HTML to other HTML with the load function in JQuery and place it inside the div with id="showDialog"
$('#ShowDialog').load("../xxxx.html", function (content) {...}
Is this what you are trying to do? or are you trying to run some JavaScript from other file?
What do you mean by:
setup.html has no id attribute like #ShowDialog
does setup.html does not have any div with that id?
and by:
can you still call (So, it will do something on mainPage.html ?? )
call what? the loader.
about:
By the way, why we call class using $(.'ShowDialog')rather than just call name like $('ShowDialog')
The preceding dot (.) is because classes on jQuery selectors are specified with a preceding dot (.), and id's with a hash sign (#), think of it, like Css selectors, but in jQuery.
Please explain exactly what are you trying to do so we can help you better :)

Related

6 javascript tasks assigned to me by my lecturer

I am a complete beginner to javascript. I am also new to this website. I am asking for help to complete an assignment. I have been trying for more than 4 hours by looking at lecture material and online for a solution. It is causing me a lot of unnecessary stress. Before javascript we only used CSS and Html. I was given 6 javascript tasks to manipulate the html file (taskc.html) already given to me.
The tasks are as follows
Make a statement to change contents of h1 from "Welcome" to "Text"
2nd statement should make an new alert window when the page loads that delivers a message explaining what the page is about
3rd statement should change the title to "text"
4th statement should log the contents (innerHTML) of the first paragraph element in the console.
5th statement should hide the contents of the second paragraph when the page loads
6th statement should change the contents of the header to have a new colour of your choice
Here is that html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task C - The Document Object Mode</title>
</head>
<body>
<h1 id="header">Welcome</h1>
<p id="first">This site uses JavaScript</p>
<p id="second">Javascript is very useful</p>
</body>
</html>
Because the actual coding im meant to add is meant to be in the .js file I was given. so I figured I had to link the js file in the html file so I added
<script type="text/javascript" src="taskc.js"></script>
With that out of the way I went to the lecture notes and I thought I would simply need to modify some of the code given to me there like
document.getElementById('demo').innerHTML = 'Hello World!';
When I put this code in brackets I got the error (document is not defined)
I modified it to match the requirements for task 1
here it is
document.getElementById('header').innerHTML = 'text';
I was confused because I didn't know what this error meant and of course Errors and how to fix them are never explained so I had to lookup how to resolve the error.
I found that to fix it I have to declare it as a variable so I ended up doing this.
var document = 'taskc.html';
When I did this for document, alert and console all the errors went away, but when I did a live preview only statement 1 was working
If anyone could help me fix this I would really appreciate because I don't understand enough javascript to be able to complete this in a reasonable amount of time.
So first: Please use Javascript functions to keep your code tidy and clean.
Example:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task C - The Document Object Mode</title>
</head>
<body>
<h1 id="header">Welcome</h1>
<p id="first">This site uses JavaScript</p>
<p id="second">Javascript is very useful</p>
<script type="text/javascript" src="taskc.js">test();</script>
</body>
</html>
function test(){
alert("This is a test!");
}
Always implement scripts that are document referenced at the bottom of your html.
If you use JQuery you can use following code to check document is loaded:
$(document).ready(function(){
//foo bar
});

HTML equivalent of PHP include for JavaScript parts

I'm looking for a Javascript equivalent of a technique I've been using in PHP. That is, to place even the most basic page setup:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
...in a php file like 'doc_start.php' and then start every page in my site with...
<?php require_once('/path/to/doc_start.php); ?>
Now I need to begin a project that's strictly HTML and JS (no PHP) and want a similar way to avoid duplicating basic, common HTML elements. Obviously, I want to do more than this very basic stuff, like import JQuery in every page, link to a common stylesheet, etc. Again, all easy in PHP, but I'm still kind of a newbie in JS.
I've read about HTML5 includes, but can't seem to find anything that addresses what I want to do
In order to import other pages into your current document, you need to use a link tag.
For example....
<head>
<link rel="import" href="/path/to/imports/stuff.html">
</head>
This will allow you to reference other html, css or javascript documents into your page without copying and pasting the same code within each page.
https://www.w3schools.com/html/html_links.asp
Javascript and PHP are different languages for very different purposes. But assuming you have some element you don't want to repeat some elements one solution is the following:
Save the HTML elements that you don't want to keep repeating as a string. Then use the .innerHTML property to add elements.
The .innerHTML property stores the mark up of an element as a string.
For example, if we have the following <div>:
<div class="example"> <br> Hello there this is a test! </div>
...and we use .innerHTML:
console.log(document.querySelector(".example").innerHTML);
It will output "<br> Hello there this is a test!".
We can add to the .innerHTML using the += operator. So if you want to add something inside the body it's as simple as:
var something = "some HTML";
document.body.innerHTML += something;
Hope this was what you were looking for!

Place of ng-app in html tags [duplicate]

This question already has answers here:
Placement of the ng-app directive (html vs body)
(3 answers)
Closed 7 years ago.
I'm new to AngularJS. My lecturer said ng-app can use in html, body, div tags etc. My question is, if ng-app can use in html tag and body tag, is there a any use if i use it in html tag rather than body tag?
What I mean is, the head tag is middle of body and html. Is there any effect cause in head tags when I use it html tag or not. hope my question is clear.
The reason that you would place the ng-app inside the html tag over the body tag is because you want to manipulate something inside of the head and body using angularjs. Here is an example:
<html ng-app="MyApp">
<head>
<meta charset="utf-8">
<title ng-bind="'Title - ' + title"></title>
<link rel="stylesheet" href="/css/style.css" />
</head>
<body>
...
Notice in the title I have a ng-bind, this way i can use the variable name title to change the title of the web page the user is on. The title will always be Title - what ever link their on In the app.js I make the title var a global variable. This is just one reason to put ng-app in the html tag instead of body.
No. ng-app has no effect on <head> unless you intend to. It should be added to the element which is the scope of your app, the root element html.
Most of the time it is better to use it on body tag unless you want to change something in head e.g. title. For dynamic value of title, ng-app should be added to the <html>.
yes there are some benefits if you put ng-app in the <html> tag,
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>
if u put it in html then you can control all the things between html tag, that mean all html can be manipulate using angularjs, for EX you can change the title.
But if you put it in <body> then you loose the control of the <title> or something inside the <head> tags and you can control the inside the <body> tag only.
here is the DOC for NG-APP
Use this directive to auto-bootstrap an AngularJS application. The ngApp directive designates the root element of the application and is typically placed near the root element of the page - e.g. on the <body> or <html> tags.

Javascript Function Not Being Called after dynamic loading

I have a weird issue that i am hoping someone can help resolve.
Problem
When i load html dynamically via .load() function, if any aspect of html in the loaded fragment tries to access the javascript query functions in original HTML page, it doesn't work. Example code below:
Main HTML page (main.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<!--javascript load functions etc... standard header stuff -->
</head>
<body>
<div id="dynamic_section_fragment"></div>
Load Fragment
<script type="text/javascript">
// <![CDATA[
function loadFragment() {
$("#dynamic_section_fragment").load("/api/fragment/");
};
$(".checkvalue").click(function () {
$.getJSON("/api/checkvalue", {term: $(this).attr('value')}, function () {
console.info("submitted for checking");
})
});
// ]]>
</script>
</body>
</html>
FRAGMENT File (fragment.html)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
</head>
<body>
<div th:fragment="check_value">
<br/>
Check the value in the attribute field
<br/>
<a href="javascript:" th:attr="value='123'" class="checkvalue">Check This<a/>
</div>
</body>
</html>
SPRING MVC Controller Method
#RequestMapping("/api/checkvalue")
public String getFragment(Model model) {
return "fragment :: check_value";
}
So a run down of actions:
-Main.html page loads
-User clicks on Load Fragment hyperlink
-Javascript dynamically loads the relevant fragment into the div
-User clicks on Check This hyperlink, nothing happens
Is there something i am missing or something i need to be aware?
It is as if Thymeleaf has preregistered all the possible scenarios of events and doesn't allow any others.
Only way i have been able to get it to work is by injecting the "checkvalue" javascript within the fragment, which as you can agree is a bad way of doing things.
Help is appreciated.
You are applying the click event listener to all existing objects with the checkvalue class.
$(".checkvalue").click(function ()
What you rather wish to do (to make the click event apply to all the existing and any new added, dynamically) is to set a event on a parent in the dom tree (parent both to the existing and to all that will be added).
In your case, the body tag would probably be the safe bet.
The following should suffice:
$('body').on('click', '.checkvalue', function() { ...
Simplified, the code will apply a listener on the body element instead of the .checkvalue objects, and whenever a object with the .checkvalue class is clicked (wether dynamically or statically loaded), the event will fire.
edit
I would also suggest that you, in your javascript, don't use jquery before you know for certain that it is loaded.
The jquery lib have a way of fixing this for you, by using the $( document ).ready() function:
$( document ).ready(function() {
// All jquery dependant code here.
});

Jscript not printing to element

I have no idea why this isn't working. I mean as far as I know It should print my array in alphabetical order to the div "output"
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title> Lexicographic ordering </title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var words = [];
var input = prompt("Please enter a word or type end to stop prompts");
while (input != 'end') {
words.push(input);
input = prompt("Please enter a word or type end to stop prompts");
}
words.sort();
getElementById('#output').innerHTML= words.join();
</script>
</head>
<body>
<header>Lexicographic Ordering </header>
<hr>
<div class ="page-wrapper">
h1> Lexicographic Ordering </h1>
<div id="output"></div>
</div>
</body>
</html>
There are two small bugs in your code, and they're both in this line:
getElementById('#output').innerHTML= words.join();
getElementById is not a part of the window, it's a part of the document object, so you must reference it properly. Also, that method takes an ID, not a selector, so you don't need the # in front of it.
document.getElementById('output').innerHTML= words.join();
That should do what you want! Alternatively, since I notice you have jQuery included, you could do $('#output').innerHTML = ... to achieve the same effects.
You may also try to move the <script> block at the end, just before closing of the </body>. Anywhere after the <div id="output"></div>.
JavaScript on some browsers fails when they have to reference some elements which has not been parsed by their HTML parser when the script is executing or trying to reference them.
Also, you don't use # with getElementById(...);. # is used with Jquery. This is pure JavaScript. Make it getElementById('output').whatever...;
Edit:
Another option suggested by Patrick Evans is to move the JavaScript Code in an onload() event handler method to execute the code. This ensures that the HTML is fully loaded in the DOM before we try to manipulate it.

Categories