Why there are two different Javascripts? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am learning JavaScript, but the tutorial are kind of different depending on the resources. It looks like the JavaScipts are different, there is like 2 types of it.
So, let's say if we take one source, they have a code like this:
<html>
<body>
<p>Before the script...</p>
<script>
alert( 'Hello, world!' );
</script>
<p>...After the script.</p>
</body>
</html>
But when I do tutorial, on Codecademy , for example, they do not have any html code, no body, p, script... the code does not go into html. Functions like alert, onclick are very popular and, in fact, the w3schools begins with these functions, where on Codecademy there are no such things. And this code line
document.getElementById('demo').innerHTML = Date();
it says it is important in javascript, but codecademy does not mention it at all! Like what are those document dot getElementById('demo').What is it doing? Why it is everywhere on w3schools, but not on Codecademy, if it is so important? I finished whole JavaScript course on Codecademy, but I am still confused how come it is so different?
I learned Python before and it is similar to proper JavaScript (I call proper JavaScript the one, that is on Codecademy, because the structure is just like Python)
So the weird JavaScript (the one that is on w3schools, etc. and not on Codecademy) often has dollar sign, lines like this
function $(x) {
return document.getElementById(x);
}
The proper JavaScript use dollar signs only with string interpolations and that's it and the whole Codecademy tutorial does not have this all weird code that I provided above, which seems really important on other web sources.
All the YouTube tutorials I found are also using proper JavaScript, just declaring variables, writing functions, like, normal programming language, like Python, but what's with all the HTML tags, alerts, onclicks, dollar signs, etc., that are in tutorials like w3schools? Can please someone explain me?
Yes, I'm embarrassed a lot. To think of that I know Python and JavaScript on higher than beginner level, but I cannot figure out what's with the different code and what is happening...
P.S. Thank you everyone for answers. I probably wasn't clear, but I didn't wanted you to explain what actually those code lines, that I posted, meant (like most of you did), but mainly I wanted to know how come it's so different, why is that difference, why two different types of JavaScript? Hence, I accepted the appropriate answer.

document.getElementById is part of the DOM API, it's not part of JavaScript. If you want to interact with webpages you need html that is parsed and "converted" into DOM tree like structure. For example document don't exist in Node.js (server side JavaScript) but there is library that allow to use if you want to test your front-end code.
<script> tag is a way to add JavaScript files to html page. But you don't need html page to use JavaScript (you can use Node.js that I've mentioned).
and about this:
function $(x) {return document.getElementById(x);}
$ is normal variable and function name, it's legacy for Prototype and jQuery libraries that used this for their API main entry point and it's very short and clean.

The one on Codecademy mostly deals with server-sided Javascript, read up on NodeJS if you want to know more about it.
The other one with document.getElementById() and such is client-side Javascript and it gets executed by you or anyone who visits the webpage (so the client) inside of the browser.
NodeJS on the other hand doesn't run in a browser and doesn't have a global document or window because of that. You can use it to make a webserver (check out Express) or use it for other stuff in the same way you would use other languages like for example Python.
Both of them are still the same Javascript but they run in a different context.
The dollar sign is pretty typical jQuery syntax, it's just a framework for Javascript where they decided to use $ as variable name (which is allowed) so you could easily see it's a function from jQuery. There's nothing preventing you from using $ yourself in variable names, not in NodeJS and not in the browser.

There are arguably more than 2 even!
Javascript was developed to work inside the browser, in the context of the DOM, but it is also a programming language independent of any browser, of any HTML, of any DOM.
In HTML, <script> tags are for javascript, but you can also link to javascript files.

the <script> tag is just a html element which declares the content of this block to be javascript.
the content will be executed by the browser inside of the scope of the DOM.
in a javascript application you do not code javascript directly into the DOM, instead the JS files will be included/injected into the page.

