Separating jQuery code from HTML - javascript

I'm trying to clean up my code so I'm putting all the stuff in my
<style></style>
In a CSS file. And I'm trying to do the same for my jQuery. So I created a Custom.js file. But do things like:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Stay in html file or can I move them the Custom.js file? Also, I'm using a jQuery plugin called uscrollbar so I have this piece of code in my html file:
<script>
$(document).ready(function(e) {
$('#scroll_form').uscrollbar();
});
</script>​​​​​​​​​​​​​​​​​
Can I also move that to Custom.js?

A much better question.
It's best to keep links to external scripts in your HTML, it's perfectly fine to have a few <script> tags. Especially ones using a CDN!
You can move your document.ready() function to external JS, where all of your other JS is kept. But sometimes it's easier to include small snippets like that directly in pages where it concerns only that page.
When moving things to separate files, it's important to include them in the right order.
Usually something like Modernizr at the top (<head>), with jQuery near the bottom (just before </body>), followed by your plugins, followed by your custom scripts.

Check out RequireJS, it gives you a super simple way to include javascript files as you need them, rather than stuffing your header / footer full of tons of <script> tags.

Keep your references to Javascript files (local or remote) in your HTML code. Place them at the bottom of the page before the closing body tag if they do not need to be ready until the DOM is ready. For instance, your jQuery reference should almost always be in your 'head' section because any references to jQuery while the HTML loads need to be defined even though functions that aren't called until after document is ready do not need to be defined. Many other supporting files like 'jquery.easing' for instance, can go at the bottom which improves page load times.
You can move the uscrollbar() call to a .js file, but I would recommend putting all of your "ready" commands in one function, and then in your HTML simply call that function on ready. IE:
<script type="text/javascript">
jQuery(document).ready(function() {
fn_LoadFunctionName_Thats_InYour_Custom_js_files();
});
</script>
Don't forget to include type="text/javascript" in your script tags.

If you're using custom js that's more than just one little function call, I'd separate into a new js file and just call that in your <script> tag. Same with css. If you're changing styles with your jquery, then usually I use addClass, removeClass, and toggleClass to modify my styles. That way you don't lose track of your styling from css to js files.

You can certainly move them to Custom.js file. Just make sure you have included the file in your html file as you've included the jQuery library.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="Custom.js"></script>
Just make sure the path for Custom.js is correct. Also, you don't put script tag in the js file. So the Custom.js would be:
$(document).ready(function(e) {
$('#scroll_form').uscrollbar();
});

Related

Why my script.js file doesn't work but the JavaScript code inside of the index.html file works?

When i add this:
<script src="script.js"></script>
<script src="jquery-3.5.1.min.js"></script>
to my index.html file in the head of the file, and i create a JavaScript file, it looks like the html doesn't recognize it.
But when i add this:
<script type="text/javascript">
//code
</script>
to my index.html file in the body of the file, all of the code i done in JavaScript works.
Can somebody explain why this happens?
It’s always a good practice to add jQuery code just before the closing </body> tag. If you have not done that, then use the defer attribute.
Also if you’re writing jQuery code make sure that your code is placed after the jQuery link code.
Don't add your JS files in the head. You are most likely going to be accessing DOM elements, and those elements are defined in the HTML. If you insert a script above the html, the elements won't be recognized because they're not defined yet. Add all of your scripts after the body, I add mine after the closing html just to be safe. And please add your script after your jQuery script.

Javascript for Responsive Menu in Wordpress

