Can you create a dynamic javascript function and immediately call it?
I already found that you can't use the callback from append.
proposed, non working, code:
<script type="text/javascript">
var count=1;
$(document).ready(function(){
$(".main").append('
<script type="text/javascript">function init'+count+'(){alert("'+count+'");}<'+'/script>
');
window['init'+count]();
});
</script>
<div class="main"></div>
Edit:
Narrowed it down to a synchronization problem. Placing alert("") between append and window makes it work, but that is not really a useful fix because the count might go up to a 100 when I place this code in a loop.
Guess I'll have to keep looking.
That should work, but you aren't quoting correctly. There shouldn't be any unescaped double quotes within append(" and "). Try:
$(".main").append("
<script type=\"text/javascript\">function init'+count+'(){alert(\"'+count+'\");}<'+'/script>"
);
use an external script and $.getScript(), it allows you to specify a callback and makes your code a bit neater
$.getScript("http://scriptURL.com/script.js", function(){ itit(); });
Theres no point of inlining the code.. you could just run it in the same place you're appending the tags or use jQuery.globalEval();
Yes, you can! This is the way javascript was invented! It is extremely powerful:
<script type="text/javascript">
var count=1;
var init = [];
$(document).ready(function(){
(function (count) {
init[count] = function () {
alert(count);
}
})(count);
init[count]();
});
</script>
<div class="main"></div>
or, if you just want to construct and call the function without storing it ...
<script type="text/javascript">
var count=1;
$(document).ready(function(){
(function () {
alert(count);
})();
});
</script>
<div class="main"></div>
Related
<script>
function showAlert(){
alert('Bazinga')
}
$(document).ready(function(){
showAlert();
});
</script>
In my example I first of all declaring function and else calling this function when documents is loaded. But alert is now show.
Make sure you have included jQuery library , The script should be after the jQuery library.
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script>
function showAlert(){
alert('Bazinga');
}
$(document).ready(function(){
showAlert();
});
</script>
Fiddle
I think you forgot the ";" on alert, try adding ";". If that does not do the trick you could try move up ur document ready.
Here's a very simple question that my simple mind can't answer: why isn't the anonymous and onload function below being run when I load in the external library? I am missing something really, really basic. Library.js has only one line: console.log('library'). How much more basic can one get?
<script type="text/javascript" src='js/library.js' />
<script type="text/javascript">
(function () {
console.log('anon');
})();
window.onload = function () {
console.log('onload');
} ();
</script>
Your script syntax is invalid. You should have a separate closing tag instead of the self-closing version.
<!--------- v --------->
<script type="text/javascript" src='js/library.js'></script>
You also have an issue in that you're invoking the onload function immediately.
window.onload = function () {
console.log('onload');
}/* () */;
// ^^---remove these to assign the function instead of invoking it.
i'm trying this code:
<script type="text/javascript">
$('#ooo').click( function() {
alert("jadner");
});
<script>
prueba
I expected it shows the alert when i click on "prueba", but it doesn't show anything..
Regards
Javi
You need to bind the event only after the DOM finishes loading. Wrap your code inside $(document).load() event like this:
<script type="text/javascript">
$(document).ready(function() {
$('#ooo').click(function() {
alert("jadner");
});
});
</script>
1 - Make sure jQuery has been included.
2 - Make sure your click handler is in a $(document).ready(function() {...}); block.
See:
http://docs.jquery.com/Tutorials:Introducing_$(document).ready()
You have to either reverse the order of the tags, i.e. put the script after the link:
prueba
<script type="text/javascript">...</script>
or wrap the code in a $(document).ready() callback:
$(document).ready(function(){
$('#ooo').click( function() {
alert("jadner");
});
});
The problem: When your JS is executed, it tries to find the element with ID ooo which does not exist yet. Parsing is always from top to bottom. So the script gets executed before the link element is created.
Add return false; below the alert. and like Nanne says, make sure you've got jQuery loaded properly
should be </script> not <script>
use document.ready()
<script type="text/javascript">
$(document).ready(function(){
$('#ooo').click( function() {
alert("jadner");
});
});
</script>
prueba
Try the following code.
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script language="javascript">
$(function()
{
$('#ooo').click( function()
{
alert("jadner");
});
});
</script>
prueba
I've updated the script here to give a better example. For $header I've got an anonymous function now returning $("#header"). Although this works I'm sure its not efficient as it calls $header every time it's used - so its the same as just using $("#header") throughout the code.
What I really want is to store $("header") in a variable. When I try to do this with $header2 (below) it fails. #header is red not blue.
When I use firebug to output lib.page.$header2.selector is correctly displays #header. As you can see the script which calls lib.page.init is at the bottom of the DOM.
Any ideas?
<script type="text/javascript">
var lib = {
page : {
$header : function() { return $("#header")},
$header2 : $("#header"),
init: function() {
lib.page.$header().css("background","red");
lib.page.$header2.css("background","blue");
console.log(lib.page.$header2.selector);
}
}
}
</script>
</head>
<body>
<div id="wrapper">
<div id="header">
<em>Example!</em>
</div>
</div>
<script type="text/javascript">
$(function() { lib.page.init(); });
</script>
</body>
Because when you define $header : $('#header') that element is not available? and when you call lib.page.init it is? I am not sure when you call lib.page.init, but I bet it's in $(document).ready() right? And you define the object literal before the dom is ready.
Ok, your div#header is not available by the time you want to assign it to $header, you have two options and I will show you the best option first. It's what I meant with 'put all scripts at the bottom'!
<head>
<!-- dont put scripts here if you can avoid it, it's bad! -->
</head>
<body>
<div id="wrapper">
<div id="header">
<em>Example!</em>
</div>
</div>
<!-- keep scripts at the end of the page just before the </body> tag -->
<script type="text/javascript">
var lib = {
page : {
// div#header is available
$header : $("#header"),
init: function() {
lib.page.$header().css("background","red");
}
}
}
// you don't need onDomReady anymore.
lib.page.init();
</script>
</body>
Another option if you want to keep scripts in the header, is to assign $header in your onDomReady call.
<script>
// create lib etc here
$(function(){ // this is an onDomReady call in jQuery
lib.page.$header = $('#header');
lib.page.init();
});
</script>
"This happens because the variables are instantiated at the time the script is interpreted.
So at the time of the parser gets to the script the $("#header") isn't in the DOM yet."
When i am trying to write the code like
document.getElementById('id1') after teh script tag it is showing document.getElementById(..) null or not an object..
Is it necessary to write document.getElementById('id1') in function only.
If i write this code in function then it is accepting. So what the mistake here..
and if i want to execute a function on loading of the page where to write onLoad() function.. i try to write at but it is not loading.. please help me
Thank you
In order to be sure that your dom element is loaded, you have to wait the document is loaded.
To do this you can do:
<head>
<script type="text/javascript">
function foo(){
var elem = document.getElementById("yourElem");
//...
}
</script>
</head>
<body onload="foo()">...</body>
or
<head>
<script type="text/javascript">
function foo(){
var elem = document.getElementById("yourElem");
//...
}
window.onload = foo;
</script>
</head>
<body>...</body>
If you want the script to run after the page is loaded, you can use window.onload.
<script>
window.onload = function () {
//code goes here
}
.
.
.
</script>
Put your script bellow the element you are getting will also work.
<div id="ele"></div>
<script language="javascript">
alert(document.getElementById('ele').tagName);
</script>
<div id="ele1"></div>
But unless you have special purpose, it's a good habit to write handlers in after document loaded, that is, put your code in window.onload event handler.