When you see getElement usually its trying to find an element from DOM tree, in your case it's trying to find and element with the id demo.
Would find something like this
<div class="container">
<p id="demo"> </p>
</div>
For the code document.getElementById('demo').innerHTML = new Date() this would get the date and set it to your HTML #demo node.
As for function $(x) {return document.getElementById(x);} this function is trying to copy jQuery funtion of selecting DOM. Its does the same thing as the above code but you type alot less once its declared.
function $(x) {
return document.getElementById(x);
}
$('demo') // finds all nodes that have #demo in your DOM tree
In your HTML snippet using <script> before and after a tag means that you have or not to wait for the document to load. DOM tree loads from one node to the next and when you load a JS file or script, it gets instant loaded and fired, unless its told no to using events and conditions.
<html>
<body>
<p>Before the script...</p>
<!-- This element exists in your DOM tree already so you
don't really need the document to load. -->
<script>
alert( 'Hello, world!' );
</script>
<p>...After the script.</p>
<!-- This element is added after the script so if you run
the code above trying to find this "p" tag you would need
to add a proper window.onload event -->
</body>
</html>

Related

Is it safe to remove javascript source?

I found a way to hide javascript source using jQuery by using this script.
<script type='text/javascript'>
$(function(){$("script").remove()});
</script>
I tested creating variables, changing is value programmatically, calling functions, and ajax and so far it runs smoothly according to what it is intended to do.
I asked this question to prevent future damage to the web site I am currently developing.
Anyone who found out and using this method?
I found a way to hide javascript source
No, this does not hide javascript source code. It simply removes all <script> elements from the DOM.
Is it safe?
For normal javascript scripts, that have already been executed, yes. You could damage other functionality that uses script elements, like some templating engines, though.
I want to prevent future damage to the web site I am currently developing.
Don't damage it now! Omit this script.

How to use jQuery without making a mess? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I could expect short answers to be "just use AngularJS/Backbone/...(fill the blank)".
But I believe before I dive into those ultimately, there shall be alternatives and proper ways of getting things done.
So for now, I am using plain html, css, javascript and the only library I use is jQuery and some plugins.
Confession time:
these are the things that I found myself doing all the time and I really think these are "bad" and not "the right thing to do":
Use global js variable to hook things together.
eg.
$(document).ready(function(){
window.someVar = ...;
window.someFun = function(){...};
});
Need to bind all the event again after DOM manipulation, because it stops working after selecting some elements and putting it somewhere else.
eg.
$(".myElementWithSpecialActionHandler").click(function(){});
after the element was relocated, say insert to a different position of the page, the event handler function stops working. So I have to do
// after DOM manipulation
// again >.<
$(".myElementWithSpecialActionHandler").click(function(){});
Js code is dumped into one giant "main.js" file.
css code is dumped into one giant "main.css" file.
I use <tag onClick="someFunction(); ...> here and there because of issue "2." sometimes.
I use inline css here and there.
I am a noob. But I am deeply uneasy writing all these code and yet I am not quite clear how to "make it right". I don't this is an ideal question in SO, but I think this is quite common for new developers. So the answers would benefit a lot of people.
Any enlightenment, web links, pointers to good source, help, and critics are greatly appreciated!
Yours sincerely,
A noob with good taste=> therefore he is disgusted with his own code :(
I don't think there are correct answers to any of these question, but preferences/opinions
1) I don't like adding variables to global scope, so window.someVar is a wrong practice because there can be accidental manipulation of a value by another non relevant scope. If you are using jQuery the need for global variables are very less. If you find yourself using it many times then you may have to rethink about the solution
2) You need to look at event delegation instead of binding event handler after creating new elements. Assuming you are adding new input elements to a div with id x then you can do the below in dom ready handler instead of binding it again and again
$('#x').on('change', 'input', function(){})
3) I normally uses a single js file for my script, so that it can be properly cached
4) same as the script file
5) In string literals I use ' as the enclosing tag so that I can use " inside for html attributes like var x = '<div class="someclass"></div>'.
6) I normally wouldn't use inline css, As much as possible try to separate style info from the html markup
Just to get it out of the way, you can definitely profit from using some sort of frontend framework. I like jQuery for small things that need to directly manipulate the DOM.
1) some of this is unavoidable. JavaScript is built on global variables. Even Douglas Crockford acknowledges this in "JavaScript: The Good Parts". Just try to keep it to a minimum. Look at patterns to contain things, such as immediately invoked function expressions.
3) Try to find ways to split things up then use something to concatenate and minify it. That said, I'm guilty of bunching things up too much too.
4) There are good reasons to split things out. Your CSS reset can be in its own file. Site-wide layout in another file. Page specific stuff can go into their own files. Templating languages can help you subdivide a page into functional pieces that can have their own CSS files.
5) I didn't know that this was a problem honestly. I've seen plenty of people use single quotes around JS strings.
6) Good for hacking, bad for long term. Just add another class (or id if appropriate). You could put it in a shame.css: http://csswizardry.com/2013/04/shame-css/

