I think I just need a second pair of eyes on this one. The div's onclick event doesn't seem to be working. Any ideas?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title="My First Program"/>
<script type="text/javascript">
window.onload = function(){
window.alert("If you see me then the page has loaded");
click();
}
//we do programming here
/*because
it is
fun*/
window.alert("Helo World!");
function click(){
window.alert("CLICK!!!!");
}
</script>
</head>
<body>
<div>This web page will run my first program</div>
<!--this will be awesome-->
<br>
<br>
<br>
<div id="d1" onclick="click()">Click me</div>
</body>
Also, for the reccord, this is not my first program.
your html is malformed. the title tag needs to look like this:
<title>My First Program</title>
Also, you seem to have a naming conflict because you named your function the same thing as a built-in function. rename your 'click' function to 'myclick' or something else.
Once you fix that, everything else should be good.
When something is going weird, the first thing you should always do is validate your markup.
http://validator.w3.org/check
Here is the complete, working version of the markup.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My First Program</title>
<script type="text/javascript">
window.onload = function(){
window.alert("If you see me then the page has loaded");
click();
}
//we do programming here
/*because
it is
fun*/
window.alert("Helo World!");
function myclick(){
window.alert("CLICK!!!!");
}
</script>
</head>
<body>
<div>This web page will run my first program</div>
<!--this will be awesome-->
<br>
<br>
<br>
<div id="d1" onclick="myclick()">Click me</div>
</body>
Every time I see a question like this anywhere, the typical answer I give is "don't use the Netscape model for event handling".
Give this a read - http://www.quirksmode.org/js/introevents.html
Update: Looks like "click" isn't a very good name for a function, since it's already registered for events and such, which is likely why it didn't work. I should have caught that.
Related
Hello my questions is about how a webpage is loaded! Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>Waiting</h1>
<script type="text/javascript">
alert("Why?");
</script>
</body>
</html>
I cannot for the life of me figure out why the alert is running before the heading is displayed. It is my understanding that since the alert is right above the closing body tag it will be the last thing run. Why is the page waiting for me to close out the alert before displaying the heading?
Thanks for the help!
Edit: I ran this code in firefox rather than chrome and it worked how I wanted it to - the heading displayed first before the alert ran.
You need to execute your script after the page loads with
<body onload="script();">
An external script will execute before the page loads.
<body onload="script();">
<h1>Waiting</h1>
<script type="text/javascript">
function script() {alert("Why?");}
</script>
</body>
You can use setTimeout() to show the alert after a few seconds (when the page should have loaded).
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>Waiting</h1>
<script type="text/javascript">
setTimeout(function(){
alert("Why?");
}, 1000);//wait 1000 milliseconds
</script>
</body>
</html>
You can check if the header (the h1 tag) is there and only alert if it is there.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1 id="header">Waiting</h1>
<script type="text/javascript">
var x;
x = setInterval(function(){
if(document.getElementById("header")){
alert("Why?");
clearInterval(x);
}
}, 100);
</script>
</body>
</html>
The simplest workaround code without using JQuery I could write is this. Please check it.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1>Waiting</h1>
<script type="text/javascript">
window.onload = function(){
setTimeout(()=>{
alert("Why?");
},10)
}
</script>
</body>
</html>
The cleanest way to do this seems like it would be to put your javascript in a separate file, and load it with the defer attribute. This will cause it to fire after the DOM loads (technically, just before DOMContentLoaded, but it doesn't work consistently across browsers unless there is a src attribute, which is why you would need to move it to an external file.
<script src="myScript.js" defer></script>
Oddly, adding some CSS to your heading could also affect this since JS is supposed to execute in order after any pending CSS.
The timeout function or a $(document).ready() function will do what you need in theory, but a timeout could need to be adjusted based on the complexity of the page, and if you aren't already using jQuery, you probably won't want to add it just to use $(document).ready().
I know that this is a frequently asked question.
I have tried all the methods like using onload() for body tag,
placing the script after the DOM elements and using self invoking function.
Yet I get that my element is undefined.
P.S: document.getElementsByTagName('') replaced with document.getElementById('') works fine. Why is that? Please explain both of my doubts. Here is my simple code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="loadHandler()">
<p>Drag me!</p>
<script type="text/javascript">
function loadHandler() {
document.getElementsByTagName('p').setAttribute('draggable', true);
}
</script>
</body>
</html>
getElementsByTagName (as the name suggests) returns an array of elements. If you want the first one, take the first one.
.highlight{ color: red}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body onload="loadHandler()">
<p>Drag me!</p>
<script type="text/javascript">
function loadHandler() {
var elem = document.getElementsByTagName('p')[0];
elem.setAttribute('draggable',true)
elem.classList.add('highlight');
}
</script>
</body>
</html>
As for why dragging is not working, perhaps the documentation might shed some light
By default, only text selections, images, and links can be dragged. For all others elements, the event ondragstart must be set for the drag and drop mechanism to work, as shown in this comprehensive example.
getElementsByTagName returns array of results, not just a single result like getElementById. Try to use getElementsByTagName('p')[0].
I apologize in advance if this has been asked before. So the circumstances I mentioned in the title is this:
I am writing html into a new window.document.open() object. The html I am writing also includes in the head.
This is the script I am not able to run,
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script>
$(document).ready(function(){
alert('This is working!');
});
</script>
The interesting thing is that every other jquery code works. For example in my html I have a button with id='but' and this script works
$('#but').click(function(){
alert('you clicked a button')'
});
so why is the $(document).ready() not working? Is this because window.document.open() doesn't count as document for jquery?
Thanks in advance.
edit: I think my question is unclear. I am terribly sorry about that. Here's the situation:
I have a javascript file that essentially has this:
var w=window.open();
var temp=`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Template for converted files</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<script type="text/javascript" src="file.js"></script>
<script>
$(document).ready(function(){
alert('This is working!');
});
</script>
</head>
<body class="body">
<button id='but'>click me!</button>
</body>
</html?
`;
w.document.open();
w.document.write(temp);
the file file.js has the following:
$('#but').click(function(){
alert('you clicked a button')'
});
now when I run the first JS file, I am able to open a new window with the button. when clicked it says "you clicked a new button"
But the alert "This is working!", isn't working.
Hope this makes the situation clear. I am really sorry for not being clear from the start.
Because jQuery has no method open() in it's api.
open() is a window method only.
You can refer to the new window by passing it to a variable:
var win = window.open(url[,options])
I am a newbie in web development and tried my hand the following code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Generic Page </title>
<script type="text/javascript">
setTimeOut(wakeUpUser, 5000);
function wakeUpUser() {
alert("Time to make life interesting");
}
</script>
</head>
<body>
<h1>Just a generic heading </h1>
<p>Just a normal paragraph</p>
</body>
</html>
But the script does not run only a boring static HTML page.I am following the HeadFirst Javascript Programming.Is the book wrong on this example?
You have a typo in your JavaScript. setTimeout should be written with a small "o".
This is the Script error in your code, modify the "SetTimeout" to an actual case.
I have attached both the result of your code and Bug Fixed code results, where SetTimeout code fix suggested works fine.
setTimeout(wakeUpUser, 5000);
Your Code Before Fix:
Result After Bug Fix:
Just a super small typo in your code, instead of 'setTimeOut', it needs to be a lowercase 'O', so 'setTimeout'. Here's the complete snippet:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>A Generic Page </title>
<script type="text/javascript">
setTimeout(wakeUpUser, 5000);
function wakeUpUser() {
alert("Time to make life interesting");
}
</script>
</head>
<body>
<h1>Just a generic heading </h1>
<p>Just a normal paragraph</p>
</body>
</html>
I think you much call setTimeout use o insteh of O after declare function :) ... If you don't have jQuery library. try to use setInterval function :) more exaple
http://www.w3schools.com/jsref/met_win_setinterval.asp
Try moving the setTimeout to be after the function is declared.
Your browser's developer tools should show you any errors encountered. Specifically the 'console'.
Happy coding!
Edit: see also the other answers about the small o in setTimeout
What i want to do is simple. When i click the image, i want some message to appear.
Afterwards, when i click it again i want it to disappear. I have problems iplementing it
due to my lack of jQuery knowledge. I would appreciate some help with the following code, as well as some other implementations. I know i can do something with class="hidden" and have jQuery add/remove it but oh well.
This is what i'm trying to work with.
<!DOCTYPE html>
<html>
<head>
<script>
function greet(){
a = document.getElementById('here');
if (a.trim().length==0){
a.innerHTML = 'message!';
}
else{
a.innerHTML = '';
}
</script>
</head>
<body>
<img src="http://www.clker.com/cliparts/K/9/M/I/M/8/on-button-small-th.png" alt="alt" onclick="greet()"/>
<p id='here'></p>
</body>
</html>
EDIT: seems like i should use a.value, but i must be doing something else wrong too.
If you are using jQuery it is very simple; just use this as your JavaScript (don't forget to link the jQuery main library - I like the Google CDN for that). Just use the toggle function:
function greet() {
$('#here').toggle();
}
Also it is better to register the onClick through jQuery rather than your html (for examplesee this SO question). So that would be like this for the whole page instead :
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$( document).ready(function() {
$("#greet").click(
function () {
$('#here').toggle();
}
);
$("#here").hide();
}
</script>
</head>
<body>
<img id="greet" src="http://www.clker.com/cliparts/K/9/M/I/M/8/on-button-small-th.png" alt="alt"/>
<p id='here'><!--MESSAGE SHOULD BE HERE--></p>
</body>
</html>
Working example in jsFiddle.