I want to clear my code a little bit and I want to run my jquery code without any function call in the html file. My actual code is :
HTML:
<head>
<script src="js/colorpick.js"></script>
<script>
$(document).ready(function() {
colorpick_start();
});
</script>
</head>
JS:
function colorpick_start() {
...
}
But if I write for example an alert in the first row of the js without any function call, that works.
alert('test');
function colorpick_start() {
...
}
But this is not working for jquery selectors or something. Is there any solution to get my jquery working without code in the html file?
I want my html file to look like this, if this is possible:
<head>
<script src="js/colorpick.js"></script>
</head>
The
$(document).ready(function() {
Waits until the DOM is ready for selectors etc.
If you add the
$(document).ready(function() {
to your colorpick.js file it will wait for the DOM to be ready and then execute colorpick_start().
And believe me this catches out most people when they start using JQuery.
In order to achieve this:
<head>
<script src="js/colorpick.js"></script>
</head>
Move the document ready call to the js file you are referencing in your HTML file and make sure that the method called is present.
$(document).ready(function() {
colorpick_start();
});
This should so it.
Put your script
<script src="js/colorpick.js"></script>
before </body> tag. This will ensure that your page is loaded fully before script starts.
$(document).ready(function() {
colorpick_start();
});
this code is working because you are calling your function after document is loaded. document load is event. you can put your function on any event you want, but it wont start if you just define your function. You have to somehow call your function. example would be on click (or on document load)
<div id="example"></div>
$("#example").on('click', function () {
your function here
});
Use that code:
$(function(){
$('.colorpicker').val("colorpicker"); //or whatever you like
});
Plnkr example code
Related
I've looked all around stack overflow for answers to this same problem. Usually it's simple syntax errors like omitting a closing tag or not writing the src attribute properly.
I could've sworn, though, that my html and js is correct, but I still can't get the jQuery working.
The normal javascript (function test()) works perfectly as it's linked with an html button using onclick. The $('#click') jQuery simply will not work, though.
<head>
<script type='text/javascript' src='jquery-3.2.1.min.js'></script>
<script type='text/javascript' src='test.js'></script>
</head>
<body>
<button type='button' style='margin: 1em;' id='click'>CLICK</button>
<button type='button' style='margin: 1em;' id='testButton' onclick='test()'>TEST LINKING</button>
</body>
Both js files and the html are in the same folder.
And here's the js.test:
$('#click').click(function () {
alert('jQuery Works!');
}); //NOT WORKING!
function test() {
alert('Okay!');
} //WORKING!
The problem isn't linking jQuery, it's about scope and DOM loading.
When you create a function globally it becomes a global reference that you can access whenever you want afterward.
When you call a function, or change the value of a variable, it needs a scope to know when to be called. It's generally the global scope but, when you use jQuery functions, you cannot know if your libraries are already loaded and therefore if you'll be able to access the functions they provide.
Therefore, wrap your EH in a document.ready function that is executed by jQuery itelf when the DOM is fully loaded. You can do it this way :
$(document).ready(function(){
$('#click').click(function () {
alert('jQuery Works!');
});
});
Or in a shorter way :
$(function(){
$('#click').click(function () {
alert('jQuery Works!');
});
});
Ahh, the problem here is that when you load the JS and jQuery file, browser starts going through you code, finds that it should now bind a click handler for #click, but when it actually goes to find #click on the page it doesn't get it. Because it has not been added to the dom yet !
You have three ways to deal with this :
Use the defer attribute of the script tag. It is used to define script that will not run until after the page has loaded
<script type='text/javascript' src='test.js' defer></script>
Just load your JS for the event handler after the divs like :
<head>
<script type='text/javascript' src='jquery-3.2.1.min.js'></script>
</head>
<body>
<button type='button' style='margin: 1em;' id='click'>CLICK</button>
<button type='button' style='margin: 1em;' id='testButton' onclick='test()'>TEST LINKING</button>
<script type='text/javascript' src='test.js'></script>
</body>
This is why you normally see the line
Place CSS includes in the head and JS include just before the close of the body tag
That's because without CSS your page would look ugly untill it has been loaded, and placing JS in the end would make sure that the DOM is in place for any action to be performed on it
You can use the $(document).ready(function(){ ... }) event handler. This event is triggered when the document is ready or essentially when the dom has been created. Binding you click handler here makes sure that the elem is actually available for your JS to bind to
You cant define a function in a way like this. you need to do this
$(document).ready(function() {
$('#click').click(function() {
alert('jQuery Works!');
//declare other function
});
});
`
I have a layout file where i included Jquery just before closing tag.
//layout.handlebars
<!DOCTYPE html>
<html>
<head></head>
<body>
{{{body}}} // renders the body content
<script src='/js/jquery-2.2.4.min.js'></script>
</body>
</html>
I also have a page specific javascript(helper.js) that makes an Ajax call.
<div>Some sample data</div>
<script src="/js/helper.js"></script>
but the problem here is jquery is loaded at the end of the page but i am referring to it in the external javascript before jquery is loaded. which shows me '$' is not defined and i know that is obvious.
One solution to this will be like adding jquery to the head section but that is not what i want.
Is there any approach that i can apply to make an ajax call from external file without moving Jquery to head section.
Any help is much appreciated!!
Is there any approach that i can apply to make an ajax call from external file without moving Jquery to head section.
Yes, I assume you already understand the cause of the issue. As you see below the final content is ..
<!DOCTYPE html>
<html>
<head></head>
<body>
<div>Some sample data</div>
<script src="/js/helper.js"></script> <!--Jquery is not loaded yet, and hence $ is undefined -->
<script src='/js/jquery-2.2.4.min.js'></script>
</body>
</html>
As you already know one option is to move jquery anywhere in the HTML but make sure its loaded before any other jquery dependent files. Now since you don't want to take this option. we have another option.
Solution:
Our only aim is to make sure the jquery library is loaded prior to any other jquery dependent files.
We can get the files on document.ready using $.getScript()
$(function(){
$.getScript( "/js/helper.js", function( data, textStatus, jqxhr ) {
console.log( "Load was performed." );
});
});
Extras: If you feel this is a overhead and you cannot add this code to all the files in your page (since there can be too many files ), You can write a generic function and a global array variable , This function will check for file paths in the array and execute each one synchronously and remove from the array. Make sure this generic function is called in every document.ready event.
One Solution is that You can put the jquery script at the start of body tag before {{{body}}} section .. In this way your helper script will be rendered after jquery and your problem will be solved .....
Well its not pretty but you could use some kind of test and wait loop something like
<script>
(function test(){
if( window.jQuery ){
//your jQuery code
} else {
setTimeout(function(){ test(); }, 200);
}
})
</script>
Is there any way to load these snippets after full load of html?
I'd be very happy if loading the snippets after the js file (set to ASYNC load) or even set a timer.
<script>$(document).ready(function(){var modals = ['#bookings', '#studios', '#mygallery', '#social', '#reviews', '#articles', '#contactme', '#credits', '#pagemap', '#tsandcs', '#events'];if (window.location.hash && ~modals.indexOf(window.location.hash)) {$(window.location.hash).modal();}})</script>
<script>$(document).ready(function(){$("#myModal11").modal('show');});</script>
<script>$(".modal:not(.noclose) a").click(function(){$(this).closest(".modal").modal("hide");});</script>
You can try this Behaviour
Hope this helps !
<html>
<head>
</head>
<body>
// My Html Here
<script>
$(document).ready(function(){
var modals = ['#bookings', '#studios', '#mygallery', '#social', '#reviews', '#articles', '#contactme', '#credits', '#pagemap', '#tsandcs', '#events'];
if (window.location.hash && ~modals.indexOf(window.location.hash)) {
$(window.location.hash).modal();
}
$("#myModal11").modal('show');
$(".modal:not(.noclose) a").click(function(){
$(this).closest(".modal").modal("hide");
});
});
</script>
</body>
// And Remove this click function and use .on instead of it for single handler
$(".modal:not(.noclose)").on("click","a",function(){
$(this).closest(".modal").modal("hide");
});
});
You are putting them in a document on ready function,
$(document).ready(function(){$("#myModal11").modal('show');});
Just put the last one in that same on ready function and you're good to go
Although you could just put in them in one of those functions too:
$(document).ready(function(){
// put all code here...
});
i've seen the other posts in regard to this, but the following method is not working for some reason.
onclick="parent.testing();"
now for the full story. i have an index.html that houses all the JS files. also within the index, i have an empty 'div' tag. with jQuery, i'm appending a page1.html file to the empty 'div'. so the index kinda looks like this:
<html>
<head>
<script files>
<script>
ready { function testing(){do stuff;} }
</script>
</head>
<body>
<div><iframe src="page1.html" (added via jQuery)></div>
</body>
</html>
now in the page1.html file, i'm trying to call a function when a link is clicked. but i'm receiving the following error:
Uncaught TypeError: Cannot call method 'testing' of undefined
i've also tried the following but they didn't work:
onclick="window.testing();"
onclick="window.frames[0].testing();"
Your parent page script isn't valid JavaScript, but assuming ready { ... }:
<script>
ready { function testing(){do stuff;} }
</script>
...is a simplification supposed to represent a document ready handler you are declaring testing() as a local function within that ready handler so it can only be accessed from within that ready handler. You need to make testing() global in the parent page:
<script>
$(document).ready({ /* your on ready stuff here */ });
function testing(){ /* do stuff; */ }
</script>
...and then you should be able to call it from the iframe using parent.testing().
If I understand your question, your problem it's your function is not called, right? So maybe a solution is to put this in your "page1.html"
<script type="text/javascript" src="your_js_file"></script>
I am trying to load 2 javascript events/functions in the body onload as follows :-
<body onLoad="getSubs(document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value);getTags(document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value);">
Whenever I load using 2 functions the first one aborts - but if I just load the one it works fine - am I doing something wrong is it no possible to put 2 functions within the onload?
try this:
<html>
<head>
<script language="javascript">
function func1(){
//the code for your first onload here
alert("func1");
}
function func2(){
//the code for your second onload here
alert("func2");
}
function func3(){
//the code for your third onload here
alert("func3");
}
function start(){
func1();
func2();
func3();
}
</script>
</head>
<body onload="start()">
</body>
</html>
Multiple onload
Just do it from java script instead, one of the link shared into a comment explains well why it is best to use this approach over inline attributes.
<head>
<script>
document.body.onload = function() {
getSubs(...);
getTags(...);
};
</script>
</head>
<body>
...
</body>
I would avoid at all cost to have inline javascript, that is what you did in the code of your question: add javascript within an HTML attribute.
Best practice is to add your javascript in a separate file, see the related question on this principle What is Unobtrusive Javascript in layman terms?
So you'd have an other file called for instance "myjsfile.js", then you reference it from your HTML page
<script src="./path/to/your/myjsfile.js"></script>
Here is the answer to where to place this reference: Where to place Javascript in a HTML file?
Your "myjsfile.js" file would simply have:
window.onload = function(){
getSubs(...);
getTags(...);
};
Another thing to avoid: add javascript within the same HTML file. The reason is also based on the same principle of unobstrusive javascript. What is Unobtrusive Javascript in layman terms?
But I guess there are corner cases where you may want to do that.
If you really have to, do use window.onload instead of the inline javascript onload="...", see why here window.onload vs <body onload=""/>
Just add the following to your HTML file:
<script type="text/javascript">
window.onload = function(){
getSubs(...);
getTags(...);
};
</script>
Here is the answer to where to place this code: Where to place Javascript in a HTML file?
Note: Yes, in the same place as where you would put the reference to an external javascript file
Another thing: I do not know where your getSubs() and getTags() functions are defined. But if you want your code to work, it needs to call these functions after the file (or part of javascript) that defines them has been loaded.
In short: make sure the javascript file containing the definitions of getSubs() and getTags() is referenced before your code.
One thing that you could do is create a new JS function that accepts the document.form1.HotelID.options[document.form1.HotelID.selectedIndex].value parameter and call the two functions in the newly created function.
I tried calling two functions using the below code and it worked fine for me.
<html>
<body onload="callStart();callAgain();">
<script type="text/javascript">
function callStart() {
alert('First');
}
function callAgain() {
alert('Again');
}
</script>
</body>
</html>