I have a problem, and I would like you to guide me to solve it if you do not mind ... In my HTML source code had several pieces of css codes here and there. So I decided to put together into a file called principal.css and do the following in the head section
<link href="css/principal.css" rel="stylesheet" type="text/css" />
This has worked wonderfully! My idea was to do the same with the javascript code in my HTML, but it has not worked. This is one of them:
$("[data-slider]")
.each(function () {
var input = $(this);
$("<span>")
.addClass("output")
.insertAfter($(this));
})
.bind("slider:ready slider:changed", function (event, data) {
$(this)
.nextAll(".output:first")
.html(data.value);
});
Is there some special way to do this? My goal is that the page has the least amount of code, I leave well indented, documented and clean. Greetings, I will await your answers in! Please, excuse my english...
You need to wrap this in $(document).ready(...)
Also, it has unusual indentation. It would probably be better to format it like this:
$(document).ready(function() {
$("[data-slider]").each(function () {
var input = $(this);
$("<span>").addClass("output").insertAfter($(this));
}).bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first").html(data.value);
});
});
I personally don't like chaining so many commands like this in a row. It might be SLIGHTLY more efficient, but it makes it much more difficult to debug and fix problems. I personally would break the .each() and the .bind() into separate statements. But I suppose it's a matter of preference.
.ready() documentation
$(document).ready(function(){
// your code here
});
or
.load() documentation
$(window).on('load', function(){
// your code here
});
Place your js
code in a separate .js
file. Similar to how CSS is also placed in a separate file and then link it to your html file.
like so, in your html file:
<script src="somejsfile.js"></script>
And yes, you have to wrap your js code in a document.ready function so it can execute when the documents elements are finished loading.
For example:
$(document).ready(function() {
// Your JS code here
});
This is because the browsers HTML
interpreter reads code from TOP to BOTTOM
, so if your not setting a document.ready
, the JavaScript
will run before any of your document elements are loaded
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With