Why can't I just declare the script in <head>? [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 3 years ago.
When I de-comment in the HTML, the code works properly. May I ask what the problem is and why it happened? Just started learning web programming last week, thanks a lot.
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="utf-8">
<title>Canvas</title>
<script src="jquery-3.3.1.js"></script>
<script src="menu.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<span id="id1">Welcome back to my site. </span>
<div id="div1" >
<p>Hi</p>
Hi
<!--<script src="menu.js"></script> -->
</div>
<input type="button" id="btn" value="Toggle" />
</body>
</html>
JavaScript (menu.js)
$("#hyper").click(function(){
alert("Hi");
});

The problem is that when the <script> is in <head> its executed before the document has been loaded. It means when the <script> is in <head> and $("#hyper") line is executed at that time the element
Hi
is not generated. So it doesnot work.
Solution:
Put your <script> at end of <body>
Or you can use document.ready()
Below are two examples to see the difference.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
//At this point "<div id="test"><div>" is not loaded
console.log($('#test').length) //0
console.log(document.querySelector('#test')) //null
</script>
<div id="test"><div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"><div>
<script>
console.log($('#test').length) //1
console.log(document.querySelector('#test')) //<div id="test">…</div>
</script>

There are two problems with scripts in the <head>
Those scripts are executed before loading of the body, sometimes this may cause problems, however you can overcome this problem using document.ready or window.onload etc.
In big applications scripts become very big file, then if you've loaded them in the <head>, then user have to wait until they load fully to see anything on the webpage, but if you put them in the footer of the page, then you can create a pre-loader on the webpage, which will be loaded and shown to the user until all the scripts load completely.

Related

Adding jQuery to wordpress page to display Time/Date Picker

I found a Time picker here:
Time Picker.
It is the second one on the list with the grey square and 4 arrows. I need to know how to add this time picker to a WordPress page. When I downloaded all the JS files and the CSS files it included an HTML page. But, if I use the HTML code (below) the arrows are missing so selecting the time doesn't work like the original page. The download provides me with the js and css files needed I just don't know how to use them.
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>jQuery Time Entry</title>
<link href="jquery.timeentry.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="jquery.plugin.js"></script>
<script src="jquery.timeentry.js"></script>
<script>
$(function () {
$('#defaultEntry').timeEntry();
});
</script>
</head>
<body>
<h1>jQuery Time Entry Basics</h1>
<p>This page demonstrates the very basics of the
jQuery Time Entry plugin.
It contains the minimum requirements for using the plugin and
can be used as the basis for your own experimentation.</p>
<p>For more detail see the documentation reference page.</p>
<p>Enter your time: <input type="text" id="defaultEntry" size="10"></p>
</body>
</html>
These are the first two steps needed in the USAGE: section of the source page.
Include the jQuery library (1.7+) in the head section of your page.
Download and include the jQuery Time Entry CSS and JavaScript in the
head section of your page.
I tried to add this code to my wordpress page on the text tab but I don't get the results I need:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>jQuery Time Entry</title>
<link href="/wp-content/jquery.timeentry.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="/wp-content/jquery.plugin.js"></script>
<script type="text/javascript" src="/wp-content/jquery.timeentry.js"></script>
<script type="text/javascript">
<!--
$('#spinnerOrange').timeEntry({spinnerImage: 'wp-content/spinnerOrange.png'});
//--></script>
</head>
<body>
<h1>jQuery Time Entry Basics</h1>
<p>This page demonstrates the very basics of the
jQuery Time Entry plugin.
It contains the minimum requirements for using the plugin and
can be used as the basis for your own experimentation.</p>
<p>For more detail see the documentation reference page.</p>
<p>Enter your time: <input type="text" id="spinnerOrange" size="10"></p>
</body>
</html>
I am not sure if I referenced the script right or the stylesheet. Any help would be greatly appreciated.
Thanks,
Matt
jQuery is already included in Wordpress by default.
In order to add scripts, the right way to do it in Wordpress is using wp_enqueue_script
Here the doc: https://developer.wordpress.org/reference/functions/wp_enqueue_script/
Here a sample:
https://premium.wpmudev.org/blog/adding-jquery-scripts-wordpress/

Separate HTML / JavaScript

I'm attempting to have my JavaScript code in a file apart from my HTML file.
Linking the 2 scripts between each other works, however stuff like the function document.getElementById() doesn't.
Anyone know how to fix this?
HTML code:
<!DOCTYPE HTML>
<html>
<head>
<title>Boost</title>
<script src="javascript.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css"/>
</head>
<body>
<h3>
<p id="TopTextParagraph">Hi there</p>
<div>
<button id="clickNext">Next</button>
</div>
</h3>
</body>
</html>
JavaScript code:
document.getElementById("clickNext").onclick = goNext;
function goNext() {
console.log("stuff here")
}
JavaScript works when I put it in the HTML file using <script> </script>, just don't know how to make it work in a separate JavaScript file.
You are adding the script inside head tag. When that snippet is executed clickNext element does not exist in the dom
You can add the script near the closing body tag to resolve the problem & remove from the head tag
<body>
<h3>
<p id="TopTextParagraph"> Hi there</p>
<div>< button id="clickNext"> Next</button></div>
</h3>
<script src="javascript.js"></script>
</body>

