Separating JQuery scripts with selectors in an external file does not work?

advertisements

I have a JQuery Selector and an event associates with it.I want to keep it in external file and just copy and directly save it. The thing which I see is that the external JavaScript that has the selector does not work. Can someone explain Why?

NOTE: I am able to use the same function within my HTML file but when externalize it. It just doesn't work . The script that I have is as follows:-

 $('#pervious').click(function() {
        var presentSlide = $('.visible').attr('id');
        var tempArr = presentSlide.split("-");
        var persentSlideNo = tempArr[1];
        var perviousSlideNo = Number(persentSlideNo) - 1; if (perviousSlideNo > -1)
        {
        var perviousSlide = "Slide-" + perviousSlideNo;

            $('#' + presentSlide).fadeOut('slow',function(){
            $(this).removeClass('visible').addClass('hidden');
            });
            $('#' + perviousSlide).fadeIn('slow',function(){
            $(this).removeClass('hidden').addClass('visible');
            });
        }

    });


How are you including this script?

Note that it needs to go below the definition of your id=pervious element, or it needs to go after it (e.g. document.ready), otherwise the element won't exist, and there won't be anything to bind to.

UPDATE To restate, it needs to execute AFTER the pervious element gets created. Putting it in an external document is likely causing it to execute BEFORE the pervious HTML element is created, and therefore it doesn't work. You can put it in an external file, sure, just make certain that the element gets loaded, e.g.

$(document).ready(function() {
    $.getScript('http://yoursite.com/extrascript.js');
});