1

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?

2 Answers 2

1

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);
   });
});


Explanation:

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.
Sign up to request clarification or add additional context in comments.

4 Comments

Yes this was the problem, but it was working inline, so can you please explain why it had to be wrapped in '$(document).ready(function(){});' to make it work from external file so that I can understand this for the future. Thanks.
@IliaRostovtsev why not just get rid of the $(window).load altogether in favor of $(document).ready?
Thank you Ilia for the explanation.
@zamnuts There are bunch of other ways for achieving desired results!
0

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.

2 Comments

No the php is not in the js file. It's in the page file.
@Ally, oops yea, missed that detail in your post "Called from page like so"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.