I have a web page that redirects to another page on click. On the second page I have this:
<?php if(isset($_POST['tab1'])) { ?>
<script>$('#home').trigger('click'); </script>
<?php }?>
The $_POST
comes back ok, only I get this error in the console for the jquery:
In firebug:
TypeError: $("#home") is null
Or in Chrome:
$('#home').trigger('click');
If I run this: alert(document.getElementsByTagName('#home'));
I get a alert with: [object HTMLCollection]
as undefined
If I view the source I can see my jquery there:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script>
!window.jQuery && document.write('<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js"><\/script>');
</script>
Any ideas on why the jquery fails?
Try putting it in a document ready to ensure that the DOM is loaded before manipulating it:
<?php if(isset($_POST['tab1'])) { ?>
<script>$(function() { $('#home').trigger('click'); } );</script>
<?php }?>
FIX:
<script>$( window ).load(function() { $('#home').trigger('click'); });</script>
Put your script in the ready()
function. Try something like this:
<?php if(isset($_POST['tab1'])) { ?>
<script>$(function(){
$('#home').trigger('click');
});</script>
<?php }?>
Assuring the document loads first is critical.
<script>$(function() { $('#home').trigger('click'); });</script>
That's because by the time the script is loaded, it may be possible that #home
isn't defined yet (because the source code defining it has not yet been downloaded/parsed),
so you should make sure by enclosing it with $(function() { ... });
or $(document).ready(function() { ... });
in some setups the $ sign is not an alias for jQuery
(ex. jQuery.noConflict();
causes that)
see also Replace "$"(dollar Sign) with "JQuery"
so $(document).ready(function() { ... });
is written
jQuery(document).ready(function() { ... });
In my case, the unique solution that worked is this one I've got from here:
<script language="javascript" type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(
function() {
alert($j("selector")); //object is properly initialized
}
);
</script>
Use the jQuery.noConflict();
return variable instead of $
.