I am an intermediate HTML and I am starting to learn JavaScript within it.
<html>
<head>
<title>Uh oh! No page.</title>
<h1 class="index">The page you requested for is not available! Click here to go back</h1>
<style>
.index {
text-decoration: none;
font-family: Arial;
}
</style>
</head>
<body onload="myfunc()">
<script>
function myfunc() {
var x;
if (confirm("Im confuzzled! Where did the page go?\n\nSelect OK to be redirected and Cancel to do it manually ") == true) {
window.location = "index.html";
} else {
alert("You will now manually have to redirect to the lemoon homepage");
}
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
<footer onload="pageLocate()">
<script>
function pageLocate() {
document.getElementById("demo").innerHTML =
"Page location is: " + window.location.href;
}
</script>
</footer>
</html>
I cannot get the document tag to display anything. Can you please help?
i have scanned your code twice and still can't see where is the tag that has id = "demo". If you don't create a tag with an id, which is in this case : "demo", then when you call for it, how can console even work when it can't find the target ? i believe that this is your fault
There is no element with the ID of "demo". You would need to give the element that you want to perform a function with an id of "demo" for this to work.
EX:
<div id="demo">Hello!</div>
You did not have to ask this question, it just would have taken a little bit of thinking or some searching on google.
I really hope you wanted something like this, as there were some not so logical things there.
1.footer and h1 tags belong to the body of the page (inside tag).
2.you pretty much created a function to get some data for another function, that can be accessed from the other function
<html>
<head>
<title>Uh oh! No page.</title>
<style>
.index {
text-decoration: none;
font-family: Arial;
}
</style>
<script>
function myfunc() {
if (confirm("Im confuzzled! Where did the page go?\n\nSelect OK to be redirected and Cancel to do it manually ") == true) {
window.location = "index.html";
} else {
alert("You will now manually have to redirect to the lemoon homepage");
}
document.getElementById("demo").innerHTML = "Page location is: " + window.location.href;
}
</script>
</head>
<body onload="myfunc()">
<h1 class="index">The page you requested for is not available! Click here to go back</h1>
<footer id="demo" onload="pageLocate()">
</footer>
</body>
</html>
Related
A fellow noob here. I was wondering how can I make this button print something when pressed, I tried the document.write() but it prints it on a new clear page, I want it to be just like the image I attached.
Any ideas :D
<button onclick = "myVidPlayer.requestPictureInPicture()" " Id="togglePipButton"
>START</button>
If you are refering to print as write to DOM element or console use below code:
const someData = 'the_Data_You_Want_To_Print'
document.getElementById('printButton').onclick = function() {
//print in DOM element
document.getElementById('printHere').innerHTML = someData;
//print on console
console.log(someData)
};
#printHere {
position: absolute;
top: 15%;
left: 6%;
font-size: 5vw;
}
<button id="printButton">Click Me To Print</button>
<p id="printHere"></p>
You could use an alert window.
alert("Hello! I am an alert box!!");
or something like this:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Alert</h2>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
So basically I was trying to make an error message that is hidden by default be displayed when the user inputs incorrect information. However, the message wasn't appearing. So I used the debugger and found out that the error node element at the top of the js. code was successfully finding the element in the HTML and also successfully changing it's properties. And yet nothing was happening. So after a bit of research I found out that there is a property called isConnected which shows if the Node is connected to the Document. Turns out mine was connected(true) immediately after finding the element, but it was disconnected(false) by the time it entered the errorHandler() func. So again after a bit of debugging I found out that the bottom line of the onPageLoad func was causing the problem. It used to be rootUl.innerHTML += template(countriesObj); but that was breaking it. However, when I moved my error element in the HTML from the ul to outside the id="root" div, it was working fine. It was only breaking when the element was inside the ul. At the end of the day I fixed it by using Element.insertAdjacentHTML() instead, which wouldnt sever the connection between the error element and Document. So after about an hour of struggle, I am curious why that happens and what the difference is between rootUl.innerHTML += template(countriesObj); and rootUl.insertAdjacentHTML('beforeend', template(countriesObj));
Just to add, rootUl.innerHTML+=template(countriesObj) breaks the connection even when used by other function which are not shown here.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>List Towns</title>
<script src="../handlebars.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p style="text-align: center; font-size: 18px; font-weight: 700; font-family: Arial, Helvetica, sans-serif;">
Input in the following format: "{Country}: {town}, {town} {Country}: {town}, {town}" and so on. Matching is case-insensitive. Non-english characters are not supported. Numbers are not supported. Check regex for more info. Reset button deletes entire database and refreshes page.
</p>
<form action="#" class="content">
<label for="towns">Towns</label>
<input id="towns" type="text" placeholder="ex. Bulgaria: Burgas, Varna Turkey: Ankara"/>
<button id="btnLoadTowns">Load</button>
</form>
<div id="root">
<ul>
<!--When the element was here, innerHTML wasn't working correctly-->
<h4 id="error" style="color: rgb(136, 9, 0); display: none;" >Error. Input string not in correct format. Look at instructions above.</h4>
</ul>
</div>
<!--When the element was here, innerHTML was working fine-->
<!-- <h4 id="error" style="color: rgb(136, 9, 0); display: none;" >Error. Input string not in correct format. Look at instructions above.</h4> -->
<button id="reset">Reset</button>
<h4 id="empty-database" style="color: rgb(136, 9, 0); display: none;" >Database is currently empty.</h4>
</body>
<script src="./app.js"></script>
</html>
async function pageApp(){
//Misc
let error = document.querySelector('#error');
let emptyDatabase = document.getElementById('empty-database');
// Grab the unordered list of countries
let rootUl = document.querySelector('#root ul');
// Extract(GET request) data from database
let database = await getRequestForCountries();
// Get the two templates: One is for both country and town, another is just for town when country already exists
let template = await getTemplate();
let templateTown = await getTemplateTown();
// Load countries on page load
onPageLoad();
//Attach load event to button
attachLoadEvent();
//Reset button for deleting the database
resetButton()
function errorHandler(){
error.style.display = 'block';
setTimeout(function(){
error.style.color = 'rgb(136, 9, 0)';
error.style.background = 'none';
}, 150)
error.style.color = 'red';
error.style.background = 'rgb(136, 9, 0)';
}
function onPageLoad(){
database.forEach(entry => {
let townsArr = entry.towns;
let countryName = entry.countryName;
let townsArrObj = townsArr.reduce((acc, cur) =>{
let townObj = {
name: cur
}
acc.push(townObj);
return acc;
},[]);
let countriesObj = {
countries:[
{
name: countryName,
towns: townsArrObj
}
]
}
//Was rootUl.innerHTML += template(countriesObj); But that breaks the DOM of error and makes error.isConnected = false;
// rootUl.innerHTML += template(countriesObj);
rootUl.insertAdjacentHTML('beforeend', template(countriesObj));
})
}
Element.innerHTML +=, gets HTML code within the element and append it with something.
document.querySelector('p').innerHTML += `<span>Appended span</span>`;
<p>
Lorem Ipsum
<span style="color: red">Something</span>
<p>
Whereas, Element.insertAdjacentHTML('beforeend', 'To be inserted node'), will add new node, before the specified element.
document.querySelector('p').insertAdjacentHTML('beforeend', '<div>I am div</div>');
<p>Lorem ipsum</p>
I am looking for javascript command that would do the following:
Click on image -> open spoiler
Click on image again -> hide spoiler
Here is what I got so far:
javascript in my html
<script>
function myFunction() {
document.getElementById("prvy").innerHTML = document.getElementById('spoiler_id').style.display='';}
</script>
Spoiler
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
And my button:
<div id="prvy" onclick="myFunction()"></div>
What I managed to do, is to click on a image, wich will open spoiler. Hovewer, I've been unable to do the second part, onclick again it will close the spoiler.
I also did serach for solution alredy, nothing worked for me, not even this: Link
I also tired if{} else{} statement but didn't work for me either.
Help would be really appreciated, as I am getting desperate on this one.
You can use jQuery .toggle() to toggle show/hide
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
Note : You need to include jQuery in your document as
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Working snippet :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
<div id="prvy" onclick="myFunction()">button</div>
<script>
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
</script>
In the JavaScript where you click the button use the simple jQuery function toggle.
$('#spoiler_id').toggle();
Toggle will hide the element selected if it is currently shown or display the element if it is currently hidden.
you would need some state that flips when the function is called.
like this.
<script>
var state = false;
function myFunction() {
state = !state;
if(state){
//do something
}else{
//do something else
}
}
</script>
Is that all of your code, it would be easier for you and less confusing too if you just gave the buttons an on click function and then called that function in your js.
Can I see all of your html
I am giving an example to concerned question using javascript.
HTML:
<script type="text/javascript">
var permit = 'true';
function showhide() {
var getcont = document.getElementsByClassName('hidshowcont');
if (permit === 'true') {
permit = 'false';
getcont[0].style.display = 'block';
}
else {
permit = 'true';
getcont[0].style.display = 'none';
}
}
</script>
<style type="text/css">
.hidshowcont{
height: 200px;
width: 300px;
border: 1px solid #333333;
display: none;
}
</style>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR1cSDTn18ufwjuMihttTvCPJOnFY-4hxbPcaOVd87nSPaQakbP9IERaQ" />
<br />
<br />
<div class="hidshowcont">
This is an example of hide and show the container by clicking of an image.
</div>
This will help u much
I have a page which has a lot of buttons. What I need to do is to show a div near the button. I tried this:
<style>
#noteDiv {display:none; position: absolute; background-color: white; border: 1px solid blue;}
</style>
<script>
function showNote(e) {
var x = 0, y = 0;
if (!e) e = window.event;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else if (e.clientX || e.clientY) {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
document.getElementById("noteDiv").style.display = "block";
document.getElementById("noteDiv").style.left = (x)+"px";
document.getElementById("noteDiv").style.top = (y-350)+"px";
}
function hideNote() {
document.getElementById("noteDiv").style.display = "none";
}
</script>
<body>
<?php
echo "<button type ='button' id = 'noteButton'>Note</button>";
echo "<script>document.getElementById('noteButton').onclick = showNote;\n";
echo "</script>";
?>
</body>
<div id='noteDiv' >
<div ><span onclick="hideNote()">Close</span></div>
<br clear="all">
<div id='noteContent' style='max-height: 30em'></div>
</div>
It does work. But sometimes the page will show one more div on top of the page, like a warning message, and thus the noteDiv's position will be far from the buttons to which it should attach.
My thinking is to get the position of the buttons, and send the x, y values of the button position to the function showNote(), from there show the noteDiv. I don't know if this idea is reasonable and how to get and transfer the current clicked button's position to javascript?
Any suggestions and hints will be appreciated!
From the beginning.
Load javascript on top of your page is a very bad idea. I'll let the tons of web articles to explain you why. Just to say one reason, the js files are downloaded before the html is rendered (depending on the browser), resulting in a slower rendering of the page.
About your approach:
Three words: separation of concerns. Positioning dom elements is not what belongs to javascript (except some very rare occasions).
Styling the DOM, which comprehends positioning of the objects, belongs to the Cascading Style Sheet, also known as CSS.
So if something is not rendered in the right way, don't try to fix it with javascript. It will only drives you to enormous headaches.
For a better answer, please provide a code that can show us the error.
UPDATE
Here is a working example (probably not optimised) of what you are maybe trying to achieve. Please, please, please, please... read a book about html, css and js. It's totally worth it. I didn't use php, didn't need it.
Just for the records, the general structure of an html page I personally use is like this one:
html
head
title
meta
styles link
styles sections
js **LIBRARIES** which need to be loaded on **TOP**
google analytics
body
html content
js **LIBRARIES** which need to be loaded on **BOTTOM**
js scripts
And for your sanity, and of the people who helps you, indent correctly (it's also a sign of respect to the people who are reading your code).
Here is the code with the snippet:
function toggleNote(id) {
var noteParent = document.getElementById(id);
var note = noteParent.querySelector('.note');
var display = "none";
if (note.style.display == "none" || note.style.display == "" ) {
display = "block";
}
note.style.display = display;
}
.note {
display: none;
position: relative;
background-color: white;
border: 1px solid blue;
}
.noteContent {
max-height: 30em
}
<body>
<div class="buttonContainer" id="note0">
<button id='noteButton' onclick="toggleNote('note0')">Note</button>
<div class='note'>
<div>
<button onclick="toggleNote('note0')">Close</button>
</div>
<br clear="all">
<div class='noteContent'>It's something!</div>
</div>
</div>
</body>
All the HTML like <button> <div> <span> <ul><li> <table> etc MUST be inside the <body> </body> tag:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<!-- you can include css and javascript here -->
<!-- but best place to include javascript ist at the bottom -->
<!-- see last comment -->
</head>
<body>
<?php echo '<button type="button" id="noteButton">Note</button>'; ?>
<!-- best place to include javascript or echo them with PHP what ever
right before the closing body tag -->
</body>
</html>
You are echoing a <button> via PHP before the opening <body> tag which is wrong. Try use something like firebug and https://validator.w3.org/
I have a a link that looks similar to this
Blog
As you can the link has an ID of 'blog' what I want to do is to create an div on the fly with the ID from the link that was clicked so if the 'blog' is clicked, then the markup would be
<div id="blog">
<!--some content here-->
</div>
Like wise if for instance the news link is clicked then I would like,
<div id="news">
<!--some content here-->
</div>
to be created in the markup if this possible? and how Im pretty new to jQuery.
Try this:
$("a").click(function(){
$("#wrapper").append("<div id=" + this.id + "></div>");
});
Not tested, should work ;)
where: #wrapper is parent element, work on all a as you see.
You will need to give the div a different ID. Perhaps you could give it a class instead:
$("#blog").click(function() {
$(this).after("<div class='blog'>...</div>");
return false;
});
That's just one of many ways to create a div. You probably also want to avoid duplicates however in which case, use something like this:
$("#blog").click(function() {
var content = $("#blog_content");
if (content.length == 0) {
content = $("<div></div>").attr("id", "blog_content");
$(this).after(content);
}
content.html("...");
return false;
});
As for how to handle multiple such links I would do something like this:
Blog
News
Weather
<div id="content"></div>
with:
$("a.content").click(function() {
$("#content").load('/content/' + this.id, function() {
$(this).fadeIn();
});
return false;
});
The point is this one event handler handles all the links. It's done cleanly with classes for the selector and IDs to identify them and it avoids too much DOOM manipulation. If you want each of these things in a separate <div> I would statically create each of them rather than creating them dynamically. Hide them if you don't need to see them.
Try This :
<a id="blog">Blog</a>
<a id="news">news</a>
<a id="test1">test1</a>
<a id="test2">test2</a>
$('a').click(function()
{
$('<div/>',{
id : this.id,
text : "you have clicked on : " + this.id
}).appendTo("#" + this.id);
});
First of all you should not make 2 elements with same ID. At your example a and div will both have id="blog". Not XHTML compliant, plus might mess up you JS code if u refernce them.
Here comes non-jquery solution (add this within script tags):
function addDiv (linkElement) {
var div = document.createElement('div');
div.id = linkElement.id;
div.innerHTML = '<!--some content here-->';
document.body.appendChild(div); // adds element to body
}
Then add to HTML element an "event handler":
Blog
This question describes how to create a div. However, you shouldn't have two elements with same IDs. Is there any reason why you can't give it an id like content_blog, or content_news?
Unfortunately if you click on a link the page you go to has no idea what the idea of the link you clicked was. The only information it knows is what's contained in the URL. A better way to do this would be to use the querystring:
Blog
Then using the jQuery querystring plugin you could create the div like:
$("wrapper").add("div").attr("id", $.query.get("id"));
You shouldn't have elements in your page with the same ID. Use a prefix if you like, or perhaps a class.
However, the answer is as follows. I am imagining that your clickable links are within a div with the ID "menu", and your on-the-fly divs are to be created within a div with the ID "content".
$('div#menu a').click(function(){
$('div#content').append('<div id="content_'+this.id+'"><!-- some content here --></div>');
});
Any problems, ask in the comments!
Also the following statement is available to create a div dynamically.
$("<div>Hello</div>").appendTo('.appendTo');
Working fiddle: https://jsfiddle.net/andreitodorut/xbym0bsu/
you can try this code
$('body').on('click', '#btn', function() {
$($('<div>').text('NewDive').appendTo("#old")).fadeOut(0).fadeIn(1000);
})
#old > div{
width: 100px;
background: gray;
color: white;
height: 20px;
font: 12px;
padding-left: 4px;
line-height: 20px;
margin: 3px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div>
<!-- Button trigger modal -->
<button type="button" id="btn">Create Div</button>
<div id="old">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</body>
</html>