live code examples: cytoscape.js initialization -- incomplete?

Being brand new to cytoscape.js, I may be missing something obvious. Please forgive me if that is so.
I am studying the first example offered here:
reached from this page
Three files are offered -- HTML, CSS, JavaScript -- along with the impression that these three will, when loaded into my browser, create a running example.
But the HTML seems to be incomplete, possibly in two ways:
the JavaScript on the jsbin page needs to be included via a script tag
the variable cy is not defined anywhere that I can see, leading to this error message in the console: Object #cy has no method cytoscape
A stack overflow search on that error message points back to the very fine cy.js documentation, but alas, I am still in the dark: where do I initialize the "cy" object?
And best of all, where can I find a complete working example, useful for such a raw beginner as myself, something I can pore over and study until I begin to grasp the logic of this style of programming, and make use of this very fine library?
Thanks!
Your first example is indeed a fully working example. Just use the menu to the top left. Choose File -> Download. This will download a single HTML-file, that works out of the box.
The file is called jsbin.ravecala.1.html. Open with
firefox jsbin.ravecala.1.html
(I also struggled a while before realizing this.)
I really don't know what's your JavaScript & jQuery knowledge level, but it seems you may need to practice it all a little.
Yes, if you're referring to the following tag:
<script src="http://cytoscape.github.io/cytoscape.js/api/cytoscape.js-latest/cytoscape.min.js"></script>
This is indeed necessary, as it is the basis of cytoscape.js, the library itself, wich allows, for instance, add the method cytoscape to the variable #cy, as you mentioned in your second point.
The variable #cy is the div itself. jQuery refers to objects IDs this way, with #. So:
<div id="cy"></div>
Can be referred as $("#cy"). Wich adds the cytoscape function to it is the library itself.
I think that this live example is really good, although the one you linked is more basic and appropriate to get known with the basic structure and initialization of cytoscape.js. I suggest you to get known with jQuery (this course was really clear to me) and read the cytoscape.js documentation, which is full of rich examples.

How HTML, JS and CSS work together

I would like to understand how HTML, JS and CSS work together and reference one another.
I have found that HTML can reference CSS via an id reference.
Example: <div id="left-show"></div>
However, it would be much appreciated if someone could clarify the following:
How would you tell your HTML code to reference a specific JS function.
Within a JS function, is it a good practice to reference a CSS id?
If a JS function and CSS id share the same name, would that create a conflict?
How would you tell your HTML code to reference a specific JS function.
Generally, you don't.
You include a script (with a <script> element) that accesses whatever parts of the DOM you want it to interact with (via the document object that the browser will make available to the script).
You can use the addEventListener method to bind a function so that it will run in response to an event (such as a button being clicked).
Within a JS function, is it a good practice to reference a CSS id?
There is no such thing as a CSS id. HTML has IDs which have a multitude of purposes including being matched by CSS ID selectors, being linked to with a fragment identifier on the end of a URL and allowing a <label> to reference its associated form control with the for attribute.
If you want to access a specific element, then an HTML ID is a good way to identify it (via the getElementById method).
If a JS function and CSS id share the same name, would that create a conflict?
There can be some issues if JavaScript variables of any kind (including functions) match the ID of an HTML element. This is best avoided by staying away from the global scope as much as possible (as per this answer).
Your questions are a bit far-reaching for a full explanation on a concise Q&A site like SA. You would really need to read a lot of material for a full understanding.
However, some brief simplified answers to get you started
1) HTML links to JavaScript via events that trigger JavaScript functions. This is an example of a very simple event on an HTML element that will look for a function in your JavaScript declared as function aJavaScriptFunction(){ } when you click on the button. There are different ways to do this and different types of event, but this is a good place to start.
<input id="thebutton" type="button" value="A Button" onclick="aJavaScriptFunction();" />
2) It very much depends what you are trying to do, but in general selecting HTML DOM elements via their ID is an efficient method of selecting them to do something with them. So this might be the JavaScript function that we're using in the previous example.
function aJavaScriptFunction()
{
var aButtonElement = document.getElementById("thebutton"); // <-- It's not a "CSS id" as such, CSS can use the HTML id
// .... some more javascript that uses aButtonElement like
aButtonElement.style.borderColor = "red";
}
3) No. JavaScript and CSS don't really directly overlap as such in the way you might be thinking, when you're beginning, think of them both as altering the HTML. It is possible to do some of the same things with JavaScript as CSS, but in general they happen at different times. This CSS doesn't conflict with the previous JavaScript, though they both do similar things.
#thebutton { border-color: blue; }
Here are all my examples put together into a jsFiddle where you can play with them.
You'd be best off visiting somewhere like W3 Schools or Code Academy.

