I have looked at other questions similar to this, but I haven't found an answer.
My <body onload="doStuff()"> has stopped calling the doStuff() JavaScript function. I have tried replacing <body onload="doStuff()"> with <body onload="alert('Test');"> and that creates the alert successfully.
Then I tried putting that same alert just inside the doStuff() function (and reverting the onload to call doStuff()), but the alert did not appear.
Are there any reasons why this would happen? Also, it may be relevant to note that I am almost certain that I did not make any code changes in between this working and it not working (you may not believe that, but it's true); however, I did delete a sub-folder from the server that contained a Joomla installation.
Make sure that your script tag is correct.
<script src="myscript.js" /> will cause <body onload="...">...</body> to fail.
It should be:
<script src="myscript.js" type="text/javascript"></script>
Try to move away from inline calls and utilise jQuery as it was intended. Its really good working practice, (not to mention easier to debug) by keeping your style, and script logic separate.
for body on load, use this.
$(document).ready(function () {
doStuff();
});
or it can be shortened even further to
$(function () {
doStuff();
});
For whatever reason in firefox, my Scripts declared in the body of the page was preventing inline calls from firing. I moved my script tags to the header and then it worked.
The issue with the uncaught syntax error (see comments in original post) was that, when I was converting a PHP array into a JavaScript array, something was going wrong, i.e., a weird character was being appended. I solved this by replacing my DIY PHP-array-to-JS-array code with this code:
<?php
$js_array = json_encode($resultsArray);
echo "var jsResultsArray = ". $js_array . ";\n";
?>
This isn't really connected to the headline question of the post, but it was the root problem.
Related
As the title says (window.location.href not working when “isset['buttonname']” is occurring (php js)), my page is not redirecting to my new page that I want it to go to. I have tried using :
window.location.href = 'reviewer.php';
</script>
and have also tried using
echo "<script> location.href='http://gwupyterhub.seas.gwu.edu/~rkanungo/clout_computing/reviewer.php'; </script>";
Neither one of these scripts are being executed, and I insert them earlier in my code to see if they would even be executed and still nothing, even right after the initial if clause. Any suggestions?
I suggest that you try the Javascript document ready function with window.location.replace(), for example.
<script type="text/javascript">
(function() {
window.location.replace("https://example.com");
})();
</script>
Alternatively you can only use the window.location.replace() function if the above doesn't work.
The PHP header() function must be called before any actual output, for example "echo".
Sorry folks, I figured it out. Was simply not on the correct url while changing and none of my changes were showing up. Thank you all though!
I have been trying to change the background image of my HTML body with a .js but nothing happens. Do I need to put the Javascript code inside my HTML?
function plano1() {
alert('you');
$(document.body).css('background-image', 'url(img/planoSelected.png)');
}
This is the complete function I have been trying to do. Google Chrome shows the alert, but doesn't do the $(document.body). What am I supposed to do?
Notes: I use the function with a "onmouseover". I have already tried to use:
$('body').css('background-image', 'url(img/planoSelected_2.png)');
$("body").css('background-image', 'url(img/planoSelected_2.png)');
The jQuery code should be called at the bottom of the page, above the closing body tag.
Load jQuery first:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('body').css('background-image', 'url(img/planoSelected_2.png)');
});
</script>
The code is fine, but there are a few reasons why this might not work.
Make sure the image paths are correct, relative to the script's location
Is plano1 called?
Make sure jQuery is actually loaded
Make sure the DOM is ready when calling the function (use $(document).ready if not sure)
Make sure there are no errors in the code before plano1 is called
If these things are all right, and it still doesn't work, check if your onmouseover is working at all. Simply alert or log something in the console.
<form>
<a name='lala'/><a name='lala'/>
</form>
<script type='text/javascript'>
var elem=document.getElementsByName('lala');
alert(elem.length);
</script>
alert pops up 0!??
so that makes it next one not working!??
for(i in elem)
elem[i].addEventListener('click',function(){alert('lala');}, false);
many thanks!!
It is not working because by the time you call document.getElementsByName
the DOM elements are not loaded yet, therefore, your document.getElementsByName('lala'); will return null.
There are several ways to perform a function just when the DOM elements are ready. The simplest way is to create a function in your <head> and call it in the load event of your body
<head>
<script type="text/javascript">
function domLoaded() {
var elem=document.getElementsByName('lala');
alert(elem.length);
}
</script>
</head>
<body onload="domLoaded();">
....
</body>
When you placed the javascript function in the end of your tag, you just began to call the code when your elements where ready. That will work too, but isn't it better to do things the right way and place all your JS code in the head element? By throwing JS code all over the code is going to make you life hell when you need to fix things.
getElementsByName is not supported by all browsers, see here for all browser compatibilities.
It works for me, however. I am running Chrome 10.0.648.127
javascript code had to be included at the bottom of the page,
so that's why folks you should always put your js code to the bottom of the page.
many thanks to everybody ;)
Could this cause potential problems:
<HTML>
<BODY>
...
<INPUT name="xyz" onchange="myFunction();">
...
<SCRIPT>
function myFunction()
{
...
}
</SCRIPT>
</BODY>
</HTML>
What happens if the page loads slowly and the form renders before the script portion at the bottom is loaded? Will a JavaScript error occur if the user enters some text into the INPUT box?
You need to load the script before you can call it. Why don't you change it to something like this:
<input name="xyz" id="myInput">
...
<script>
function myFunction
{
...
}
window.onload = function() {
var myInput = document.getElementById('myInput');
myInput.onchange = myFunction;
}
</script>
This approach allows you to separate your markup and scripting and have all of your js in one place.
JavaScript development has changed over the years.
Not only is your original question being debated, but to go back to the theme of your original question, so is your methodology itself.
I highly recommend reading this short bit on some JavaScript best practices:
http://www.catswhocode.com/blog/best-practices-for-modern-javascript-development.
It works, though it may be a problem if you loaded more HTML and it took longer for the browser to parse your JavaScript at the end. In that case, your function won't be defined and you will get...
myFunction() is not defined
Note you need to add open and closing parenthesis (( & )) after myFunction.
Whilst functions declarations are hoisted, they are only hoisted in their containing script block.
Also, you should really use lowercase tags, it isn't 1998 anymore :) And a doctype also helps, and finally, you should try and remove your event handlers from inline attributes.
The script needs to be defined in the DOM prior to it being executed. If script is at the bottom it needs to be loaded prior to use.
I have a website with a form that uses TinyMCE; independently, I use jQuery. When I load the form from staging server on Firefox 3 (MacOS X, Linux), TinyMCE doesn't finish loading. There is an error in Firefox console, saying that t.getBody() returned null. t.getBody(), as far as I understand from TinyMCE docs, is a function that returns document's body element to be inspected for some features. Problem doesn't occur when I use Safari, nor when I use Firefox with the same site running from localhost.
Original, failing JavaScript-related code looked like this:
<script type="text/javascript" src="http://static.alfa.foo.pl/json2.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.ui.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({ mode:"specific_textareas", editor_selector:"mce", theme:"simple", language:"pl" });
</script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.jeditable.js"></script>
<script type="text/javascript" src="http://static.alfa.foo.pl/jquery.tinymce.js"></script>
<script type="text/javascript" charset="utf-8" src="http://static.alfa.foo.pl/foo.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ });
</script>
I tried changing script loading order, moving tinyMCE.init() call to the <script/> tag containing $(document).ready() call—before, after, and inside this call. No result. When tinyMCE.init() was called from within $(document).ready() handler, the browser did hang on request—looks like it was too late to call the init function.
Then, after googling a bit about using TinyMCE together with jQuery, I changed tinyMCE.init() call to:
tinyMCE.init({ mode:"none", theme:"simple", language:"pl" });
and added following jQuery call to the $(document).ready() handler:
$(".mce").each( function(i) { tinyMCE.execCommand("mceAddControl",true,this.id); });
Still the same error. But, and here's where things start to look like real voodoo, when I added alert(i); before the tinyMCE.execCommand() call, alerts were given, and TinyMCE textareas were initialized correctly. I figured this can be a matter of delay introduced by waiting for user dismissing the alert, so I introduced a second of delay by changing the call, still within the $(document).ready() handler, to following:
setTimeout('$(".mce").each( function(i) { tinyMCE.execCommand("mceAddControl",true,this.id); });',1000);
With the timeout, TinyMCE textareas initialize correctly, but it's duct taping around the real problem. The problem looks like an evident race condition (especially when I consider that on the same browser, but when server is on localhost, problem doesn't occur). But isn't JavaScript execution single-threaded? Could anybody please enlighten me as to what's going on here, where is the actual problem, and what can I do to have it actually fixed?
The browser executes scripts in the order they're loaded, not written. Your immediate scripts -- tinyMCE.init(...) and $(document.ready(...)); -- can execute before the files finish loading.
So, the problem is probably network latency -- especially with 6 separate scripts (each requiring a different HTTP conversation between the browser and server). So, the browser is probably trying to execute tinyMCE.init() before tiny_mce.js has finished being parsed and tinyMCE is fully defined.
If don't have Firebug, get it. ;)
It has a Net tab that will show you how long it's taking all of your scripts to load.
While you may consider the setTimeout to be duct taping, it's actually a decent solution. Only problem I see is that it assumes 1 second will always fix. A fast connection and they could see the pause. A slow connection and it doesn't wait long enough -- you still get the error.
Alternatively, you might be able to use window.onload -- assuming jQuery isn't already using it. (Can anyone else verify?)
window.onload = function () {
tinyMCE.init(...);
$(document).ready(...);
};
Also, was that a direct copy?
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ }
</script>
It's missing the ) ending ready:
<script type="text/javascript">
$(document).ready(function(){
/* jQuery initialization */ })
</script>
Missing punctuation can cause plenty of damage. The parser is just going to keep reading until it finds it -- messing up anything in between.
Since this is the first page which came in google when I asked myself the same question, this is what i found about this problem.
source
There's a callback function in tinyMCE which is fired when the component is loaded and ready. you can use it like this :
tinyMCE.init({
...
setup : function(ed) {
ed.onInit.add(function(ed) {
console.log('Editor is loaded: ' + ed.id);
});
}
});
If you are using jquery.tinymce.js then you don't need tiny_mce.js because TinyMCE will try to load it with an ajax request. If you are finding that window.tinymce (or simply tinymce) is undefined then this means that the ajax is not yet complete (which might explain why using setTimeout worked for you). This is the typical order of events:
Load jquery.js with a script tag (or google load).
Load TinyMCE's jQuery plugin, jquery.tinymce.js, with a script tag.
Document ready event fires; this is where you call .tinymce(settings) on your textareas. E.g.
$('textarea').tinymce({ script_url: '/tiny_mce/tiny_mce.js' })
Load tiny_mce.js this step is done for you by TinyMCE's jQuery plugin, but it could happen after the document ready event fires.
Sometimes you might really need to access window.tinymce, here's the safest way to do it:
$(document).tinymce({
'script_url': '/tiny_mce/tiny_mce.js'
'setup': function() {
alert(tinymce);
}
});
TinyMCE will go so far as to create a tinymce.Editor object and execute the setup callback. None of the editor's events are triggered and the editor object created for the document is not added to tinymce.editors.
I also found that TinyMCE's ajax call was interfering with my .ajaxStop functions so I also used a setTimeout:
$(document).tinymce({
'script_url': '/tiny_mce/tiny_mce.js'
'setup': function() {
setTimeout(function () {
$(document).ajaxStart(function(e) {/* stuff /});
$(document).ajaxStop(function(e) {/ stuff */});
}, 0);
}
});