Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Stuart McPherson
Stuart McPherson
15,939 Points

Last Javascript function not work but does work if pasted straight into developer tools console?

Making a website on wordpress with a custom theme and I've written some Javascript.

I originally had each function in its own $(document).ready(function () { This worked fine, all javascript executed.

I know its not best practice so I set each part up in its own function and then called all the functions inside 1 $(document).ready(function () {

But now the last function called in the document ready for my sidenaviagtion isn't working. But if I copy the code and paste it into the console, it then works. It's like the last function isn't being read at all.

Any thoughts?

Below is my current code and then below that was the original code where each bit was in a document ready

Website is: http://128sqnatc.org.uk

MainNav(); is the mobile naviagtion

eventImage(); moves the event image to the top of the event div: http://128sqnatc.org.uk/events/

homepageModal(); Open a video on the homepage - button at the bottom

sideNavigationModal(); is the side nav: http://128sqnatc.org.uk/activities/team-sports/

eventDate(); positions the end date next to the start date horizontally

    // MAIN NAV
    function mainNav() {

        $("#navIcon").on('click', function(){
      $('.menu-main-menu-container').toggleClass('anim');
      $('.overlay').toggleClass('overlayZindex ');
    });

        $('.animation').click(function(){
            $('.anim').toggleClass('reverse-animation');
        })

    $('#navIcon').click(function(){
        $(this).toggleClass('open');
    });
    }


    // Move events image to top
    function eventImage() {
    setTimeout(function(){


      // Loop each li
      $( "ul.event-list-view li" ).each(function( index ) { 
        // Move image into .event-info
        $(this).prepend($(this).find(".event-details img"));
      });

      }, 10000);
    }




    // HOMEPAGE MODAL VIDEO
    function homepageModal() {
    // Get the button that opens the modal
    const btn = document.getElementById("videoBtn");

    // Get the modal
    const modal = document.getElementById("myModal");

    // Get the <span> element that closes the modal
    const span = document.getElementsByClassName("close")[0];

    btn.addEventListener('click', (event) => {
        modal.style.display ='block';
    });

    // When the user clicks on <span> (x), close the modal
    span.addEventListener('click', (event) => {
        modal.style.display ='none';
    });

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
    }



    // SIDENAV MODAL
     function sideNavigationModal() {
    // Get the button that opens the modal
    const sideBtn = document.getElementsByClassName("sideNav")[0];
    const sideBtn2 = document.getElementsByClassName("sideNav")[1];

    // Get the modal
    const sideModal = document.getElementById("sideNavModal");

    // Get the <span> element that closes the modal
    const span = document.getElementsByClassName("close")[0];

    sideBtn.addEventListener('click', (event) => {
            sideModal.style.display ='block';

     $('.sideModal').removeClass('sideNavMenuClose').addClass('sideNavMenuOpen');
            $('.header').removeClass('sideNavPageIn').addClass('sideNavPageOut');
            $('.footer').removeClass('sideNavPageIn').addClass('sideNavPageOut');
            $('.main').removeClass('sideNavPageIn').addClass('sideNavPageOut');
            $('.title').removeClass('sideNavPageIn').addClass('sideNavPageOut');
    });

    sideBtn2.addEventListener('click', (event) => {
            sideModal.style.display ='block';

   $('.sideModal').removeClass('sideNavMenuClose').addClass('sideNavMenuOpen');
    });         

    span.addEventListener('click', (event) => { 

    $('.sideModal').removeClass('sideNavMenuOpen').addClass('sideNavMenuClose');
            setTimeout(function(){
                sideModal.style.display ='none';
            }, 1500);
            $('.header').removeClass('sideNavPageOut').addClass('sideNavPageIn');
            $('.footer').removeClass('sideNavPageOut').addClass('sideNavPageIn');
            $('.main').removeClass('sideNavPageOut').addClass('sideNavPageIn');
            $('.title').removeClass('sideNavPageOut').addClass('sideNavPageIn');
    });

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == sideModal) {
            //sideModal.style.display = "none";
        }
    }

    }

    function eventDate() {

    setTimeout(function(){
        if($('.event-date').hasClass('multi-date')) {
            $(".event-date div:nth-child(2)").css({"margin-left": "3.8em"});    
        } else {

        }
    }, 4000);
    }


    $(document).ready(function () {


    eventImage();
    eventDate();    
    mainNav();  
    homepageModal();
    sideNavigationModal();

    });
    // MAIN NAV
    $(document).ready(function () {

        $("#navIcon").on('click', function(){
      $('.menu-main-menu-container').toggleClass('anim');
      $('.overlay').toggleClass('overlayZindex ');
    });

        $('.animation').click(function(){
            $('.anim').toggleClass('reverse-animation');
        })

    $('#navIcon').click(function(){
        $(this).toggleClass('open');
    });
    });


    // Move events image to top
    $(document).ready(function () {
     setTimeout(function(){


      // Loop each li
      $( "ul.event-list-view li" ).each(function( index ) { 
        // Move image into .event-info
        $(this).prepend($(this).find(".event-details img"));
      });

      }, 3000);

    });




    // HOMEPAGE MODAL VIDEO
    $(document).ready(function () {
    // Get the button that opens the modal
    const btn = document.getElementById("videoBtn");

    // Get the modal
    const modal = document.getElementById("myModal");

    // Get the <span> element that closes the modal
    const span = document.getElementsByClassName("close")[0];

    btn.addEventListener('click', (event) => {
        modal.style.display ='block';
    });

    // When the user clicks on <span> (x), close the modal
    span.addEventListener('click', (event) => {
        modal.style.display ='none';
    });

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
    });



    // SIDENAV MODAL
    $(document).ready(function () {
    // Get the button that opens the modal
    const sideBtn = document.getElementsByClassName("sideNav")[0];
    const sideBtn2 = document.getElementsByClassName("sideNav")[1];

    // Get the modal
    const sideModal = document.getElementById("sideNavModal");

    // Get the <span> element that closes the modal
    const span = document.getElementsByClassName("close")[0];

    sideBtn.addEventListener('click', (event) => {
            sideModal.style.display ='block';

    $('.sideModal').removeClass('sideNavMenuClose').addClass('sideNavMenuOpen');
            $('.header').removeClass('sideNavPageIn').addClass('sideNavPageOut');
            $('.footer').removeClass('sideNavPageIn').addClass('sideNavPageOut');
            $('.main').removeClass('sideNavPageIn').addClass('sideNavPageOut');
            $('.title').removeClass('sideNavPageIn').addClass('sideNavPageOut');
    });

    sideBtn2.addEventListener('click', (event) => {
            sideModal.style.display ='block';

    $('.sideModal').removeClass('sideNavMenuClose').addClass('sideNavMenuOpen');
    });         

    span.addEventListener('click', (event) => { 

    $('.sideModal').removeClass('sideNavMenuOpen').addClass('sideNavMenuClose');
            setTimeout(function(){
                sideModal.style.display ='none';
            }, 1500);
            $('.header').removeClass('sideNavPageOut').addClass('sideNavPageIn');
            $('.footer').removeClass('sideNavPageOut').addClass('sideNavPageIn');
            $('.main').removeClass('sideNavPageOut').addClass('sideNavPageIn');
            $('.title').removeClass('sideNavPageOut').addClass('sideNavPageIn');
    });

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == sideModal) {
            //sideModal.style.display = "none";
        }
    }

    });

 /*

    $(document).ready(function () {

    if($('.event-date').hasClass('multi-date')) {
        $(".event-date div:nth-child(2)").css({"margin-left": "3.8em"});    
    } else {

    }
    });
Stuart McPherson
Stuart McPherson
15,939 Points

Without a timeout on the eventImage(); function, it wouldn't seem to work

2 Answers

Brodey Newman
Brodey Newman
10,962 Points

Hey Stuart,

Having a hard time understanding exactly what isn't working for you. By last function, do you mean your 'sideNavigationModal' function is not working properly?

Stuart McPherson
Stuart McPherson
15,939 Points

Hi Brodey,

Ye that function, the last one I'm calling in my document ready but the code does work as when it was in its own document ready and when its pasted into the console it works. It basically makes the side nav slide in and out pushing the page to the side as it comes in.

Brodey Newman
Brodey Newman
10,962 Points

It looks like your problem is that you have your functions which are called at the bottom of your script page like below:

    eventImage();
    eventDate();    
    mainNav();  
    homepageModal();
    sideNavigationModal();

But some of these functions require elements that aren't available to the current page you're on. For example, the homepageModal function tries to grab 'document.getElementById("videoBtn");' which isn't available on the 'team-sports' page which is causing an error.

Are you by chance using the one single script file for each page? If so, you could try making a separate script.js file per page and include the specific function you need for that page. Ex( team-sports will have teamSports.js ). This wont be the best idea though, since you will have more files which requires more downloading.

Another option would be to check if the element exists in the DOM for that page, and if so, add the event listener. I'll demonstrate below.

    // HOMEPAGE MODAL VIDEO
    function homepageModal() {
         if (document.getElementById('videoBtn')) {
              // element is found..

              // Get the button that opens the modal
              const btn = document.getElementById("videoBtn");

              // Get the modal
              const modal = document.getElementById("myModal");

              // Get the <span> element that closes the modal
              const span = document.getElementsByClassName("close")[0];

              btn.addEventListener('click', (event) => {
                  modal.style.display ='block';
              });

              // When the user clicks on <span> (x), close the modal
              span.addEventListener('click', (event) => {
                  modal.style.display ='none';
              });

              // When the user clicks anywhere outside of the modal, close it
              window.onclick = function(event) {
                   if (event.target == modal) {
                       modal.style.display = "none";
                  }
              }
         } else {
             // element is not found

              return;
         }
    };

Hopefully this helps.