sorry if this is a basic question but I'm having trouble figuring out how to use a Javascript/jQuery script in my website. (If this is well documented and I just don't know the right terms, please share what to look for - I've had no luck yet online with what I know.)
I'd already designed a site with static pages, it just didn't have a blog. So I put Wordpress in for one of the pages, and figured out how to add in the HTML/CSS design for my existing site's menu using the header.php and footer.php files. However, my jQuery script that's supposed to load when the page is resized in order to change the menu design is not working.
I pasted the <script type="text/javascript" src="jquery.min.js"></script> code in the <head> part of the file, adjusted the body tag to <body onresize="myFunction()" <?php body_class(); ?>>, and added the "myFunction" script to the footer.php file, above the </body> tag. Above function myFunction() { I also have window.onload=myFunction(); which isn't working either - so no matter what size the page is loaded at or what size it's changed to the menu is unresponsive.
When I tried adding an enqueue code block to the functions.php file it broke the page entirely, giving a 500 error.
Any advice would be hugely appreciated!
Check that the path you specify to the jQuery library is correct. In your script tag src="jquery.min.js is a relative path. This means that the file jquery.min.js is in the same directory as your html/php/template according to your src path.
I would recommend using a CDN. You won't have a relative path, need to load your jquery files, and you'll benefit from browser caching if other pages/sites have loaded the same files.
3x
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
2x
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
When you add resources such as scrips and style sheets to WordPress you should enqueue them using the functions wp_enqueue_script() and wp_enqueue_style().
Doing this ensures that your scirpt/style is only included once, allows you to declare dependancies, and (in the case of scripts) allows you to add it to the footer should you require/desire.
You can find more information on these functions in the Codex -
wp_enqueue_script()
wp_enqueue_style()
In conjunction with these functions, you should use the wp_enqueue_scripts action, ensuring that your scripts styles get enqueued at the correct time.
So for example, you should place something similar to this in your functions.php file. Because jQuery already exists within WP, you don't even need to specify a location, you just tell WP that you want to enqueue it -
add_action( 'wp_enqueue_scripts', 'my_enqueue_jquery' );
function my_enqueue_jquery(){
wp_enqueue_script( 'jquery' );
}

Where to insert JavaScript Libraries and CSS in my HTML code?

I am little new to web development and when I was searching internet about other topics, I have seen many people has put popular JS Libraries in Different Places of their websites.
eg: Inserting JS Libraries on the Very Beginning or Start of the <head> </head> section. (Before loading any JS Code or a CSS File)
eg: Inserting JS Libraries on the End of the <head> </head> section. (After loading all JS Codes and CSS Files)
eg: Inserting JS Libraries on the End of the <body> </body> section. (After loading all JS Codes, Texts, Images, Videos, CSS Files etc...)
So my question is this.
What is the best practice for inserting (where) following JS Libraries, Plugins and CSS Style Sheets to a web page for the most faster loading times and other advantages? - Please mention the reason -
JQuery and it's Plugins
Bootstrap 3.js
Modernizr.js
Angular.js
And another widely used JS Libraries which I couldn't mention here...
Normalize.css
reset.css
bootstrap.css + more
Thank You..!
There is no so called "standard" method. The choice of where to put the lines boils down to one question: When will I need the library?
You see, web files loads line by line, let's take the following as an example of what I mean:
<script>
document.getElementById("target").innerHTML = "changed"
</script>
<p id="target">unchanged</p>
#target isn't altered because the script was loaded before the element did. Web files loads procedurally. When the line of JavaScript is loaded. It is executed immediately, but the target element isn't. So it couldn't change the element.
Even with jQuery, there is the same problem:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("#target").text("changed");
</script>
<p id="target">unchanged</p>
Therefore, we often use $(function(){}).
Back to the loading problem
People who put their <script> tags or <link> tags in the body (in front) or in the head, wanted to execute the script immediately, sometimes they won't use $(function()) or document.onload
People who put their <script> tags or <link> tags in the body (in the end) wanted to ensure all elements are loaded then execute the script or load CSS.
Conclusion
You should load independent resources such as jQuery first, then load dependent resources such as jQuery plugins. Then you try to decide when you want the resources to start loading, then put the lines in places.
You should put CSS links in the <head> tag because you don't want visitors seeing unstyled content before loading the CSS files.
If you can't decide or don't care about the time, put every <script> and <style> tags in the <head>.
Here is another post you might be interested in: Load and execution sequence of a web page?
CSS can added inside header tag & but put all JS Libraries and custom files just before closing closing body tag
<body>
//other tags
<script> All Scripts here </script>
</body>
By doing so you wont have to check if DOM content has loaded.
It decrease page loading time.Otherwise a js need to be completely loaded before DOM loading.
It also makes sure that all events are attached properly to DOM element.
I think this address all your concern specially the third one
CSS Sheets go in the < head >. The order of the CSS files matter so libraries should be put in first then you can put in the specific ones you have.
Javascript links go in the < body > but place them at the very end. That way your HTML content loads first then the JS loads and it will recognize all your selections. It is more efficient to do it this way.
The most important thing to note when placing your css and script tags is that the order you place them determines the order they are loaded in and if style or code is loaded later it over writes the code written before. So if you have css styling that assigns different styles to the same attributes of the same element then it is the one loaded later that takes effect. And with script tags it's important to remember that for dependency reasons. You should load the dependencies first so that they are there for the other scripts to use. Aside from that normally css tags are in the head and script tags at the bottom of your body element

JQuery loading inside html file but not in linked javascript file (JqueryUI tabs)

I'm currently having a weird problem.
I'm using JqueryUI tabs, and am loading php pages with each tabs. This works well for me, but what I am trying to do, is loading another php page from within one of those tabs with the html "a" tag. For some reason, it doesn't work when I place the click function in a already linked javascript file, but works when I place the code in a script tag directly in the html file.
Here is the function:
$(function(){
$('a.commandsRecep').on('click',function(e){
e.preventDefault();
window.open(this.href,'','width=700,height=700');
});
})
I know that loading pages from within a tab is done by Ajax and am wondering if that's what causing me problems.
The link is inside a table :
<td><a class="commandsRecep" href="./Ben_test/page_principale.php">Réception des commandes</a></td>
What is the order of includes?
Make sure that jquery is included before javascript file.
The order should be like :
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="yourScript.js"></script>
Found it!
After a while, I got to the same type of error.
What I had to do was separate my script in two parts, one that required jqueryUI and one that didn't.
That way, in the html files where I don't import jqueryUI, I only import the one that doesn't require it.
Looks like having jquery that required jqueryUI without having imported jqueryUI was stopping the script from executing.

Where do I put the $(document).ready()?

I've been trying to add JavaScript to my HTML/CSS, but been running around in circles.
My current set-up is where the html, CSS, and JavaScript files (2 files; my JavaScript code, and jQuery's code) are all separate, but linked to each other via the html page.
So here are my questions:
1) Do I put the link to the jQuery code within the html head? Or within my JavaScript code page?
2) Where does this code go? The html page, or my JavaScript page?
$(document).ready(function(){
//Code here
});
3) Above, by 'code here', they mean JavaScript code, right? Not my html code?
4) I've read about initializing JavaScript code at the bottom of an html page. From what I take though, I don't have to do that with jQuery's .ready function, right?
You should like to your JavaScript files either in the <head> or above the closing </body> tag.
The code can go anywhere really, but I would suggest an external JavaScript page.
Yes
This is correct.
When Javascript code is executing in your browser, all of your included Javascript files and any code you write in-between those "script" tags in the HTML document is going to be executed as though it were all part of one giant file (same namespace). So in some sense, it doesn't matter whether you write your code in the HTML document or whether you write it in an external file that you include - you're free to do either, and it will be executed the same. You can balance maintainability, reusability and convenience (think about what functions you write that you might want to reuse on other pages) and do whichever you feel is best.
To make this concrete - this is one valid way to write your Javascript, if you wanted to write the code inside your HTML file:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert('Document Ready!');
});
</script>
</head>
<body>
...
Here's the intro at the jQuery site, for reference:
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
Writing your Javascript code at the bottom of the HTML page was/is a technique for getting it to execute as soon as the document is loaded, which is unnecessary when using jQuery's '$(document).ready' (that's what it does - it abstracts the business of getting Javascript functions to execute on page load, and implements it in a cross-browser way).
See: Introducing $(document).ready() for more.
It doesn't really matter where you place your jQuery code. If you place it in the head tag, it'll automatically load everything. If you decide to place it all in an external JavaScript file, you need to link it with a <script type="text/javascript" src="my_file.js"></script> tag.
The 'code here' part is only for JavaScript. What the code is saying is that when the document is ready, run this function. The function can be whatever you like - whatever you put inside the function will run when the document is ready (i.e. when the webpage is called by the browser).
You don't need to insert it at the bottom of the HTML page - you can do it anywhere. People only insert it at the bottom to optimize their loading speed. It's nonessential.
$(document).ready(function(){
//Code here
});
goes in your javascript file. All javascript code that should be executed once the page has loaded goes where the //Code here comment is.
Perhaps a quick jQuery tutorial would be in order?
Or, you can put your script tag in the bottom of your body, and not have to use the $(document).ready() function.
Put in the head. This is the most stable way and it works. Some people may disagree and say it is slower, etc, but I have found this to always work.
Where you put your code is up to you. You can put in your head with a
<script>Code here</script>
or in a separate file and include it with
<script src="reftomyscript.js"></script>
Yes, put your javascript code in this, either in the head or in a separate file.
Yes, and see (1)

Categories

Resources