Reputation: 955
I've been developing my scripts in line and now want to start moving them to a js file. However, the first script I am moving will not work from the js file.
function listEvents(url, phash) {
var hashlocation = phash.split('#')[1];
if (hashlocation === undefined) {
var page = '';
} else {
var page = hashlocation;
}
$('#events').empty().load(url + page);
}
Called from page like so;
$(window).load(function() {
listEvents('<? echo base_url(); ?>ajax/events_ajax/',window.location.hash);
});
The js file is loaded after the jquery library in the head before anyone asks. I have cleared my cache, put cloudflare into dev mode etc, and if I load the JS file in my browser I see my function. I'm not seeing any errors in the console. What am I missing?
Upvotes: 1
Views: 610
Reputation: 13412
I suppose that you would need to put your code into .ready
function:
$(document).ready(function() {
$(window).load(function() {
listEvents('<? echo base_url(); ?>ajax/events_ajax/',window.location.hash);
});
});
The problem is that when you fired your code, the content has not fully been loaded, which in your case, I think is #events
. It was not on the DOM yet and as a result ignored by jQuery. If you run it in you HTML file, most like you'd put your code right under <div id="events"></div>
(or whatever your container is) and because it was executed afterwards, that element was found and your code worked expected way!
Read more about jQuery .ready() function
.ready()
function: Specify a function to execute when the DOM is fully loaded.Upvotes: 1
Reputation: 9592
My guess is your embedded PHP <? echo base_url(); ?>
:
listEvents('<? echo base_url(); ?>ajax/events_ajax/',window.location.hash);
Check your network panel in your browser's dev tools, not just console. See if you're seeing any 404s.
If you were working with inline scripts, those are PHP, but after moving to a .js
file, the files are no longer handled by PHP.
Upvotes: 0