After finding that the hidden attribute only works with html5 and latest browsers I might have found another way to hide content based on conditional statements.
I ran into a problem where the function in javascript does not seem to executed, in short it does not hide the first paragraph.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function DetachEmptyField(pattern) {
$("#pattern").val(pattern);
$(pattern).detach();
}
});
</script>
</head>
<body>
<p id="hideMe">This is a paragraph, 1.</p>
<p>This is another paragraph, 2.</p>
<button>Remove paragraph 1</button>
#* Razor conditional statements to be added later here ... *#
<script type="text/javascript">DetachEmptyField("#hideMe");</script>
</body>
</html>
The DetachEmptyField function is not available in the global scope (it lives inside your ready callback) and therefore your call will not work. If you really want to call it like this
<script type="text/javascript">DetachEmptyField("#hideMe");</script>
you will have to declare it in the global scope (be aware that this is a bad practice)
// global function
function DetachEmptyField(pattern) {
$("#pattern").val(pattern);
$(pattern).detach();
}
$(document).ready(function(){
});
Anyway, if you just need to hide the element you can use css "display: none" or if you can check on the server side whether or not the element should be present on the page you can simply not include that paragraph in the response.
#if ( /*some condition that needs to be true in order to display the <p> */ ) {
#: <p id="hideMe">This is a paragraph, 1.</p>
}
Related
from the html below I would like to execute a script by calling his id. So that when the script id is called the display fonction execute. Any other suggestion will be appreciate as long that the script only execute when the id is called. Thank you
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
//Here is where I would like to execute the script by calling his id.
//Any other suggestion to make it work will be appreciate
});
</script>
<script type="text/javascript" id="execute">
$(document).ready(function(){
display();
});
</script>
<!--------------------- Footer -------------------------------->
<script>
function display(){
$("#show").css("display", "block");
}
</script>
<p id="show" style="display:none">This is a paragraph with little content.</p>
</body>
</html>
That's not how JavaScript works.
Once you include a <script> in DOM, it's executed. However, the script itself can define functions, which could be named and called at a later point (by their name), by any other script or element in the page, as long as they have access to the context in which you defined your function.
Example:
<script>
function myFunction() {
window.alert('I got called!');
}
</script>
<button onclick="myFunction()">Execute myFunction()</button>
So instead of using the id of the script, I'm using the name of the function.
To fully answer your question: running a script by id is not possible because all scripts are executed as soon as they are parsed by the browser (which happens in their chronological order in DOM) and there is no way of re-running them after they have already been executed.
Obviously, one could argue that you could remove the <script> tag altogether, create a new one with the same contents, which is going to be rerun when added to DOM. But, at least in theory, it's not rerunning the same <script>, it's running a different one. Another instance/<script> tag.
Needless to say, nobody does that as it's much more convoluted than to simply define a function and call that function at a later time.
Thank you for your explanation on the DOM. It help me figure out another alternative
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
var result = window.prompt("Would you like the footer to be display?");
if(result == "yes"){
bodyPage1();
}
});
</script>
<script>
function bodyPage1(){
display();
}
</script>
<!--------------------- Footer -------------------------------->
<script>
function display(){
$("#show").css("display", "block");
}
</script>
<p id="show" style="display:none">This is a paragraph with little content.</p>
</body>
</html>
I was embedding html in a website (template based) and I wanted to manipulate the html outside of my user-defined html. The way it basically works on the site is:
<html>
<head></head>
<body>
<p>Hello World!</p>
</body>
<html>
<script>
document.getElementsByTagName("p").innerHTML = "Greetings World!";
</script>
</html>
</html>
However, this will only look for "p" elements within the inside html scope. My question is, is there a way to retrieve DOM elements from the inner html scope to the outer html scope? Here's the code I'm working with:
<!-- Website HTML -->
<html>
<textarea id="np-text">Hello World!</textarea>
<!-- Custom HTML -->
<html>
<body>
<button onclick="myFunction()">Change Value</button>
<script>
function myFunction() {
document.getElementById("np-text").innerHTML += '<span class="hover"><span></span></span>';
}
</script>
</body>
</html>
</html>
The main problem is that I cannot change the outer HTML scope in any way; the only html I can define is not in the same scope of what I want to change.
You can't "change the outer HTML scope in any way", because there is not supposed to be one. The HTML you have included in your question is completely wrong in every way imaginable and will make any HTML validator facepalm.
The only valid way to have an "inner HTML tree" inside an existent HTML document is through the use of an iframe or object. In the case of an iframe, in order to be able to access the content of the outer tree, both the content of the parent window and the one of the iframe are required to originate from the same domain.
If all of the above is in place, you can access the document of the parent window and subsequently the textarea using the following code:
parent.document.getElementByID("np-text");
In addition, you also have an error in your JavaScript code, where you use:
document.getElementsByTagName("p").innerHTML = "Greetings World!";
The getElementsByTagName method returns an HTMLCollection, instead of a single HTMLElement, which doesn't have the innerHTML method. In order to change the innerHTML of a collection of elements, you can use the following code:
/* Fetch all 'p' elements. */
var pCollection = document.getElementsByTagName("p");
/* Iterate over every element in the collection and change its content. */
[].forEach.call(pCollection, (element) => element.innerHTML = "Greetings World!");
// Your original code:
// document.getElementsByTagName("p").innerHTML = "Greetings World!";
// New code:
document.getElementsByTagName("p")[0].innerHTML = "Greetings World!";
<html>
<head></head>
<body>
<p>Hello World!</p>
</body>
</html>
I notice you use getElementsByTagName("p"), as a short notice you'll see the s after getElements, with this s it meant it'll be an HTMLCollection since you might have many p element in your HTML, [0] meant the first <p> element in this HTML page.
For a better code you should do something like this:
document.getElementById("greeting").innerHTML = "Greetings World!";
<html>
<head></head>
<body>
<p id="greeting">Hello World!</p>
</body>
</html>
<html>
You can use id="" function to have a safer code since you said it's in template which you might not sure of its position, while id in the HTML must be unique, it's proving that you'll find the element/place you want to change and also having a better code.
I'm trying to use a same HTML block in several places and pages, while keeping in low number of lines of code and a low redundancy.
Basically, I need something that is similar to a function that when it's called, it will just load a HTML code into the page - this will be done on page load, so no click or other actions that needs to trigger it.
I don't want to use PHP include.
Example:
<div class="x">
<div class="y">
<div class="z"></div>
</div>
</div>
I'll need to use the same class X into 100+ pages and it will have the same content.
What's the best method to insert just the X class and the inside content to be added automatically?
You could put your code in a different .html file and load it with .load() http://api.jquery.com/load/
$('#targetid').load('somewhere/a.html'); // loads the .html in the #targetid
main.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Main page</title>
<sript src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$('#commonsection').load('reusablefile.htm');
// which is eqvivalent to:
//
// $.ajax({
// url: 'reusablefile.htm',
// dataType: 'html',
// success: function(data){
// $('#commonsection').html(data);
// }
// });
});
</script>
</head>
<body>
<div id="commonsection"></div>
</body>
</html>
reusablefile.html:
<script>
(function($){ //separate scope to keep everything "private" for each module
//do additional javascript if required
})(jQuery);
</script>
<p>...Some non-trivial content...</p>
If you have any javascript frameworks in use they usually have an option as well.
AngularJS uses directives to handle repetitive html code.
https://docs.angularjs.org/guide/directive
Also possibly repeat question of:
How to reuse the html code in every html page?
Try this if you don't mind use the dirty way. :)
$(".reuseTarget").html($(".x").text());
$(".reuseTarget").html($(".x").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="x">
<div class="y">
<div class="z">aabb</div>
</div>
</div>
<div class="reuseTarget">
</div>
When i keep my javascript/jquery external, my code doesn't work. but when i combine them in my html file everything is fine.
any suggestions as to why this is?
here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type ="text/javascript" src="jquery.js"></script>
<script type ="text/javascript" src="program.js"></script>
</head>
<body>
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
</body>
</html>
with external javascript
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
VERSUS
<!DOCTYPE html>
<html>
<head>
<script type ="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
</script>
</body>
</html>
I guess you execute the click event before the DOM finishes loading. Wrap your code inside the dom ready event and it should work, Assuming your path to the external javascript file is correct.
$(function(){
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
});
Always use firebug (console) to see what is wrong with the script, if you run into any script errors.
Your javascript is executed before there are elements on the page. You can get around this by using $(document).ready(function(){...}); or moving your external javascript files to the bottom.
Wrap your js code in external file in
$(document).ready(function(){
//your code goes here
});
Right now you are including external js file in header and it is executed. At this point there is no elements so $('#clickme') and $("p") are empty set. In the second example you run this code after rendering html with that elements.
The reason that there is a difference, is that in the external file your code is executing before the browser has fully parsed the DOM so you are attempting to programatically access elements of the page which the browser is not yet aware of. This is exactly what most people have already said, but let me elaborate a bit further...
Whilst a lot of people have mentioned using jQuery's document ready handler, I would like to point out that a workable solution is simply to move your script tags to the bottom of the page.
Not only will this solve your problem in itself, but it will also improve page load times because of how browsers treat scripts. When the browser encounters a script it stops everything else it is doing (known as a "blocking" operation), and parses and executes the script. This causes the page to just appear to stall from a user's perspective, meaning a bad user experience. Thus, because the scripts are parsed and executed only as they are encountered, by moving your scripts to the bottom you allow the browser to fully render the page so that the JavaScript does not block rendering.
Though rather than just moving scripts to the bottom of the page, I'd also follow what the others recommended and wrap the whole code in the document ready handler just to be extra safe that your code will always be executed at the correct time.
Also, in the debate of inline or external, external scripts are generally preferred as they are easier to maintain and the browser can cache them independently of the page (providing the correct HTTP headers are present).
To sum up here's some example code:
<html>
<head></head>
<body>
<!-- all your markup here -->
<!-- script at bottom, markup already rendered by this point -->
<script type="text/javascript" src="jquery.js"></script>
<!-- inline or external, still wrap in document ready handler -->
<!-- though external is better because the browser can cache it independently of the page -->
<script type="text/javascript">
//wrap in document ready to be extra safe
$(function() { /*code here*/ });
</script>
</html>
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.