jQuery Not Working in Eclipse

Still a bit new with jQuery so I may be making a basic error.
I just completed the jQuery introductory course and now am trying to do some of my own basic work, but have hit a slight road block.
Essentially it seems the jQuery file script.js isn't getting called properly.
When I ran it inserting it into stackoverflow it seems to work fine. However,
when I pull the html file in the browser it only displays the html elements in the file and not any of the jQuery code.
Any help would be appreciated!
$(document).ready(function() {
$("body").append("<p>I\'m a paragraph!</p>");
/* write 'Hello World! to the first div' */
$("#first").append('<h1> Hello World!</h1>');
//a clickable 'Hello World!' example
$("#link").click(function() {
$('#greeting').append("<h1>Hello Again!</h1>");
});
});
<!DOCTYPE html>
<html>
<head>
<title>Hello World - jQuery Style</title>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
</head>
<body>
<div id="first"></div>
<div id="second">
Click Me! <br /> <span id="greeting"></span>
</div>
</body>
</html>
You should declare your current javascript file after you get the jquery.min.js
If you look in your console ( right click and inspect ) You will notice that it cannot understand $ jquery sign.
Solution should be just swap these two lines in your html :
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
Try switching the order of the tags for script.js and jquery.min.js so that jquery is initialised first

Why won't my jQuery work at all?

I can't get jQuery to work on my page. so I used jsfiddle.net to test if my jQuery code works, and it does. However, when I copy and paste the same code unto my document, it doesn't work. So I'm assuming that there's an error with linking the jQuery external file on my html document. I'm using TextWrangler as my text editor.
html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Rules </title>
<link rel="stylesheet" href="styleRules.css" />
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type= "text/javascript" src="JsRules.js"> </script>
</head>
<div id="left" >
<ol>
<li> First Rule </li>
</ol>
</div>
css
#left {
float:left;
margin-left:200px;
}
jQuery
$(document).ready(function () {
$("#left").mouseenter(function () {
$("#left").fadeTo("fast", 0.25); });
});
Thanks for the time in answering and reading this. I'm currently stuck, I've reached a dead end, and I can't wait to overcome this problem!
I agree with other people that it's most likely a typo in the name of your jQuery file. I created a web page using your exact code except that I spelled the jquery file correctly. It worked fine.
And even though using the BODY element is proper and important, it didn't affect the outcome of my testing your code.
Please, use the "Inspect Element" (tools of chrome ) or Firebug (tool of Firefox and Chrome) for find the error.
Now for me the possible errors are:
Name not declared correctly for example <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
you can change the script with external files (libraries of google) <script src="http://code.jquery.com/jquery-2.0.0.js"></script>
Now I create the DEMO on JSFIDDLE with your code and seems that it works
You have a typo in your HTML referencing the jQuery document:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Rules </title>
<link rel="stylesheet" href="styleRules.css" />
<!---Typo was here--->
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type= "text/javascript" src="JsRules.js"> </script>
</head>
<div id="left" >
<ol>
<li> First Rule </li>
</ol>
</div>
</body>

What is the difference between these two jQuery usage

Im a jquery starter so if its a wrong one forgive me :)
I just want to know why placing the content at different positions made this script working, although to my best i think script to kept in head section of the document. Please explain the concept.
Working Code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example 2</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>
</p>
<script type="text/javascript">
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
</script>
</body>
</html>
Not Working
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example 2</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
</script>
</head>
<body>
<p>
</p>
</body>
</html>
In the second instance the code is executed before the <p> has been parsed into the DOM tree, so while it still works there's nowhere to put the output text into. In other words, jQuery("p") matches no element so .html() "does nothing".
You can fix this by either waiting for the DOM to be fully parsed:
jQuery(function() {
jQuery("p").html(...);
});
or by using an output mechanism that does not depend on the <p> existing, such as alert() or console.log().
Well, it seems that your browser firstly load <head> section thus in second example there is no p element then.
In both cases you should wrap your code in $(function(){ ... }).
If you place your script before the <body> element, it is executed before the DOM tree is loaded/parsed. The <p> element does therefore not exist and cannot be found. You can:
Place the script after the <body> tag (like in your first example)
or you can call your function after the ready event has been fired:
$(document).ready(function() {
jQuery("p").html("Check if jQuery Supports Ajax method : "+ jQuery.support.ajax );
});

Categories