The document.domain method
- Method type: iframe.
Note that this is an iframe method that sets the value of document.domain to a suffix of the current domain. If it does so, the shorter domain is used for subsequent origin checks. For example, assume a script in the document at Page on company.com executes the following statement:
document.domain = "company.com, llc";
After that statement executes, the page would pass the origin check with
page on company.com.
However, by the same reasoning, Company.com, LLC could not setdocument.domain to other | other.
With this method, you would be allowed to exectue javascript from an iframe sourced on a subdomain on a page sourced on the main domain. This method is not suited for cross-domain resources as browsers like Firefox will not allow you to change the document.domain to a completely alien domain.
The Cross-Origin Resource Sharing method
- Method type: AJAX.
Cross-Origin Resource Sharing (CORS) is a W3C Working Draft that defines how the browser and server must communicate when accessing sources across origins. The basic idea behind CORS is to use custom HTTP headers to allow both the browser and the server to know enough about each other to determine if the request or response should succeed or fail.
For a simple request, one that uses either GET or POST with no custom headers and whose body is text/plain, the request is sent with an extra header called Origin. The Origin header contains the origin (protocol, domain name, and port) of the requesting page so that the server can easily determine whether or not it should serve a response. An example Origin header might look like this:
Origin: http://www.quora.com
If the server decides that the request should be allowed, it sends a Access-Control-Allow-Originheader echoing back the same origin that was sent or * if it’s a public resource. For example:
Access-Control-Allow-Origin:http://www.quora.com
If this header is missing, or the origins don’t match, then the browser disallows the request. If all is well, then the browser processes the request. Note that neither the requests nor responses include cookie information.
The Mozilla team suggests in their post about CORS that you should check for the existence of the withCredentials property to determine if the browser supports CORS via XHR. You can then couple with the existence of the XDomainRequest object to cover all browsers:
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest(); xhr.open(method, url);
} else { xhr = null;
} return xhr;
}
var request = createCORSRequest("get", "Stack Overflow");
if (request){ request.onload = function() {
// ...
}; request.onreadystatechange = handler; request.send();
}
Note that for the CORS method to work, you need to have access to any type of server header mechanic and can't simply access any third-party resource.
Source: Cross-domain Ajax with Cross-Origin Resource Sharing
The window.postMessage method
- Method type: iframe.
window.postMessage, when called, causes a MessageEvent to be dispatched at the target window when any pending script that must be executed completes (e.g. remaining event handlers if window.postMessage is called from an event handler, previously-set pending timeouts, etc.). The MessageEvent has the type message, a data property which is set to the string value of the first argument provided to window.postMessage, an origin property corresponding to the origin of the main document in the window calling window.postMessage at the time window.postMessage was called, and a source property which is the window from which window.postMessage is called.
To use window.postMessage, an event listener must be attached:
// Internet Explorer window.attachEvent('onmessage',receiveMessage); // Opera/Mozilla/Webkit window.addEventListener("message", receiveMessage, false);
And a receiveMessage function must be declared:
function receiveMessage(event){ // do something with event.data;}
The off-site iframe must also send events properly via postMessage:
<script>window.parent.postMessage('foo','*')</script>
Any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message. Consequently, any event listener used to receive messages must first check the identity of the sender of the message, using the origin and possibly source properties. This cannot be understated: Failure to check the origin and possibly sourceproperties enables cross-site scripting attacks.
- Define “doesn't work” - what your code supposed to do? We can only guess what was your intention without comments in code.
- Why do you run function after interval if the function already runs inside setInterval - remove last line.
- What does setRotation - no idea if problem is there. You haven't provided complete code.
- Run setInterval after defining variables and functions. It usually change nothing, but here may be this exception when it does.
It’s not necessary. Yes, you can write code directly inside a <script> tag.
That said, it’s rare you’ll actually want to do that on anything other than a toy project. Substantial projects have substantial code. It is broken down into files in order to be more manageable and meaningful. Otherwise, it’s like a giant wall of text that’s hard to read.
Additionally, many JavaScript developers prefer to have a build process. This is a process that will bundle your code, often times generate some code, minify it, and allow you to customize it. These aren’t technical requirements to run code, but they c
It’s not necessary. Yes, you can write code directly inside a <script> tag.
That said, it’s rare you’ll actually want to do that on anything other than a toy project. Substantial projects have substantial code. It is broken down into files in order to be more manageable and meaningful. Otherwise, it’s like a giant wall of text that’s hard to read.
Additionally, many JavaScript developers prefer to have a build process. This is a process that will bundle your code, often times generate some code, minify it, and allow you to customize it. These aren’t technical requirements to run code, but they can be really helpful for simplifying how much time you spend working on your code. In my opinion, the best part of a build process is the ability to setup unit tests… you can basically auto-run your code before actually using it in a web page. This can save a lot of time.
I don’t really get how Quora works (I’m new) soo….
I'm kinda new to Javascript and HTML. I'm trying to convert whatever is in the text to hexa-decimal by using .toString(16)
Whenever I put a set value for the code it works. When I put it into an input, it doesn't.
I've tried to debug it. I made sure it was sending the right info by doing alert(x); and I got the correct info. So, I don't know what the problem is. I've tried a lot of things to try and resolve this on my own.
<body>
<input type="text" id="textBox" value="50">
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
I don’t really get how Quora works (I’m new) soo….
I'm kinda new to Javascript and HTML. I'm trying to convert whatever is in the text to hexa-decimal by using .toString(16)
Whenever I put a set value for the code it works. When I put it into an input, it doesn't.
I've tried to debug it. I made sure it was sending the right info by doing alert(x); and I got the correct info. So, I don't know what the problem is. I've tried a lot of things to try and resolve this on my own.
<body>
<input type="text" id="textBox" value="50">
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var x = '';
x = document.getElementById("textBox").value;
var b = x;
b = x.toString(16);
alert('Your original number was ' + x);
alert('Your hexidecimal number is ' + b);
}
</script>
</body>
For 50, I should get 32. But instead, whenever I use the text box instead of inserting a number through the code, it gives me 50. Same for any other number. If I put 21 in the text box, I get 21. When I should get 15. I guess a better example. When it says,"x = document.getElementById("textbox")" it will give me the correct value. But, when I do b = x.toString(16), I get the same value. If I do x = (a value example:21) and also do b = x.toString(), I get the correct value for hexadecimal example:21 is now 15.
The reason you should hire a digital marketing freelancer is that it can be very overwhelming trying to do this on your own–which is why so many people and businesses outsource that work. Fiverr freelancers offer incredible value and expertise and will take your digital marketing from creation to transaction. Their talented freelancers can provide full web creation or anything Shopify on your budget and deadline. Hire a digital marketing freelancer on Fiverr and get the most out of your website today.
3 things that are problems
a) incorrect nesting
b) missing symbols [; . {} \| ]
c) lack of understanding DOM commands
Check first for (a) then (b) in code examination. But if you haven't sufficient exposure to (c), don't use anything that starts withe the word “Java".
The second line of setClock
arms like the most likely culprit. getSeconds
should be called with parentheses.
Putting JS code in HTML is never a good idea, although for small pieces of scripts people would just throw them in their HTML somewhere and not bother to put them separately.
But the best practice is putting JS code to a separate file, and CSS code to a separate file, as well. This way not only your HTML will look neater and easy to read whenever a problem comes up (or something new to be added) and you need to review your code but it will also help you debug your JS easier in case you need to when your website grows bigger
Maintenance is easier.
If you’re building a web app, the code can reach thousands of lines pretty quickly. It’s too confusing to read, so the better way is to write your code in separate files, say a file is only for signing in (and out) of users, another for downloading database, another is for users form, etc. It’s up to you how you organize it.
If you do everything in just one file, when you want to say something like “only show form if the user is signed in”, maybe you will have to scroll up and down your code to see what was the name of the sign in function? Often it’s hard to remember.
Also
Maintenance is easier.
If you’re building a web app, the code can reach thousands of lines pretty quickly. It’s too confusing to read, so the better way is to write your code in separate files, say a file is only for signing in (and out) of users, another for downloading database, another is for users form, etc. It’s up to you how you organize it.
If you do everything in just one file, when you want to say something like “only show form if the user is signed in”, maybe you will have to scroll up and down your code to see what was the name of the sign in function? Often it’s hard to remember.
Also, if there’s an error, the error message will show the line number and file name. Assuming you name your files in a well-organized manner, let’s say the error is in line 78 of signin.js, then you’ll quickly know which part of your program cause error.
I just came across this issue just now and couldn’t find any good answers googling or even on quora. How is that even possible?
Everyone’s answers kept saying it was either because the <script> tag wasn’t being used in the html file or the code was not being written correctly, or they said it’s because you need a server to run it. None of these suggestions solved my problem.
My html was correct, I used the <script> tag correctly.
I also saved my javascript file with .js ending.
What I didn’t realize, is that I needed to save all my files, html, css, and js with encoding of utf-8 because the <meta
I just came across this issue just now and couldn’t find any good answers googling or even on quora. How is that even possible?
Everyone’s answers kept saying it was either because the <script> tag wasn’t being used in the html file or the code was not being written correctly, or they said it’s because you need a server to run it. None of these suggestions solved my problem.
My html was correct, I used the <script> tag correctly.
I also saved my javascript file with .js ending.
What I didn’t realize, is that I needed to save all my files, html, css, and js with encoding of utf-8 because the <meta charset> is pointed to utf-8.
The beginning of my code is as follows:
<head>
<meta charset="utf-8">
<title>JSEvents</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href=bower_components/boostrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="jsevents.css">
</head>
By saving all my documents with encoding of utf-8 my javascript file finally worked!
To save as a utf-8 file, just go to:
- FILE
- SAVE WITH ENCODING
- SELECT UTF-8
That’s it baby! YES!
Hi.
Is putting JS code in HTML better than creating a separate JS file?
Yes and No.
Reason :
- When a user searches a URL the first thing that a browser is going to display is the HTML page. So if the JS is also included in the HTML then it will make the page loading easier and also faster.
- No need to download the JS file separately. Which improves the overall performance.
But its better to put the JS in a separate file. Because if you are going to do some changes in the JS then its a lot easier if you have a separate file. And also for debugging.
And also the page loading speed that I was taking about
Hi.
Is putting JS code in HTML better than creating a separate JS file?
Yes and No.
Reason :
- When a user searches a URL the first thing that a browser is going to display is the HTML page. So if the JS is also included in the HTML then it will make the page loading easier and also faster.
- No need to download the JS file separately. Which improves the overall performance.
But its better to put the JS in a separate file. Because if you are going to do some changes in the JS then its a lot easier if you have a separate file. And also for debugging.
And also the page loading speed that I was taking about earlier is just a mere milliseconds or seconds. And the user wont notice the different at all. (Only if he is using browsers like Internet Explorer he will notice. But that is long gone).
So you can create a separate file for JS and try to minify the JS file. That also will help reducing the loading time.
If you feel you are confident about putting the JS in the HTML itself (Only for small projects which contains max 30 to 40 lines of code) , then no problem. But just keep a separate copy of JS for a development purpose.
Hope this helps 🙂.
It may have to do with the order of things on your aspx page and the possibility that one of the JavaScript libraries used is replacing subst() in the prototype. So substr() works one way until the library replaces it then it works another.
Not if they are well designed, short of extreme cases where the client runs out of memory. That would take a lot of Javascript files though. But, for the sake of page speed and server load, you should still use some sort of minifier to process and consolidate JS and CSS-files for production environments.
Then there is the case where they are not well designed. A potential issue, that might trip you up if you are new to JavaScript, is that the browser doesn't really care which file your code is in. There's no namespacing.
If you declare a variable in the global scope in Script_a.js, you can use
Not if they are well designed, short of extreme cases where the client runs out of memory. That would take a lot of Javascript files though. But, for the sake of page speed and server load, you should still use some sort of minifier to process and consolidate JS and CSS-files for production environments.
Then there is the case where they are not well designed. A potential issue, that might trip you up if you are new to JavaScript, is that the browser doesn't really care which file your code is in. There's no namespacing.
If you declare a variable in the global scope in Script_a.js, you can use that variable in Script_b.js as long as they are both included in the same HTML file.
That's neat as long as you are doing it on purpose. But what tends to happen is that two variables in two different scrips just happen to have the same name, and they keep overwriting each other, creating all sorts of weird bugs.
To prevent that, the current best practice is to use an "immediately invoked function expression" (IIFE) to wrap each separate javascript file, to keep your code off of the global scope.
It's an anonymous function expression that is declared, and then immediately invoked. Basically, your JS file looks like this:
- (function() {
- var localVariable = "I'm invisible";
- // More code here
- }());
This works because the variable is in the scope of the anonymous function, rather than on the global scope. Notice the Parenthesis on the last line, which calls the function immediately after declaring it.
Here are the reasons why you should NOT put your html, css and js in one file.
- Size of file increases - leads to slower loading.
- Too much cluttered code. - Difficult to maintain
- No Modularity
- Code Duplication - Since the same Css code will be used by other pages of your site and you’ll copy it in each html.
- Bad Practice.
Keep your code modular. This will help you re use your code and maintain it properly.
Sure. We do this all the time. You can copy this to a new page and it will work fine.
- <script>
- alert('Hello World');
- </script>
It’s just code…
However, if that code is specifically making calls to objects on that page by name or ID, the code will break unless those objects also exist on the new page.
Also, if the code makes references to functions that are in other files or something, the code will bre
Sure. We do this all the time. You can copy this to a new page and it will work fine.
- <script>
- alert('Hello World');
- </script>
It’s just code…
However, if that code is specifically making calls to objects on that page by name or ID, the code will break unless those objects also exist on the new page.
Also, if the code makes references to functions that are in other files or something, the code will break un...
In JavaScript, how you work with files varies depending on whether you're coding for a browser or a server. On the client side, JavaScript makes advantage of the File API to manage files that users upload. The FileReader API lets you read file contents as either text or binary data. This allows you to examine images or upload files to a server without reloading the page. When working on a server with Node.js, you interface with files through the fs (File System) module. This lets you read, write, and remove files on the server. Because it runs asynchronously, you may manage file activities wit
In JavaScript, how you work with files varies depending on whether you're coding for a browser or a server. On the client side, JavaScript makes advantage of the File API to manage files that users upload. The FileReader API lets you read file contents as either text or binary data. This allows you to examine images or upload files to a server without reloading the page. When working on a server with Node.js, you interface with files through the fs (File System) module. This lets you read, write, and remove files on the server. Because it runs asynchronously, you may manage file activities without blocking up your server. This is especially useful for things like uploading files orIn both cases, JavaScript makes it easy to work with files. Whether you're saving data, reading configuration files, or handling uploads, JavaScript provides tools for all kinds of file management, giving you the flexibility to work with files in different environments.
For more info, you can check:
If well structured, and you used a minfier for them, then i don't see why it would break your code. However if you used a lot of heavy weight javascript files, the browser's memory could run out and cause issues. And its not generally good practice to attach a lot of JS to a website, since its bad for loading time. So try to use as few as possible!
It is more organized and readable if you store your js code in separate files. But, keeping your js code inside your html code using the <script>
tag improves page load time by reduces the amount of external page calls.
Also if you put your JS code inside of your HTML I recommend your put your <script>
after all the contents of your body(right before the </body>
tag. This ensures that the user can see all of the page contents without having to wait for the JS to load. Because of the fact that the page is already loaded before the js starts executing, you can do DOM manipulation whithou
It is more organized and readable if you store your js code in separate files. But, keeping your js code inside your html code using the <script>
tag improves page load time by reduces the amount of external page calls.
Also if you put your JS code inside of your HTML I recommend your put your <script>
after all the contents of your body(right before the </body>
tag. This ensures that the user can see all of the page contents without having to wait for the JS to load. Because of the fact that the page is already loaded before the js starts executing, you can do DOM manipulation whithout any need for event listeners like onload without which you would have had a error returned because the DOM element would not have existed yet.
Absolutely! In the fascinating realm of JavaScript, it's entirely possible to run code from one JavaScript file within another. This seamless integration allows for modular and organized scripting.
Assuming you can modify the code in both files: Turn the PHP function into a web service which accepts arguments by URL and dumps its output to the HTTP response. Then call the service with an AJAX request and stick the response into your variable.
- <?php
- // http://example.com/add.php
- function add($a, $b) {
- header('Content-type: text/json');
- echo json_encode(array('sum' => $a + $b));
- }
- add($_GET['a'], $_GET['b']);
- ?>
- // This is jQuery, but it could be anything
- $.getJSON('http://example.com/add.php?a=2&b=2', function(response) {
- doSomethingWith(response.sum);
- });
Now all your components are decou
Assuming you can modify the code in both files: Turn the PHP function into a web service which accepts arguments by URL and dumps its output to the HTTP response. Then call the service with an AJAX request and stick the response into your variable.
- <?php
- // http://example.com/add.php
- function add($a, $b) {
- header('Content-type: text/json');
- echo json_encode(array('sum' => $a + $b));
- }
- add($_GET['a'], $_GET['b']);
- ?>
- // This is jQuery, but it could be anything
- $.getJSON('http://example.com/add.php?a=2&b=2', function(response) {
- doSomethingWith(response.sum);
- });
Now all your components are decoupled, but they can still access each other with a well-known interface. (You could also call sum() from another language in the same way if you wanted to, and everything supports JSON these days.)
If for some reason that approach won't work, you could do the same sort of thing with JSONP:
- <?php
- function add() {
- // ... work omitted
- echo $_GET['functionToCall'] + "($sum)";
- }
- ?>
- // Your Javascript
- function useSum(sumFromServer) {
- // Do something with it
- }
- <!-- In your HTML: -->
- <script src="http://example.com/add.php?a=2&b=2&functionToCall=useSum"></script>
----
[1] Please keep in mind this demo code is insecure. In production, you'll at least want to filter the input.
You should certainly write your code in multiple files for easier management. You can decide, depending on how many files you have, to build them into one or more files that you distribute to customers. Check out tools like webpack and browserify to do the concatenation. These tools support modular syntax which I would recommend when dealing with a lot of files.
Usually you would use PHP files, HTML files and JS files in separate files and put the HTML code that you use inside the PHP files as templates that are also external.
You can put everything into a single file, PHP file contains HTML and HTML contains JS, but that is not very good style if you want to keep your overview
I'm going to say no, importing it will always be better. It's easier to read both files, easier to debug, and you'll get much better error checking depending on your ide.
Also always put your js at the bottom of your body, so that the html loads first, or use defer
Yes you can have 2 Document Ready Function in your jQuery code but they serve no purpose at all. You just need one document Ready Function and put all you jQuery codes there.
The Document Ready Function can have 2 types of syntaxes:
- First one
- $(document).ready(function() {
- alert('DOM is Ready');
- });
2. Second One
- $(function() {
- alert('DOM is Ready');
- });
Also check this:
Kind Regards,
Naina
Senior Web Developer
In the separate js file you are only changing the variable `text` and not updating the element's value. You are updating the element's value in the online code.
I will answer to this question in two sections :-
- If you are new to learning front-end (HTML, CSS, JS)
- If you have decent knowledge of front-end(HTML , CSS , JS)
Case 2 : If you have decent knowledge about HTML , CSS and Js , its better to have separate files for each of them , because you can edit fast , better usability and debugging becomes fast.
Case 1 : If you are learning HTML , CSS and JS for the first time and you have short codes to write and experiment with it , then keep them in one file because you can search for errors easily and you can play with the code.
But after you have developed
I will answer to this question in two sections :-
- If you are new to learning front-end (HTML, CSS, JS)
- If you have decent knowledge of front-end(HTML , CSS , JS)
Case 2 : If you have decent knowledge about HTML , CSS and Js , its better to have separate files for each of them , because you can edit fast , better usability and debugging becomes fast.
Case 1 : If you are learning HTML , CSS and JS for the first time and you have short codes to write and experiment with it , then keep them in one file because you can search for errors easily and you can play with the code.
But after you have developed a decent knowledge of these things then upgrade yourself to Case 2 as it is recommended.
There are two ways to do this in the browser.
The “old” way is to source both files in your HTML and have the first file define an object in the global scope. Then, the second file can access this object and all its properties and methods.
The more modern approach is to use a build tool like webpack to bundle your scripts together. This way, you can import specific dependencies into any file and use whatever the files export. This is what most larger apps do because it makes keeping track of things simpler.
You should write and organize your code in a way that is readable and well organized. In that light, this means smaller and specialized code snippets. Some frameworks help you in setting up a basic scaffolding that guides in this organization, however it is up to you to adhere to it and ensure that it is well organized and readable. The one rule I follow is:
Write your code as if you are presenting it to another developer/colleague
As a result, your code should tell other developers:
- What work is being performed
- Semantic comments
- Semantic naming of variables and functions
- Proper abstraction of ser
You should write and organize your code in a way that is readable and well organized. In that light, this means smaller and specialized code snippets. Some frameworks help you in setting up a basic scaffolding that guides in this organization, however it is up to you to adhere to it and ensure that it is well organized and readable. The one rule I follow is:
Write your code as if you are presenting it to another developer/colleague
As a result, your code should tell other developers:
- What work is being performed
- Semantic comments
- Semantic naming of variables and functions
- Proper abstraction of services and API
All this is pointing to smaller code snippets/files. There are several tools like Webpack, Browserify, and Gulp that help in minifying and packaging your code in a single file for production.
You can use JavaScript code in two ways.
- You can either include the JavaScript code internally within your HTML document itself.
- You can keep the JavaScript code in a separate external file and then point to that file from your HTML document.
You are using wrong event as one click in should be changed to correct event which is onclick.
Find here the correct code :
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>
There are two flavors of errors.
Errors of commission; where you do something wrong.
Errors of omission; where you don’t do something that is required.
Most likely you have an error an error of omission
I have blogger blog on which i want to show ad network ad code which is given below. I have added this javascript code to html widget but ad is not shown. I tried this same code on my wordpress blog where it is working fine.
- <div class="div11" id="b25f9e9f1760c4f82da91fda4c5669dce"></div>
- <script>
- (function(d, w) {
- if (!w.adnet) {
- var s = d.createElement("script");
- s.type = "text/javascript";
- s.src = "//domain.com/loader.js";
- d.getElementsByTagName('head')[0].appendChild(s);
- w.adnet = {host: '//domain.com'};
- }
- })(docu
I have blogger blog on which i want to show ad network ad code which is given below. I have added this javascript code to html widget but ad is not shown. I tried this same code on my wordpress blog where it is working fine.
- <div class="div11" id="b25f9e9f1760c4f82da91fda4c5669dce"></div>
- <script>
- (function(d, w) {
- if (!w.adnet) {
- var s = d.createElement("script");
- s.type = "text/javascript";
- s.src = "//domain.com/loader.js";
- d.getElementsByTagName('head')[0].appendChild(s);
- w.adnet = {host: '//domain.com'};
- }
- })(document, window);
- </script>