Are HTML comments inside script tags a best practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
The following practice is fairly commonplace in the inline JavaScript I have to work with:
<script type="text/javascript">
<!--
// Code goes here
//-->
</script>
I know that the point is to prevent browsers that are incompatible with JavaScript from rendering the source, but is this still a best practice today? The vast majority of browsers used today can interpret JavaScript; even modern mobile devices usually don't have trouble.
As for the 'why not?' question: I recently had to spend several hours debugging an issue where someone had left off the '//' in front of a '-->' at the end of a script tag buried deep in some pages, and this was causing mysterious JavaScript errors.
What do you do? Is this still considered a 'best practice?'
The important thing is that nowadays, whether a particular browser supports JavaScript or not is irrelevant (clearly the great majority do) - it is irrelevant because almost all understand script blocks, which means that they know to ignore the JavaScript even if they can't interpret it.
Matt Kruse gives a slightly more detailed explanation on his JavaScript Toolbox site for why specifically not to use HTML comments within script blocks.
Quoted from that page:
Don't Use HTML Comments In Script Blocks
In the ancient days of javascript (1995), some browsers like Netscape 1.0 didn't have any support or knowledge of the script tag. So when javascript was first released, a technique was needed to hide the code from older browsers so they wouldn't show it as text in the page. The 'hack' was to use HTML comments within the script block to hide the code.
Using HTML Comments In Script Is Bad
// DON'T do this! Code is just representative on how things were done
<script language="javascript">
<!--
// code here
//-->
</script>
No browsers in common use today are ignorant of the <script> tag, so hiding of javascript source is no longer necessary. In fact, it can be considered harmful for the following reasons:
Within XHTML documents, the source will actually be hidden from all browsers and rendered useless
-- is not allowed within HTML comments, so any decrement operations in script are invalid
I've stopped doing it. At some point you just have to let go of your NCSA Mosaic.
As per W3C Recommendation it was mainly useful to hide the script data from USER AGENTS.
Quoted from the W3c page :
Commenting scripts in JavaScript The JavaScript engine allows the string "<!--" to occur at the start of a SCRIPT element, and ignores further characters until the end of the line. JavaScript interprets "//" as starting a comment extending to the end of the current line. This is needed to hide the string "-->" from the JavaScript parser.
<SCRIPT type="text/javascript">
<!-- to hide script contents from old browsers
function square(i) {
document.write("The call passed ", i ," to the function.","<BR>")
return i * i
}
document.write("The function returned ",square(5),".")
// end hiding contents from old browsers -->
</SCRIPT>
No, it is a hangover from a workaround used when the script element was first introduced. No browser fails to understand the script element today (even if it understands it as "Script that should be ignored because scripting is turned off or unsupported").
In XHTML, they are actively harmful.
I wrote something about the history of it a while back.
Stopped using this a while back. Also, according to Douglas Crockford, you can drop the type attribute from your script tags since the only scripting language available in most browsers is JavaScript.
I would recommend using a CDATA section, as described in this question.
If you are typing manually, I suggest you always use external js files, that would help so much.
Regarding your concern: most browsers are JavaScript safe today. However sometimes people may write simple parsers to fetch a HTML directly - and I must say, the safe quote is really helpful for those clients. Also some non-JS clients like old Lynx would get benefits from this.
If you do not include literal text between script tags- that is, if you load scripts from src files, you can forget about the comments.
I stopped doing that ages ago. You really don't need it in this day and age.
I don't do it but the other day I went to validate my password protected site at w3c. So I had to use their direct input method. It complained about my javascript, so I put the comments back in everything was fine.

Categories